diff --git a/.gitignore b/.gitignore index 26c31c6..97a6e14 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,2 @@ -venv .idea -*.session -*.pyc -file_telegram_rxtx/tg_access.py +/tg_access.py diff --git a/LICENSE b/LICENSE index 4600e27..261eeb9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,201 @@ -MIT License + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ -Copyright (c) 2018 SlavikMIPT + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + 1. Definitions. -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index f988edd..29d9983 100644 --- a/README.md +++ b/README.md @@ -1,38 +1 @@ -# tgcloud -## UNDER DEVELOPMENT -## OpensourŅe Virtual Filesystem for Telegram -Synchronizes and structures files downloaded to Telegram. -- Stores only metadata, accessing raw data only when loading files. -- Loading speed is up to 240Mbit/s per session -- Multiplatform: provides standard volumes which can be mounted on linux/win/mac... -- Opensource -### Project structure: -**tgcloud:** linux based docker container -* **redis** - updates, rpc, communication -* **tfs:** FUSE based VFS module - * [python-fuse](https://github.com/SlavikMIPT/tfs) - interface to linux kernel FS - * redis storage - FS struct, meta, telegram file_id,settings - * rq communication interface - * docker -* **file_telegram_rxtx** - telegram read/write driver - * [telethon(sync)](https://github.com/SlavikMIPT/Telethon) by [@Lonami](https://github.com/Lonami) - telegram access, multithreaded downloading/uploading - * improved and tested by [@SlavikMIPT](https://github.com/SlavikMIPT) - load speed 240Mb/s - * rq communication interface - * docker -* **polling daemon** - * [telethon(asyncio)](https://github.com/SlavikMIPT/Telethon) - updates from telegram, synchronization, hashtags - * rq communication interface - * docker -* **client** - * telegram authorization interface - * [filebrowser](https://github.com/SlavikMIPT/filebrowser) - opensource golang filebrowser - * windows service - * telegram desktop client with filebrowser - * settings, statistics, monitoring... - * rq communication interface - * docker -![Diagram](/img/ProjectDiagram.png) - -You are welcome to collaborate - contact -Telegram: [@SlavikMIPT](t.me/SlavikMIPT) -Channel: [@MediaTube_stream](t.me/MediaTube_stream) +# tgloader \ No newline at end of file diff --git a/file_telegram_rxtx/__init__.py b/__init__.py similarity index 100% rename from file_telegram_rxtx/__init__.py rename to __init__.py diff --git a/file_telegram_rxtx/download_service.py b/download_service.py similarity index 69% rename from file_telegram_rxtx/download_service.py rename to download_service.py index 25e8758..0a72a29 100644 --- a/file_telegram_rxtx/download_service.py +++ b/download_service.py @@ -7,11 +7,15 @@ import os import shutil import time import tempfile +import mimetypes from telethon.tl.types import DocumentAttributeFilename - +from telethon.tl.types import Document +from telethon.utils import get_input_media +from telethon.errors.rpc_error_list import LocationInvalidError from telegram_client_x import TelegramClientX +from telethon.tl.types import Message from tg_access import * -from io import StringIO +from io import BytesIO import sys @@ -23,7 +27,7 @@ class Buffer: # {{{1 """ def __init__(self): - self.buf = StringIO() + self.buf = BytesIO() self.dirty = False def __getattr__(self, attr, default=None): @@ -53,8 +57,8 @@ class Buffer: # {{{1 path_home = './' # os.path.abspath('.') path_local = './local' client = TelegramClientX(entity, api_id, api_hash, update_workers=None, spawn_read_thread=True) -client.set_upload_threads_count(24) -client.set_download_threads_count(8) +client.set_upload_threads_count(24)#24 +client.set_download_threads_count(8)#8 last_call_time_sent = time.time() last_call_time_receive = time.time() @@ -78,28 +82,24 @@ def on_upload_progress(send_bytes, total_bytes): def download_block(chat_id, hash_uid): try: + hash_uid = str(hash_uid) + chat_id = str(chat_id) os.chdir(path_home) if not client.is_connected(): - client.connect() - if not client.is_user_authorized(): - client.send_code_request(phone) - client.sign_in(phone, input('Enter code: ')) - chat_id = int(chat_id) if chat_id.isdigit() else str(chat_id) + client.start() + chat_id = int(chat_id) if chat_id.isdigit() else chat_id entity = client.get_entity(chat_id) - messages = client.get_messages(entity, limit=20) - for i in range(20): + messages = client.get_messages(entity, limit=40) + for i in range(len(messages)): msg = messages[i] - if msg.message == str(hash_uid): + if msg.message == hash_uid: outbuf = tempfile.NamedTemporaryFile() - client.download_media(msg, file=outbuf, progress_callback=on_upload_progress) - + client.download_media(msg, file=outbuf, progress_callback=on_download_progress) outbuf.seek(0) sys.stdout.buffer.write(outbuf.read()) outbuf.close() return 0 - return -1 - except Exception as e: - # print(e) + except Exception: return -1 finally: client.disconnect() @@ -107,27 +107,24 @@ def download_block(chat_id, hash_uid): def upload_block(bytesin, chat_id, hash_uid): try: - filename = str(hash_uid) + hash_uid = str(hash_uid) + chat_id = str(chat_id) os.chdir(path_home) if not client.is_connected(): - client.connect() - if not client.is_user_authorized(): - client.send_code_request(phone) - client.sign_in(phone, input('Enter code: ')) - chat_id = int(chat_id) if chat_id.isdigit() else str(chat_id) + client.start() + chat_id = int(chat_id) if chat_id.isdigit() else chat_id entity = client.get_entity(chat_id) - document_attribute = [DocumentAttributeFilename(filename)] - client.send_file(entity, - file=bytesin, - caption=str(hash_uid), - file_name=filename, - allow_cache=False, - part_size_kb=512, - attributes=document_attribute, - progress_callback=on_upload_progress) + message = client.send_file(entity, + file=bytesin, + caption=f'{hash_uid}', + attributes=[DocumentAttributeFilename(f'{hash_uid}')], + allow_cache=False, + part_size_kb=512, + force_document=True, + progress_callback=on_upload_progress) + # message.id return 0 - except Exception as e: - # print(e) + except Exception: return -1 finally: client.disconnect() @@ -161,5 +158,4 @@ if __name__ == '__main__': main(sys.argv[0:]) -# upload_file(48012045,48012045,'test2.mp4','4801204577235b9d06db52e7209086ebbc8',is_gif=False) -# download_block(709766994,'012345678910abcdef') +# download_block("slavikmr","660f320161344649cd5447986a9f68fb60eb9734") \ No newline at end of file diff --git a/file_telegram_rxtx/Dockerfile b/file_telegram_rxtx/Dockerfile deleted file mode 100644 index 68346df..0000000 --- a/file_telegram_rxtx/Dockerfile +++ /dev/null @@ -1,14 +0,0 @@ -FROM jrottenberg/ffmpeg:centos -ADD . /home -WORKDIR /home - -RUN yum install -y https://centos7.iuscommunity.org/ius-release.rpm -RUN yum update -y -RUN yum install -y python36u python36u-libs python36u-devel python36u-pip - -RUN pip3.6 install -U requests[socks] -RUN pip3.6 install --upgrade -r requirements.txt -RUN cd vk_api && python3.6 setup.py install -ENTRYPOINT ["python3.6","worker.py","static.250.19.216.95.clients.your-server.de"] -#CMD ["worker.py","static.250.19.216.95.clients.your-server.de"] -#CMD ["python","worker.py","s1.mediatube.xyz"] diff --git a/file_telegram_rxtx/docker-compose.yml b/file_telegram_rxtx/docker-compose.yml deleted file mode 100644 index 1beff94..0000000 --- a/file_telegram_rxtx/docker-compose.yml +++ /dev/null @@ -1,9 +0,0 @@ -version: '2' -services: - processing: - build: . - image: slavikmipt/audiotube-worker:processing - volumes: - - /etc/nfs:/etc/nfs - restart: always - command: processing \ No newline at end of file diff --git a/file_telegram_rxtx/requirements.txt b/file_telegram_rxtx/requirements.txt deleted file mode 100644 index 2eb8ac5..0000000 --- a/file_telegram_rxtx/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -Telethon==0.18.3 -rq -requests \ No newline at end of file diff --git a/filebrowser b/filebrowser deleted file mode 160000 index eb12bf2..0000000 --- a/filebrowser +++ /dev/null @@ -1 +0,0 @@ -Subproject commit eb12bf2c2d962a6749fd199e9bf1d53650d52c59 diff --git a/requirements.txt b/requirements.txt index 2eb8ac5..a998911 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,2 @@ Telethon==0.18.3 -rq -requests \ No newline at end of file +cryptg \ No newline at end of file diff --git a/file_telegram_rxtx/telegram_client_x.py b/telegram_client_x.py similarity index 99% rename from file_telegram_rxtx/telegram_client_x.py rename to telegram_client_x.py index c4a7a5c..f3916ab 100644 --- a/file_telegram_rxtx/telegram_client_x.py +++ b/telegram_client_x.py @@ -291,10 +291,11 @@ class TelegramClientX(TelegramClient): def download_file(self, input_location, - file, + file=None, part_size_kb=None, file_size=None, progress_callback=None): + """ Downloads the given input location to a file. diff --git a/test.py b/test.py index 6b51c1c..d0e6f6a 100644 --- a/test.py +++ b/test.py @@ -7,6 +7,8 @@ try: from StringIO import StringIO except ImportError: from io import StringIO +from io import BytesIO +from download_service import download_block, upload_block import subprocess import tempfile @@ -19,7 +21,7 @@ class Buffer: # {{{1 """ def __init__(self): - self.buf = StringIO() + self.buf = BytesIO() self.dirty = False def __getattr__(self, attr, default=None): @@ -46,43 +48,34 @@ class Buffer: # {{{1 return self.buf.write(*args) -chat_id = 709766994 -user_id = 709766994 - -file_id = '012345678910abcdef' - - def get_block_from_telegram(chat_id, digest): - # path = download_block(chat_id=chat_id, uid=digest) - # buf = open('tempfile2', 'wb') - buf = tempfile.TemporaryFile() - process = Popen(["python3.6", "download_service.py", "download", str(chat_id), str(digest)], stdout=buf, bufsize=-1,shell=False) + buf = tempfile.NamedTemporaryFile() + process = Popen(["python3.6", "download_service.py", "download", str(chat_id), str(digest)], stdout=buf,shell=False) process.wait() - # buf.close() - # buf = open('tempfile2', 'rb') buf.seek(0) block = buf.read() buf.close() return block +chat_id = 123 +user_id = 123 + +file_id = 'a4ddb160d8a42a9379d6fbbd0cb72ff11efe9cb5' +# #upload +# buf = Buffer() +# with open('test.mp4','rb') as fp: +# buf = fp.read() +# import hashlib +# +# hexdigest = hashlib.sha1(buf).hexdigest() +# process = Popen(["python3.6", "download_service.py", "upload", str(chat_id), str(hexdigest)], stdin=PIPE, bufsize=-1) +# process.stdin.write(buf) +# process.stdin.close() +# process.wait() +# #download block = get_block_from_telegram(chat_id, file_id) -outfile = open('tempfile.mp3','wb') +outfile = open('tempfile_read2.mp3','wb') outfile.write(block) outfile.close() -buf = Buffer() -buf = b'12345678' -# with open('testfile.mp3','rb') as fp: -# buf = fp.read() -# -process = Popen(["python3.6", "download_service.py", "upload", str(chat_id), str(file_id)], stdin=PIPE, bufsize=-1) -process.stdin.write(buf) -process.stdin.close() -process.wait() -# upload_block(string_to_upload=buf.buf.getvalue(), chat_id=chat_id, hash_uid=str(file_id)) -# storage = shelve.open('./storage.db') -# object = get_block_from_telegram(chat_id, file_id) -# -# storage[file_id] = object -# print(storage[file_id])