├── .gitignore ├── LICENSE ├── README.md ├── setup.cfg ├── setup.py ├── test ├── __init__.py ├── config.py ├── test_comments.py ├── test_oauth.py ├── test_persons.py ├── test_playlists.py ├── test_schemas.py ├── test_searches.py ├── test_shows.py ├── test_upload.py ├── test_users.py └── test_videos.py └── youku ├── __init__.py ├── setup.cfg ├── util.py ├── youku_comments.py ├── youku_oauth.py ├── youku_persons.py ├── youku_playlists.py ├── youku_schemas.py ├── youku_searches.py ├── youku_shows.py ├── youku_upload.py ├── youku_users.py └── youku_videos.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | *.DS_Store 6 | 7 | # Video files 8 | *.srt 9 | *.sbv 10 | *.vtt 11 | *.flv 12 | *.mp4 13 | *.m4a 14 | *.m4v 15 | *.part 16 | *.swp 17 | 18 | # C extensions 19 | *.so 20 | 21 | # Distribution / packaging 22 | .Python 23 | env/ 24 | build/ 25 | develop-eggs/ 26 | dist/ 27 | downloads/ 28 | eggs/ 29 | lib/ 30 | lib64/ 31 | parts/ 32 | sdist/ 33 | var/ 34 | *.egg-info/ 35 | .installed.cfg 36 | *.egg 37 | 38 | # PyInstaller 39 | # Usually these files are written by a python script from a template 40 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 41 | *.manifest 42 | *.spec 43 | 44 | # Installer logs 45 | pip-log.txt 46 | pip-delete-this-directory.txt 47 | 48 | # Unit test / coverage reports 49 | htmlcov/ 50 | .tox/ 51 | .coverage 52 | .cache 53 | nosetests.xml 54 | coverage.xml 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # youku 2 | Youku API Python SDK / 优酷 API Python 客户端 3 | 4 | ## 功能说明 5 | 优酷 API Python 客户端比较完整地实现了优酷开放平台官方的各种 API,具体功能和对应的类分别是: 6 | * 视频上传 (Video Upload) ,支持中断续传,YoukuUpload 7 | * OAuth2 授权,YoukuOauth 8 | * 用户(users),YoukuUsers 9 | * 评论(comments),YoukuComments 10 | * 视频(videos),YoukuVideos 11 | * 节目(shows),YoukuShows 12 | * 专辑(playlists),YoukuPlaylists 13 | * 搜索(searches),YoukuSearchs 14 | * 人物(persons),YoukuPersons 15 | * 数据约束(schemas),YoukuSchemas 16 | 17 | 注:本客户端**不支持**优酷视频下载功能,一方面官方 API 就不支持,另一方面已经 18 | 有很多第三方库实现了视频下载功能。 19 | 20 | 视频(videos) 与 节目(shows) 的区别: 21 | video 是任意的视频基本信息,包括普通用户上传的,也包括优酷提供的版权视频。 22 | show 是指电影、电视剧、综艺节目等优酷自有内容。在 video 基础之上提供更多信息,如演员、导演等。 23 | 24 | 用户(users) 与 人物(persons) 的区别: 25 | user 指优酷网站上的注册用户, person 指节目中的演员、导演等特定实体。 26 | 27 | ## 开发说明 28 | 使用 pip 安装 youku: pip install youku 29 | 30 | 客户端已在 Python 2.6.x 以上测试过,兼容 Python 3 。依赖的第三方库只有 requests,使用 pip 安装时会自动安装 requests 。 31 | 32 | 各种 API 细节,如参数、返回值等请参考[优酷 API 官方文档](http://open.youku.com/docs/doc?id=0)和本项目中的源代码及测试代码,基本上都是一一对应的。 33 | 34 | 基本说明: 35 | 各个功能分别对应相应的模块。例如查询一个视频的基本信息: 36 | ```python 37 | from youku import YoukuVideos 38 | 39 | def main(): 40 | youku = YoukuVideos(CLIENT_ID) 41 | video = youku.find_video_by_id(VIDEO_ID) 42 | 43 | if __name__ == "__main__": 44 | main() 45 | ``` 46 | 47 | 48 | 上传功能使用示例: 49 | ```python 50 | from youku import YoukuUpload 51 | 52 | def main(): 53 | file_info = { 54 | 'title': u'Google I/O 2014', 55 | 'tags': 'Google,IO', 56 | 'description': 'I/O Keynote' 57 | } 58 | file = '/home/hanguokai/filename.mp4' 59 | youku = YoukuUpload(CLIENT_ID, ACCESS_TOKEN, file) 60 | youku.upload(file_info) 61 | 62 | if __name__ == "__main__": 63 | main() 64 | ``` 65 | 66 | client_id 在[这里](http://cloud.youku.com/app)获取。 67 | access_token 可以从[这里](http://cloud.youku.com/tools)手工获取。 68 | 69 | 因为上传包含内部状态,所以每个上传文件需要新建一个 YoukuUpload 对象,并在一个线程中执行。 70 | 其它各功能 API 都是简单的无状态 REST 调用,所有请求只需要构建一个对象使用即可。 71 | 72 | 异常处理,所有功能产生的异常都会抛出 YoukuError 异常对象,表示优酷官方定义的异常。异常对象包括如下属性 73 | * status_code,返回的 HTTP 状态码 74 | * code,错误码 75 | * type,错误类型 76 | * description,错误描述 77 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hanguokai/youku/8032710902411f92e1ae3f280eb121fd7231983b/setup.cfg -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | 4 | setup( 5 | name='youku', 6 | version='0.1.1', 7 | description='Youku open api python client and video uploader', 8 | long_description='Youku open api python client,' 9 | ' support video upload and other api, do not support video download.', 10 | url='https://github.com/hanguokai/youku', 11 | author='Guokai Han', 12 | author_email='han.guokai@gmail.com', 13 | packages=['youku'], 14 | keywords='youku api upload video', 15 | install_requires=['requests'], 16 | 17 | classifiers=[ 18 | "Topic :: Multimedia :: Video", 19 | "Development Status :: 4 - Beta", 20 | "Environment :: Console", 21 | "License :: OSI Approved :: Apache Software License", 22 | "Programming Language :: Python" 23 | ], 24 | ) 25 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hanguokai/youku/8032710902411f92e1ae3f280eb121fd7231983b/test/__init__.py -------------------------------------------------------------------------------- /test/config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import json 3 | 4 | # data for test, please replace it to yours 5 | CLIENT_ID = 'your client id' 6 | CLIENT_SECRET = 'your client secret' 7 | REDIRECT_URI = 'http://127.0.0.1:5000/youku/authorize' 8 | ACCESS_TOKEN = 'your access token' 9 | USER_ID = '419384312' 10 | USER_NAME = u'\u97e9\u56fd\u607a' 11 | 12 | 13 | def print_json(obj): 14 | print json.dumps(obj, indent=4, sort_keys=True) 15 | -------------------------------------------------------------------------------- /test/test_comments.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 | 6 | import unittest 7 | import random 8 | import string 9 | from config import * 10 | from youku import YoukuComments 11 | 12 | VIDEO_ID = 'XODY3Njc0OTA4' 13 | # random content 14 | CONTENT = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) 15 | 16 | 17 | class CommentsTest(unittest.TestCase): 18 | def setUp(self): 19 | self.youku = YoukuComments(CLIENT_ID) 20 | 21 | def test(self): 22 | comm = self.youku.find_comments_by_video(VIDEO_ID) 23 | self.assertIsNotNone(comm['total']) 24 | 25 | comm1 = self.youku.find_comment_by_id(comm['comments'][0]['id']) 26 | self.assertIsNotNone(comm1) 27 | 28 | comm2 = self.youku.find_comments_by_ids(comm1['id']) 29 | self.assertEqual(comm2['total'], 1) 30 | 31 | hot_comm = self.youku.find_hot_comments_by_video(VIDEO_ID) 32 | self.assertIsNotNone(hot_comm) 33 | 34 | comm_by_me = self.youku.find_comments_by_me(ACCESS_TOKEN) 35 | self.assertIsNotNone(comm_by_me) 36 | 37 | # comm_by_me = self.youku.find_comments_by_mention_me(ACCESS_TOKEN) 38 | # self.assertIsNotNone(comm_by_me) 39 | 40 | # comm_by_me = self.youku.find_comments_by_reply_me(ACCESS_TOKEN) 41 | # self.assertIsNotNone(comm_by_me) 42 | 43 | # comm_by_me = self.youku.find_comments_by_to_me(ACCESS_TOKEN) 44 | # self.assertIsNotNone(comm_by_me) 45 | 46 | 47 | if __name__ == '__main__': 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /test/test_oauth.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 | 6 | import unittest 7 | from config import * 8 | from youku import YoukuOauth 9 | 10 | 11 | class OauthTest(unittest.TestCase): pass 12 | # TODO 13 | 14 | if __name__ == '__main__': 15 | unittest.main() 16 | -------------------------------------------------------------------------------- /test/test_persons.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 | 6 | import unittest 7 | from config import * 8 | from youku import YoukuPersons 9 | 10 | PERSON_ID = '11366' 11 | 12 | 13 | class PersonsTest(unittest.TestCase): 14 | 15 | def setUp(self): 16 | self.youku = YoukuPersons(CLIENT_ID) 17 | 18 | def test_find_person_by_id(self): 19 | pserson = self.youku.find_person_by_id(PERSON_ID) 20 | self.assertIsNotNone(pserson['name']) 21 | 22 | def test_find_persons_by_ids(self): 23 | result = self.youku.find_persons_by_ids(PERSON_ID) 24 | self.assertGreater(result['total'], 0) 25 | 26 | def test_find_persons_by_type(self): 27 | result = self.youku.find_persons_by_type('performer') 28 | self.assertGreater(result['total'], 0) 29 | 30 | 31 | if __name__ == '__main__': 32 | unittest.main() 33 | -------------------------------------------------------------------------------- /test/test_playlists.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 | 6 | import unittest 7 | from config import * 8 | from youku import YoukuPlaylists 9 | 10 | PL_ID = '23331739' 11 | VIDEO_ID = 'XODY3NDU2MzY4' 12 | 13 | 14 | class PlaylistsTest(unittest.TestCase): 15 | 16 | def setUp(self): 17 | self.youku = YoukuPlaylists(CLIENT_ID) 18 | 19 | def test_find_playlist_by_id(self): 20 | pl = self.youku.find_playlist_by_id(PL_ID) 21 | self.assertIsNotNone(pl['name']) 22 | 23 | def test_find_playlists_by_ids(self): 24 | pl = self.youku.find_playlists_by_ids(PL_ID) 25 | self.assertGreater(pl['total'], 0) 26 | 27 | def test_find_playlists_by_category(self): 28 | pl = self.youku.find_playlists_by_category( 29 | u'资讯', period='month') 30 | self.assertGreater(pl['total'], 0) 31 | 32 | def test_find_playlists_by_me(self): 33 | pl = self.youku.find_playlists_by_me(ACCESS_TOKEN) 34 | self.assertIsNotNone(pl['total']) 35 | 36 | def test_find_playlists_by_userid(self): 37 | pl = self.youku.find_playlists_by_userid(USER_ID) 38 | self.assertIsNotNone(pl['total']) 39 | 40 | def test_find_playlists_by_username(self): 41 | pl = self.youku.find_playlists_by_username(USER_NAME) 42 | self.assertIsNotNone(pl['total']) 43 | 44 | def test_find_videos_by_playlist(self): 45 | pl = self.youku.find_videos_by_playlist(PL_ID) 46 | self.assertIsNotNone(pl['total']) 47 | 48 | def test_playlist_crud(self): 49 | pid = self.youku.create_playlist(ACCESS_TOKEN, 50 | 'title', 51 | 'test,other', 52 | description='description') 53 | pid = self.youku.update_playlist(ACCESS_TOKEN, pid, 'update title') 54 | pid = self.youku.add_videos_to_playlist(ACCESS_TOKEN, pid, VIDEO_ID) 55 | pid = self.youku.add_videos_to_playlist(ACCESS_TOKEN, pid, 56 | 'XODY4MzMyMzA4') 57 | pid = self.youku.set_cover_video_for_playlist(ACCESS_TOKEN, 58 | pid, VIDEO_ID) 59 | self.youku.find_next_video_in_playlist(pid, VIDEO_ID) 60 | pid = self.youku.del_videos_from_playlist(ACCESS_TOKEN, pid, VIDEO_ID) 61 | pid = self.youku.destroy_playlist(ACCESS_TOKEN, pid) 62 | 63 | if __name__ == '__main__': 64 | unittest.main() 65 | -------------------------------------------------------------------------------- /test/test_schemas.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 | 6 | import unittest 7 | from config import * 8 | from youku import YoukuSchemas 9 | 10 | 11 | class SchemasTest(unittest.TestCase): 12 | 13 | def setUp(self): 14 | self.youku = YoukuSchemas(CLIENT_ID) 15 | 16 | def test_video_category(self): 17 | result = self.youku.video_category() 18 | self.assertIsNotNone(result['categories']) 19 | 20 | def test_upload_spec(self): 21 | result = self.youku.upload_spec() 22 | self.assertIsNotNone(result['allowed_max_file_size']) 23 | 24 | def test_comment_expression(self): 25 | result = self.youku.comment_expression() 26 | self.assertIsNotNone(result['expressions']) 27 | 28 | def test_show_category(self): 29 | result = self.youku.show_category() 30 | self.assertIsNotNone(result['categories']) 31 | 32 | def test_playlist_category(self): 33 | result = self.youku.playlist_category() 34 | # This return category not categories, maybe a bug 35 | self.assertIsNotNone(result['category']) 36 | 37 | def test_searche_top_category(self): 38 | result = self.youku.searche_top_category() 39 | self.assertIsNotNone(result['categories']) 40 | 41 | 42 | if __name__ == '__main__': 43 | unittest.main() 44 | -------------------------------------------------------------------------------- /test/test_searches.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 | 6 | import unittest 7 | from config import * 8 | from youku import YoukuSearchs 9 | 10 | 11 | class SearchsTest(unittest.TestCase): 12 | def setUp(self): 13 | self.youku = YoukuSearchs(CLIENT_ID) 14 | 15 | def test_search_videos_by_tag(self): 16 | result = self.youku.search_videos_by_tag('Google') 17 | self.assertGreater(result['total'], 0) 18 | 19 | def test_search_videos_by_keyword(self): 20 | result = self.youku.search_videos_by_keyword('Google') 21 | self.assertGreater(result['total'], 0) 22 | 23 | def test_search_shows_by_keyword(self): 24 | result = self.youku.search_shows_by_keyword(u'柯南') 25 | self.assertGreater(result['total'], 0) 26 | 27 | def test_search_keyword_complete(self): 28 | result = self.youku.search_keyword_complete(u'柯南') 29 | self.assertGreater(result['total'], 0) 30 | 31 | def test_search_keyword_top(self): 32 | result = self.youku.search_keyword_top() 33 | self.assertGreater(result['total'], 0) 34 | 35 | def test_search_show_address_unite(self): 36 | result = self.youku.search_show_address_unite('54624') 37 | self.assertIsNotNone(result) 38 | 39 | def test_search_show_top_unite(self): 40 | result = self.youku.search_show_top_unite(u'电视剧') 41 | self.assertIsNotNone(result) 42 | 43 | 44 | if __name__ == '__main__': 45 | unittest.main() 46 | -------------------------------------------------------------------------------- /test/test_shows.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 | 6 | import unittest 7 | from config import * 8 | from youku import YoukuShows 9 | 10 | SHOW_ID = 'zeebadce421c911e4a705' 11 | 12 | 13 | class ShowsTest(unittest.TestCase): 14 | 15 | def setUp(self): 16 | self.youku = YoukuShows(CLIENT_ID) 17 | 18 | def test_find_show_by_id(self): 19 | show = self.youku.find_show_by_id(SHOW_ID) 20 | self.assertIsNotNone(show['name']) 21 | 22 | def test_find_shows_by_ids(self): 23 | show = self.youku.find_shows_by_ids(SHOW_ID) 24 | self.assertGreater(show['total'], 0) 25 | 26 | def test_find_show_premium_by_ids(self): 27 | show = self.youku.find_show_premium_by_ids(SHOW_ID) 28 | self.assertGreater(show['total'], 0) 29 | 30 | def test_find_shows_by_category(self): 31 | show = self.youku.find_shows_by_category(u'电视剧', u'古装') 32 | self.assertGreater(show['total'], 0) 33 | 34 | def test_find_shows_by_related(self): 35 | show = self.youku.find_shows_by_related(SHOW_ID) 36 | self.assertIsNotNone(show['total']) 37 | 38 | def test_find_videos_by_show(self): 39 | show = self.youku.find_videos_by_show(SHOW_ID) 40 | self.assertGreater(show['total'], 0) 41 | 42 | if __name__ == '__main__': 43 | unittest.main() 44 | -------------------------------------------------------------------------------- /test/test_upload.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 | 6 | import unittest 7 | from config import * 8 | from youku import YoukuUpload 9 | 10 | 11 | class UploadTest(unittest.TestCase): 12 | def setUp(self): 13 | self.file_info = { 14 | 'title': u'测试优酷Python客户端上传', 15 | 'tags': 'other', 16 | 'description': 'Polymer video #7' 17 | # 'category': 'Tech' 18 | } 19 | 20 | def test_upload(self): 21 | UPLOAD_FILE = 'f3659211207n.mp4' 22 | youku = YoukuUpload(CLIENT_ID, ACCESS_TOKEN, UPLOAD_FILE) 23 | 24 | # youku.create(youku.prepare_video_params(**params)) 25 | # youku.create_file() 26 | # youku.upload_slice() 27 | # youku.check() 28 | # youku.commit() 29 | # youku.cancel() 30 | # youku.spec() 31 | youku.upload(self.file_info) 32 | 33 | 34 | if __name__ == '__main__': 35 | unittest.main() 36 | -------------------------------------------------------------------------------- /test/test_users.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 | 6 | import unittest 7 | from config import * 8 | from youku import YoukuUsers 9 | 10 | 11 | class UserTest(unittest.TestCase): 12 | def setUp(self): 13 | self.youku = YoukuUsers(CLIENT_ID) 14 | 15 | def test_my_info(self): 16 | me = self.youku.my_info(ACCESS_TOKEN) 17 | self.assertIn('id', me) 18 | 19 | def test_by_id(self): 20 | user = self.youku.find_user_by_id('419384312') 21 | self.assertEqual(user['name'], u'韩国恺') 22 | 23 | def test_by_ids(self): 24 | users = self.youku.find_users_by_ids('419384312,155482632') 25 | self.assertEqual(users['total'], 2) 26 | 27 | def test_by_name(self): 28 | user = self.youku.find_user_by_name(u'GDGBeijing') 29 | self.assertEqual(user['id'], '155482632') 30 | 31 | def test_by_names(self): 32 | users = self.youku.find_users_by_names(u'GDGBeijing,韩国恺') 33 | self.assertEqual(users['total'], 2) 34 | 35 | def test_friendship_followings(self): 36 | users = self.youku.friendship_followings(user_id='419384312') 37 | self.assertIn('total', users) 38 | 39 | def test_friendship_followers(self): 40 | users = self.youku.friendship_followers(user_name='GDGBeijing') 41 | self.assertIn('total', users) 42 | 43 | def test_friendship_create_destroy(self): 44 | self.youku.create_friendship(ACCESS_TOKEN, user_name='GDGBeijing') 45 | self.youku.destroy_friendship(ACCESS_TOKEN, user_name='GDGBeijing') 46 | 47 | def test_subscribe_create_cancel(self): 48 | self.assertTrue(self.youku.create_subscribe(ACCESS_TOKEN, 49 | '2a7260de1faa11e097c0')) 50 | self.assertTrue(self.youku.cancel_subscribe(ACCESS_TOKEN, 51 | '2a7260de1faa11e097c0')) 52 | 53 | def test_subscribe_get(self): 54 | self.assertIn('total', self.youku.subscribe_get(ACCESS_TOKEN)) 55 | 56 | def test_subscribe_notice(self): 57 | self.assertIn('total', self.youku.subscribe_notice(ACCESS_TOKEN)) 58 | 59 | if __name__ == '__main__': 60 | unittest.main() 61 | -------------------------------------------------------------------------------- /test/test_videos.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 | 6 | import unittest 7 | from config import * 8 | from youku import YoukuVideos 9 | 10 | VIDEO_ID = 'XODY3NDU2MzY4' 11 | VIDEO_URL = 'http://v.youku.com/v_show/id_XODY3NDU2MzY4.html' 12 | 13 | 14 | class VideosTest(unittest.TestCase): 15 | 16 | def setUp(self): 17 | self.youku = YoukuVideos(CLIENT_ID) 18 | 19 | def test_find_by_id(self): 20 | video = self.youku.find_video_by_id(VIDEO_ID) 21 | self.assertIsNotNone(video) 22 | 23 | def test_find_by_url(self): 24 | video = self.youku.find_video_by_url(VIDEO_URL) 25 | self.assertIsNotNone(video) 26 | 27 | def test_find_by_ids(self): 28 | video = self.youku.find_videos_by_ids(VIDEO_ID) 29 | self.assertIsNotNone(video['total']) 30 | 31 | def test_find_video_detail_by_id(self): 32 | video = self.youku.find_video_detail_by_id(VIDEO_ID) 33 | self.assertIsNotNone(video) 34 | 35 | def test_find_video_details_by_ids(self): 36 | video = self.youku.find_video_details_by_ids(VIDEO_ID) 37 | self.assertIsNotNone(video['total']) 38 | 39 | def test_find_videos_by_me(self): 40 | video = self.youku.find_videos_by_me(ACCESS_TOKEN) 41 | self.assertIsNotNone(video['total']) 42 | 43 | def test_find_videos_by_userid(self): 44 | video = self.youku.find_videos_by_userid(USER_ID) 45 | self.assertIsNotNone(video['total']) 46 | 47 | def test_find_videos_by_username(self): 48 | video = self.youku.find_videos_by_username(USER_NAME) 49 | self.assertIsNotNone(video['total']) 50 | 51 | def test_update_video(self): 52 | vid = self.youku.update_video(ACCESS_TOKEN, VIDEO_ID, 'update title') 53 | self.assertIsNotNone(vid) 54 | 55 | # def test_destroy_video(self): 56 | # vid = self.youku.destroy_video(ACCESS_TOKEN, 'XODY3MzI5NDM2') 57 | # self.assertIsNotNone(vid) 58 | 59 | def test_find_videos_by_related(self): 60 | video = self.youku.find_videos_by_related(VIDEO_ID) 61 | self.assertIsNotNone(video['total']) 62 | 63 | def test_find_favorite_videos_by_me(self): 64 | video = self.youku.find_favorite_videos_by_me(ACCESS_TOKEN) 65 | self.assertIsNotNone(video['total']) 66 | 67 | def test_find_favorite_videos_by_userid(self): 68 | video = self.youku.find_favorite_videos_by_userid(USER_ID) 69 | self.assertIsNotNone(video['total']) 70 | 71 | def test_find_favorite_videos_by_username(self): 72 | video = self.youku.find_favorite_videos_by_username(USER_NAME) 73 | self.assertIsNotNone(video['total']) 74 | 75 | def test_create_favorite_video(self): 76 | vid = self.youku.create_favorite_video(ACCESS_TOKEN, VIDEO_ID) 77 | self.assertIsNotNone(vid) 78 | 79 | def test_destroy_favorite_video(self): 80 | vid = self.youku.destroy_favorite_video(ACCESS_TOKEN, VIDEO_ID) 81 | self.assertIsNotNone(vid) 82 | 83 | def test_find_videos_by_category(self): 84 | video = self.youku.find_favorite_videos_by_username(u'资讯', u'社会资讯') 85 | self.assertIsNotNone(video['total']) 86 | 87 | 88 | if __name__ == '__main__': 89 | unittest.main() 90 | -------------------------------------------------------------------------------- /youku/__init__.py: -------------------------------------------------------------------------------- 1 | from .util import YoukuError 2 | from .youku_upload import YoukuUpload 3 | from .youku_comments import YoukuComments 4 | from .youku_oauth import YoukuOauth 5 | from .youku_persons import YoukuPersons 6 | from .youku_playlists import YoukuPlaylists 7 | from .youku_schemas import YoukuSchemas 8 | from .youku_searches import YoukuSearchs 9 | from .youku_shows import YoukuShows 10 | from .youku_users import YoukuUsers 11 | from .youku_videos import YoukuVideos 12 | -------------------------------------------------------------------------------- /youku/setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md -------------------------------------------------------------------------------- /youku/util.py: -------------------------------------------------------------------------------- 1 | try: 2 | # Python 3 3 | from urllib.parse import parse_qs 4 | except ImportError: 5 | # Python 2 6 | from urlparse import parse_qs 7 | 8 | 9 | def check_error(response, expect_status=200): 10 | """ 11 | Youku error should return as json response, like: 12 | HTTP 400 13 | { 14 | "error":{ 15 | "code":120010223, 16 | "type":"UploadsException", 17 | "description":"Expired upload token" 18 | } 19 | } 20 | 21 | But error also maybe in response url params or response body. 22 | 23 | Content-Type maybe application/json or text/plain. 24 | 25 | Args: 26 | expect_status: normally is 200 or 201 27 | """ 28 | json = None 29 | try: 30 | json = response.json() 31 | except: 32 | pass 33 | if (response.status_code != expect_status or 34 | response.status_code == 400 or 35 | 'error' in json): 36 | if json: 37 | error = json['error'] 38 | raise YoukuError(error.get('code', ''), error.get('type', ''), 39 | error.get('description', ''), response.status_code) 40 | else: 41 | # try to parse error from body 42 | error = parse_qs(response.text) 43 | raise YoukuError(error.get('code', [None])[0], 44 | error.get('type', [None])[0], 45 | error.get('description', [None])[0], 46 | response.status_code) 47 | 48 | 49 | def remove_none_value(data): 50 | """remove item from dict if value is None. 51 | return new dict. 52 | """ 53 | return dict((k, v) for k, v in data.items() if v is not None) 54 | 55 | 56 | class YoukuError(Exception): 57 | 58 | """ Youku error. 59 | It has three attributes: code, type, description. 60 | http://open.youku.com/docs/upload_client_chinese.html#error-definition 61 | """ 62 | 63 | def __init__(self, code, _type, description, status_code): 64 | self.code = code 65 | self.type = _type 66 | self.description = description 67 | self.status_code = status_code 68 | 69 | def __str__(self): 70 | return ("http_status: %s, error: %s, %s, %s" % 71 | (self.status_code, self.code, self.type, self.description)) 72 | -------------------------------------------------------------------------------- /youku/youku_comments.py: -------------------------------------------------------------------------------- 1 | """Youku Open API V2 Python Client 2 | 3 | doc: http://open.youku.com/docs/tech_doc.html 4 | """ 5 | 6 | import requests 7 | from .util import check_error, remove_none_value 8 | 9 | 10 | class YoukuComments(object): 11 | 12 | """Youku Comments API. Not yet implemented. 13 | 14 | doc: http://open.youku.com/docs/api_comments.html 15 | """ 16 | 17 | def __init__(self, client_id): 18 | super(YoukuComments, self).__init__() 19 | self.client_id = client_id 20 | 21 | def find_comment_by_id(self, comment_id): 22 | """doc: http://open.youku.com/docs/doc?id=32 23 | """ 24 | url = 'https://openapi.youku.com/v2/comments/show.json' 25 | params = { 26 | 'client_id': self.client_id, 27 | 'comment_id': comment_id 28 | } 29 | r = requests.get(url, params=params) 30 | check_error(r) 31 | return r.json() 32 | 33 | def find_comments_by_ids(self, comment_ids): 34 | """doc: http://open.youku.com/docs/doc?id=34 35 | """ 36 | url = 'https://openapi.youku.com/v2/comments/show_batch.json' 37 | params = { 38 | 'client_id': self.client_id, 39 | 'comment_ids': comment_ids 40 | } 41 | r = requests.get(url, params=params) 42 | check_error(r) 43 | return r.json() 44 | 45 | def find_comments_by_video(self, video_id, page=1, count=20): 46 | """doc: http://open.youku.com/docs/doc?id=35 47 | """ 48 | url = 'https://openapi.youku.com/v2/comments/by_video.json' 49 | params = { 50 | 'client_id': self.client_id, 51 | 'video_id': video_id, 52 | 'page': page, 53 | 'count': count 54 | } 55 | r = requests.get(url, params=params) 56 | check_error(r) 57 | return r.json() 58 | 59 | def find_hot_comments_by_video(self, video_id, page=1, count=20): 60 | """doc: http://open.youku.com/docs/doc?id=36 61 | """ 62 | url = 'https://openapi.youku.com/v2/comments/hot/by_video.json' 63 | params = { 64 | 'client_id': self.client_id, 65 | 'video_id': video_id, 66 | 'page': page, 67 | 'count': count 68 | } 69 | r = requests.get(url, params=params) 70 | check_error(r) 71 | return r.json() 72 | 73 | def find_comments_by_me(self, access_token, page=1, count=20): 74 | """doc: http://open.youku.com/docs/doc?id=37 75 | """ 76 | url = 'https://openapi.youku.com/v2/comments/by_me.json' 77 | data = { 78 | 'client_id': self.client_id, 79 | 'access_token': access_token, 80 | 'page': page, 81 | 'count': count 82 | } 83 | r = requests.post(url, data=data) 84 | check_error(r) 85 | return r.json() 86 | 87 | def find_comments_by_mention_me(self, access_token, page=1, count=20): 88 | """doc: http://open.youku.com/docs/doc?id=38 89 | """ 90 | url = 'https://openapi.youku.com/v2/comments/by_mention_me.json' 91 | data = { 92 | 'client_id': self.client_id, 93 | 'access_token': access_token, 94 | 'page': page, 95 | 'count': count 96 | } 97 | r = requests.post(url, data=data) 98 | check_error(r) 99 | return r.json() 100 | 101 | def find_comments_by_reply_me(self, access_token, page=1, count=20): 102 | """doc: http://open.youku.com/docs/doc?id=39 103 | """ 104 | url = 'https://openapi.youku.com/v2/comments/by_reply_me.json' 105 | data = { 106 | 'client_id': self.client_id, 107 | 'access_token': access_token, 108 | 'page': page, 109 | 'count': count 110 | } 111 | r = requests.post(url, data=data) 112 | check_error(r) 113 | return r.json() 114 | 115 | def find_comments_by_to_me(self, access_token, page=1, count=20): 116 | """doc: http://open.youku.com/docs/doc?id=40 117 | """ 118 | url = 'https://openapi.youku.com/v2/comments/to_me.json' 119 | data = { 120 | 'client_id': self.client_id, 121 | 'access_token': access_token, 122 | 'page': page, 123 | 'count': count 124 | } 125 | r = requests.post(url, data=data) 126 | check_error(r) 127 | return r.json() 128 | 129 | def create_comment(self, access_token, video_id, content, 130 | reply_id=None, captcha_key=None, captcha_text=None): 131 | """doc: http://open.youku.com/docs/doc?id=41 132 | """ 133 | url = 'https://openapi.youku.com/v2/comments/create.json' 134 | data = { 135 | 'client_id': self.client_id, 136 | 'access_token': access_token, 137 | 'video_id': video_id, 138 | 'content': content, 139 | 'reply_id': reply_id, 140 | 'captcha_key': captcha_key, 141 | 'captcha_text': captcha_text 142 | } 143 | data = remove_none_value(data) 144 | r = requests.post(url, data=data) 145 | check_error(r) 146 | return r.json()['id'] 147 | 148 | def destroy_comment(self, access_token, comment_id): 149 | """doc: http://open.youku.com/docs/doc?id=42 150 | """ 151 | url = 'https://openapi.youku.com/v2/comments/destroy.json' 152 | data = { 153 | 'client_id': self.client_id, 154 | 'access_token': access_token, 155 | 'comment_id': comment_id 156 | } 157 | r = requests.post(url, data=data) 158 | check_error(r) 159 | return r.json()['id'] 160 | -------------------------------------------------------------------------------- /youku/youku_oauth.py: -------------------------------------------------------------------------------- 1 | """Youku Open API V2 Python Client 2 | 3 | doc: http://open.youku.com/docs/tech_doc.html 4 | """ 5 | import requests 6 | try: 7 | # Python 3 8 | from urllib.parse import urlencode 9 | except ImportError: 10 | # Python 2 11 | from urllib import urlencode 12 | from .util import check_error 13 | 14 | 15 | class YoukuOauth(object): 16 | 17 | """Youku Oauth API. 18 | 19 | doc: http://cloud.youku.com/docs?id=100 20 | """ 21 | 22 | def __init__(self, client_id, client_secret, redirect_uri): 23 | super(YoukuOauth, self).__init__() 24 | self.client_id = client_id 25 | self.client_secret = client_secret 26 | self.redirect_uri = redirect_uri 27 | 28 | def authorize_url(self, state=''): 29 | """ return user authorize url 30 | """ 31 | url = 'https://openapi.youku.com/v2/oauth2/authorize?' 32 | params = { 33 | 'client_id': self.client_id, 34 | 'response_type': 'code', 35 | 'state': state, 36 | 'redirect_uri': self.redirect_uri 37 | } 38 | return url + urlencode(params) 39 | 40 | def get_token_by_code(self, code): 41 | '''return origin json''' 42 | url = 'https://openapi.youku.com/v2/oauth2/token' 43 | data = {'client_id': self.client_id, 44 | 'client_secret': self.client_secret, 45 | 'grant_type': 'authorization_code', 46 | 'code': code, 47 | 'redirect_uri': self.redirect_uri} 48 | r = requests.post(url, data=data) 49 | check_error(r) 50 | return r.json() 51 | 52 | def refresh_token(self, refresh_token): 53 | '''return origin json''' 54 | url = 'https://api.youku.com/oauth2/token.json' 55 | data = {'client_id': self.client_id, 56 | 'grant_type': 'refresh_token', 57 | 'refresh_token': refresh_token} 58 | r = requests.post(url, data=data) 59 | check_error(r) 60 | return r.json() 61 | -------------------------------------------------------------------------------- /youku/youku_persons.py: -------------------------------------------------------------------------------- 1 | """Youku Open API V2 Python Client 2 | 3 | doc: http://open.youku.com/docs/tech_doc.html 4 | """ 5 | 6 | import requests 7 | from .util import check_error, remove_none_value 8 | 9 | 10 | class YoukuPersons(object): 11 | 12 | """Youku Persons API. 13 | """ 14 | 15 | def __init__(self, client_id): 16 | super(YoukuPersons, self).__init__() 17 | self.client_id = client_id 18 | 19 | def find_person_by_id(self, person_id): 20 | """doc: http://open.youku.com/docs/docs?id=87 21 | """ 22 | url = 'https://openapi.youku.com/v2/persons/show.json' 23 | params = { 24 | 'client_id': self.client_id, 25 | 'person_id': person_id 26 | } 27 | r = requests.get(url, params=params) 28 | check_error(r) 29 | return r.json() 30 | 31 | def find_persons_by_ids(self, person_ids): 32 | """doc: http://open.youku.com/docs/docs?id=88 33 | """ 34 | url = 'https://openapi.youku.com/v2/persons/show_batch.json' 35 | params = { 36 | 'client_id': self.client_id, 37 | 'person_ids': person_ids 38 | } 39 | r = requests.get(url, params=params) 40 | check_error(r) 41 | return r.json() 42 | 43 | def find_persons_by_type(self, type, nationality=None, gender=None, 44 | firstletter=None, orderby='view-week-count', 45 | page=1, count=20): 46 | """doc: http://open.youku.com/docs/docs?id=89 47 | """ 48 | url = 'https://openapi.youku.com/v2/persons/by_type.json' 49 | params = { 50 | 'client_id': self.client_id, 51 | 'type': type, 52 | 'nationality': nationality, 53 | 'gender': gender, 54 | 'firstletter': firstletter, 55 | 'orderby': orderby, 56 | 'page': page, 57 | 'count': count 58 | } 59 | params = remove_none_value(params) 60 | r = requests.get(url, params=params) 61 | check_error(r) 62 | return r.json() 63 | -------------------------------------------------------------------------------- /youku/youku_playlists.py: -------------------------------------------------------------------------------- 1 | """Youku Open API V2 Python Client 2 | 3 | doc: http://open.youku.com/docs/tech_doc.html 4 | """ 5 | 6 | import requests 7 | from .util import check_error, remove_none_value 8 | 9 | 10 | class YoukuPlaylists(object): 11 | 12 | """Youku Playlists API. 13 | 14 | doc: http://open.youku.com/docs/api_playlists.html 15 | """ 16 | 17 | def __init__(self, client_id): 18 | super(YoukuPlaylists, self).__init__() 19 | self.client_id = client_id 20 | 21 | def find_playlist_by_id(self, playlist_id): 22 | """doc: http://open.youku.com/docs/doc?id=66 23 | """ 24 | url = 'https://openapi.youku.com/v2/playlists/show.json' 25 | params = { 26 | 'client_id': self.client_id, 27 | 'playlist_id': playlist_id 28 | } 29 | r = requests.get(url, params=params) 30 | check_error(r) 31 | return r.json() 32 | 33 | def find_playlists_by_ids(self, playlist_ids): 34 | """doc: http://open.youku.com/docs/doc?id=67 35 | """ 36 | url = 'https://openapi.youku.com/v2/playlists/show_batch.json' 37 | params = { 38 | 'client_id': self.client_id, 39 | 'playlist_ids': playlist_ids 40 | } 41 | r = requests.get(url, params=params) 42 | check_error(r) 43 | return r.json() 44 | 45 | def find_playlists_by_category(self, category, period='today', 46 | orderby='published', page=1, count=20): 47 | """doc: http://open.youku.com/docs/doc?id=68 48 | """ 49 | url = 'https://openapi.youku.com/v2/playlists/by_category.json' 50 | params = { 51 | 'client_id': self.client_id, 52 | 'category': category, 53 | 'period': period, 54 | 'orderby': orderby, 55 | 'page': page, 56 | 'count': count 57 | } 58 | r = requests.get(url, params=params) 59 | check_error(r) 60 | return r.json() 61 | 62 | def find_playlists_by_me(self, access_token, 63 | orderby='published', page=1, count=20): 64 | """doc: http://open.youku.com/docs/doc?id=69 65 | """ 66 | url = 'https://openapi.youku.com/v2/playlists/by_me.json' 67 | params = { 68 | 'client_id': self.client_id, 69 | 'access_token': access_token, 70 | 'orderby': orderby, 71 | 'page': page, 72 | 'count': count 73 | } 74 | r = requests.get(url, params=params) 75 | check_error(r) 76 | return r.json() 77 | 78 | def find_playlists_by_userid(self, user_id, 79 | orderby='published', page=1, count=20): 80 | """doc: http://open.youku.com/docs/doc?id=70 81 | """ 82 | url = 'https://openapi.youku.com/v2/playlists/by_user.json' 83 | params = { 84 | 'client_id': self.client_id, 85 | 'user_id': user_id, 86 | 'orderby': orderby, 87 | 'page': page, 88 | 'count': count 89 | } 90 | r = requests.get(url, params=params) 91 | check_error(r) 92 | return r.json() 93 | 94 | def find_playlists_by_username(self, user_name, 95 | orderby='published', page=1, count=20): 96 | """doc: http://open.youku.com/docs/doc?id=70 97 | """ 98 | url = 'https://openapi.youku.com/v2/playlists/by_user.json' 99 | params = { 100 | 'client_id': self.client_id, 101 | 'user_name': user_name, 102 | 'orderby': orderby, 103 | 'page': page, 104 | 'count': count 105 | } 106 | r = requests.get(url, params=params) 107 | check_error(r) 108 | return r.json() 109 | 110 | def find_videos_by_playlist(self, playlist_id, page=1, count=20): 111 | """doc: http://open.youku.com/docs/doc?id=71 112 | """ 113 | url = 'https://openapi.youku.com/v2/playlists/videos.json' 114 | params = { 115 | 'client_id': self.client_id, 116 | 'playlist_id': playlist_id, 117 | 'page': page, 118 | 'count': count 119 | } 120 | r = requests.get(url, params=params) 121 | check_error(r) 122 | return r.json() 123 | 124 | def create_playlist(self, access_token, title, tags, 125 | category=None, description=None): 126 | """doc: http://open.youku.com/docs/doc?id=72 127 | """ 128 | url = 'https://openapi.youku.com/v2/playlists/create.json' 129 | data = { 130 | 'client_id': self.client_id, 131 | 'access_token': access_token, 132 | 'title': title, 133 | 'tags': tags, 134 | 'category': category, 135 | 'description': description 136 | } 137 | data = remove_none_value(data) 138 | r = requests.post(url, data=data) 139 | check_error(r) 140 | return r.json()['id'] 141 | 142 | def update_playlist(self, access_token, playlist_id, title, 143 | tags=None, category=None, description=None): 144 | """doc: http://open.youku.com/docs/doc?id=73 145 | """ 146 | url = 'https://openapi.youku.com/v2/playlists/update.json' 147 | data = { 148 | 'client_id': self.client_id, 149 | 'access_token': access_token, 150 | 'playlist_id': playlist_id, 151 | 'title': title, 152 | 'tags': tags, 153 | 'category': category, 154 | 'description': description 155 | } 156 | data = remove_none_value(data) 157 | r = requests.post(url, data=data) 158 | check_error(r) 159 | return r.json()['id'] 160 | 161 | def destroy_playlist(self, access_token, playlist_id): 162 | """doc: http://open.youku.com/docs/doc?id=74 163 | """ 164 | url = 'https://openapi.youku.com/v2/playlists/destroy.json' 165 | data = { 166 | 'client_id': self.client_id, 167 | 'access_token': access_token, 168 | 'playlist_id': playlist_id 169 | } 170 | r = requests.post(url, data=data) 171 | check_error(r) 172 | return r.json()['id'] 173 | 174 | def add_videos_to_playlist(self, access_token, playlist_id, video_ids): 175 | """doc: http://open.youku.com/docs/doc?id=75 176 | """ 177 | url = 'https://openapi.youku.com/v2/playlists/video/add.json' 178 | data = { 179 | 'client_id': self.client_id, 180 | 'access_token': access_token, 181 | 'playlist_id': playlist_id, 182 | 'video_ids': video_ids 183 | } 184 | r = requests.post(url, data=data) 185 | check_error(r) 186 | return r.json()['id'] 187 | 188 | def del_videos_from_playlist(self, access_token, playlist_id, video_ids): 189 | """doc: http://open.youku.com/docs/doc?id=76 190 | """ 191 | url = 'https://openapi.youku.com/v2/playlists/video/del.json' 192 | data = { 193 | 'client_id': self.client_id, 194 | 'access_token': access_token, 195 | 'playlist_id': playlist_id, 196 | 'video_ids': video_ids 197 | } 198 | r = requests.post(url, data=data) 199 | check_error(r) 200 | return r.json()['id'] 201 | 202 | def set_cover_video_for_playlist(self, access_token, playlist_id, 203 | video_id): 204 | """doc: http://open.youku.com/docs/doc?id=77 205 | """ 206 | url = 'https://openapi.youku.com/v2/playlists/video/setcover.json' 207 | data = { 208 | 'client_id': self.client_id, 209 | 'access_token': access_token, 210 | 'playlist_id': playlist_id, 211 | 'video_id': video_id 212 | } 213 | r = requests.post(url, data=data) 214 | check_error(r) 215 | return r.json()['id'] 216 | 217 | def find_next_video_in_playlist(self, playlist_id, cur_video_id): 218 | """doc: http://open.youku.com/docs/doc?id=78 219 | """ 220 | url = 'https://openapi.youku.com/v2/playlists/video/next.json' 221 | params = { 222 | 'client_id': self.client_id, 223 | 'playlist_id': playlist_id, 224 | 'video_id': cur_video_id 225 | } 226 | r = requests.get(url, params=params) 227 | check_error(r) 228 | return r.json() 229 | -------------------------------------------------------------------------------- /youku/youku_schemas.py: -------------------------------------------------------------------------------- 1 | """Youku Open API V2 Python Client 2 | 3 | doc: http://open.youku.com/docs/tech_doc.html 4 | """ 5 | 6 | import requests 7 | from .util import check_error 8 | 9 | 10 | class YoukuSchemas(object): 11 | 12 | """Youku Schemas API. 13 | """ 14 | 15 | def __init__(self, client_id): 16 | super(YoukuSchemas, self).__init__() 17 | self.client_id = client_id 18 | 19 | def video_category(self): 20 | """doc: http://open.youku.com/docs/doc?id=90 21 | """ 22 | url = 'https://openapi.youku.com/v2/schemas/video/category.json' 23 | r = requests.get(url) 24 | check_error(r) 25 | return r.json() 26 | 27 | def upload_spec(self): 28 | """doc: http://open.youku.com/docs/doc?id=91 29 | """ 30 | url = 'https://openapi.youku.com/v2/schemas/upload/spec.json' 31 | r = requests.get(url) 32 | check_error(r) 33 | return r.json() 34 | 35 | def comment_expression(self): 36 | """doc: http://open.youku.com/docs/doc?id=92 37 | """ 38 | url = 'https://openapi.youku.com/v2/schemas/comment/expression.json' 39 | r = requests.get(url) 40 | check_error(r) 41 | return r.json() 42 | 43 | def show_category(self): 44 | """doc: http://open.youku.com/docs/doc?id=93 45 | """ 46 | url = 'https://openapi.youku.com/v2/schemas/show/category.json' 47 | r = requests.get(url) 48 | check_error(r) 49 | return r.json() 50 | 51 | def playlist_category(self): 52 | """doc: http://open.youku.com/docs/doc?id=94 53 | """ 54 | url = 'https://openapi.youku.com/v2/schemas/playlist/category.json' 55 | r = requests.get(url) 56 | check_error(r) 57 | return r.json() 58 | 59 | def searche_top_category(self): 60 | """doc: http://open.youku.com/docs/doc?id=95 61 | """ 62 | url = 'https://openapi.youku.com/v2/schemas/searche/top/category.json' 63 | r = requests.get(url) 64 | check_error(r) 65 | return r.json() 66 | -------------------------------------------------------------------------------- /youku/youku_searches.py: -------------------------------------------------------------------------------- 1 | """Youku Open API V2 Python Client 2 | 3 | doc: http://open.youku.com/docs/tech_doc.html 4 | """ 5 | 6 | import requests 7 | from .util import check_error, remove_none_value 8 | 9 | 10 | class YoukuSearchs(object): 11 | 12 | """Youku Searchs API. 13 | 14 | doc: http://open.youku.com/docs/api_searches.html 15 | """ 16 | 17 | def __init__(self, client_id): 18 | super(YoukuSearchs, self).__init__() 19 | self.client_id = client_id 20 | 21 | def search_videos_by_tag(self, tag, category=None, 22 | period='today', 23 | orderby='relevance', 24 | page=1, count=20): 25 | """doc: http://open.youku.com/docs/doc?id=80 26 | """ 27 | url = 'https://openapi.youku.com/v2/searches/video/by_tag.json' 28 | params = { 29 | 'client_id': self.client_id, 30 | 'tag': tag, 31 | 'period': period, 32 | 'orderby': orderby, 33 | 'page': page, 34 | 'count': count 35 | } 36 | if category: 37 | params['category'] = category 38 | r = requests.get(url, params=params) 39 | check_error(r) 40 | return r.json() 41 | 42 | def search_videos_by_keyword(self, keyword, category=None, 43 | period='week', orderby='relevance', 44 | public_type='all', paid=None, 45 | timeless=None, timemore=None, 46 | streamtypes=None, 47 | page=1, count=20): 48 | """doc: http://open.youku.com/docs/doc?id=81 49 | """ 50 | url = 'https://openapi.youku.com/v2/searches/video/by_keyword.json' 51 | params = { 52 | 'client_id': self.client_id, 53 | 'keyword': keyword, 54 | 'category': category, 55 | 'period': period, 56 | 'orderby': orderby, 57 | 'public_type': public_type, 58 | 'paid': paid, 59 | 'timeless': timeless, 60 | 'timemore': timemore, 61 | 'streamtypes': streamtypes, 62 | 'page': page, 63 | 'count': count 64 | } 65 | params = remove_none_value(params) 66 | r = requests.get(url, params=params) 67 | check_error(r) 68 | return r.json() 69 | 70 | def search_shows_by_keyword(self, keyword, unite=0, source_site=None, 71 | category=None, release_year=None, 72 | area=None, orderby='view-count', 73 | paid=None, hasvideotype=None, 74 | page=1, count=20): 75 | """doc: http://open.youku.com/docs/doc?id=82 76 | """ 77 | url = 'https://openapi.youku.com/v2/searches/show/by_keyword.json' 78 | params = { 79 | 'client_id': self.client_id, 80 | 'keyword': keyword, 81 | 'unite': unite, 82 | 'source_site': source_site, 83 | 'category': category, 84 | 'release_year': release_year, 85 | 'area': area, 86 | 'orderby': orderby, 87 | 'paid': paid, 88 | 'hasvideotype': hasvideotype, 89 | 'page': page, 90 | 'count': count 91 | } 92 | params = remove_none_value(params) 93 | r = requests.get(url, params=params) 94 | check_error(r) 95 | return r.json() 96 | 97 | def search_keyword_complete(self, keyword): 98 | """doc: http://open.youku.com/docs/doc?id=83 99 | """ 100 | url = 'https://openapi.youku.com/v2/searches/keyword/complete.json' 101 | params = { 102 | 'client_id': self.client_id, 103 | 'keyword': keyword 104 | } 105 | r = requests.get(url, params=params) 106 | check_error(r) 107 | return r.json() 108 | 109 | def search_keyword_top(self, category=None, count=20, period='today'): 110 | """doc: http://open.youku.com/docs/doc?id=84 111 | """ 112 | url = 'https://openapi.youku.com/v2/searches/keyword/top.json' 113 | params = { 114 | 'client_id': self.client_id, 115 | 'count': count, 116 | 'period': period 117 | } 118 | if category: 119 | params['category'] = category 120 | r = requests.get(url, params=params) 121 | check_error(r) 122 | return r.json() 123 | 124 | def search_show_address_unite(self, progammeId, 125 | source_site=None, type=None): 126 | """doc: http://open.youku.com/docs/doc?id=85 127 | """ 128 | url = 'https://openapi.youku.com/v2/searches/show/address_unite.json' 129 | params = { 130 | 'client_id': self.client_id, 131 | 'progammeId': progammeId, 132 | 'source_site': source_site, 133 | 'type': type 134 | } 135 | params = remove_none_value(params) 136 | r = requests.get(url, params=params) 137 | check_error(r) 138 | return r.json() 139 | 140 | def search_show_top_unite(self, category, genre=None, area=None, 141 | year=None, orderby=None, headnum=1, 142 | tailnum=1, onesiteflag=None, 143 | page=1, count=20): 144 | """doc: http://open.youku.com/docs/doc?id=86 145 | """ 146 | url = 'https://openapi.youku.com/v2/searches/show/top_unite.json' 147 | params = { 148 | 'client_id': self.client_id, 149 | 'category': category, 150 | 'genre': genre, 151 | 'area': area, 152 | 'year': year, 153 | 'orderby': orderby, 154 | 'headnum': headnum, 155 | 'tailnum': tailnum, 156 | 'onesiteflag': onesiteflag, 157 | 'page': page, 158 | 'count': count 159 | } 160 | params = remove_none_value(params) 161 | r = requests.get(url, params=params) 162 | check_error(r) 163 | return r.json() 164 | -------------------------------------------------------------------------------- /youku/youku_shows.py: -------------------------------------------------------------------------------- 1 | """Youku Open API V2 Python Client 2 | 3 | doc: http://open.youku.com/docs/tech_doc.html 4 | """ 5 | 6 | import requests 7 | from .util import check_error, remove_none_value 8 | 9 | 10 | class YoukuShows(object): 11 | 12 | """Youku Shows API. 13 | 14 | doc: http://open.youku.com/docs/api_shows.html 15 | """ 16 | 17 | def __init__(self, client_id): 18 | super(YoukuShows, self).__init__() 19 | self.client_id = client_id 20 | 21 | def find_show_by_id(self, show_id): 22 | """doc: http://open.youku.com/docs/doc?id=59 23 | """ 24 | url = 'https://openapi.youku.com/v2/shows/show.json' 25 | params = { 26 | 'client_id': self.client_id, 27 | 'show_id': show_id 28 | } 29 | r = requests.get(url, params=params) 30 | check_error(r) 31 | return r.json() 32 | 33 | def find_shows_by_ids(self, show_ids): 34 | """doc: http://open.youku.com/docs/doc?id=60 35 | """ 36 | url = 'https://openapi.youku.com/v2/shows/show_batch.json' 37 | params = { 38 | 'client_id': self.client_id, 39 | 'show_ids': show_ids 40 | } 41 | r = requests.get(url, params=params) 42 | check_error(r) 43 | return r.json() 44 | 45 | def find_show_premium_by_ids(self, show_ids, page=1, count=20): 46 | """doc: http://open.youku.com/docs/doc?id=61 47 | """ 48 | url = 'https://openapi.youku.com/v2/shows/show_premium.json' 49 | params = { 50 | 'client_id': self.client_id, 51 | 'show_ids': show_ids, 52 | 'page': page, 53 | 'count': count 54 | } 55 | r = requests.get(url, params=params) 56 | check_error(r) 57 | return r.json() 58 | 59 | def find_shows_by_category(self, category, genre=None, area=None, 60 | release_year=None, paid=None, 61 | orderby='view-today-count', 62 | streamtypes=None, person=None, 63 | page=1, count=20): 64 | """doc: http://open.youku.com/docs/doc?id=62 65 | """ 66 | url = 'https://openapi.youku.com/v2/shows/by_category.json' 67 | params = { 68 | 'client_id': self.client_id, 69 | 'category': category, 70 | 'genre': genre, 71 | 'area': area, 72 | 'release_year': release_year, 73 | 'paid': paid, 74 | 'orderby': orderby, 75 | 'streamtypes': streamtypes, 76 | 'person': person, 77 | 'page': page, 78 | 'count': count 79 | } 80 | params = remove_none_value(params) 81 | r = requests.get(url, params=params) 82 | check_error(r) 83 | return r.json() 84 | 85 | def find_shows_by_related(self, show_id, 86 | count=20): 87 | """doc: http://open.youku.com/docs/doc?id=63 88 | """ 89 | url = 'https://openapi.youku.com/v2/shows/by_related.json' 90 | params = { 91 | 'client_id': self.client_id, 92 | 'show_id': show_id, 93 | 'count': count 94 | } 95 | r = requests.get(url, params=params) 96 | check_error(r) 97 | return r.json() 98 | 99 | def find_videos_by_show(self, show_id, show_videotype=None, 100 | show_videostage=None, orderby='videoseq-asc', 101 | page=1, count=20): 102 | """doc: http://open.youku.com/docs/doc?id=64 103 | """ 104 | url = 'https://openapi.youku.com/v2/shows/videos.json' 105 | params = { 106 | 'client_id': self.client_id, 107 | 'show_id': show_id, 108 | 'page': page, 109 | 'count': count, 110 | 'show_videotype': show_videotype, 111 | 'show_videostage': show_videostage, 112 | 'orderby': orderby 113 | } 114 | params = remove_none_value(params) 115 | r = requests.get(url, params=params) 116 | check_error(r) 117 | return r.json() 118 | -------------------------------------------------------------------------------- /youku/youku_upload.py: -------------------------------------------------------------------------------- 1 | """Youku cloud Python Client 2 | 3 | doc: http://cloud.youku.com/docs/doc?id=110 4 | """ 5 | 6 | import os 7 | import requests 8 | import json 9 | import hashlib 10 | import logging 11 | import socket 12 | from time import sleep 13 | from .util import check_error, YoukuError 14 | 15 | 16 | class YoukuUpload(object): 17 | 18 | """Youku Upload Client. 19 | 20 | Upload file to Youku Video. Support resume upload if interrupted. 21 | Should use one instance of YoukuUpload for one upload file in one thread, 22 | since it has internal state of upload process. 23 | 24 | doc: http://cloud.youku.com/docs/doc?id=110 25 | """ 26 | 27 | def __init__(self, client_id, access_token, file, logger=None): 28 | """ 29 | Args: 30 | file: string, include path and filename for open(). filename 31 | must contain video file extension. 32 | """ 33 | super(YoukuUpload, self).__init__() 34 | self.client_id = client_id 35 | self.access_token = access_token 36 | self.logger = logger or logging.getLogger(__name__) 37 | 38 | # file info 39 | self.file = file 40 | self.file_size = os.path.getsize(self.file) # int 41 | self.file_dir, self.file_name = os.path.split(self.file) # string 42 | if self.file_dir == '': 43 | self.file_dir = '.' 44 | self.file_ext = self.file_name.rsplit('.', 1)[1], # file extension 45 | self.file_md5 = None # string, do later 46 | 47 | # upload state 48 | self.upload_token = None # string 49 | self.upload_server_ip = None # string 50 | self.slice_task_id = None # int 51 | self.slice_offset = None # int 52 | self.slice_length = None # int 53 | self.transferred = None # int for bytes has uploaded 54 | self.finished = False # boolean 55 | 56 | # resume upload state 57 | self._read_upload_state_from_file() 58 | 59 | def prepare_video_params(self, title=None, tags='Others', description='', 60 | copyright_type='original', public_type='all', 61 | category=None, watch_password=None, 62 | latitude=None, longitude=None, shoot_time=None 63 | ): 64 | """ util method for create video params to upload. 65 | 66 | Only need to provide a minimum of two essential parameters: 67 | title and tags, other video params are optional. All params spec 68 | see: http://cloud.youku.com/docs?id=110#create . 69 | 70 | Args: 71 | title: string, 2-50 characters. 72 | tags: string, 1-10 tags joind with comma. 73 | description: string, less than 2000 characters. 74 | copyright_type: string, 'original' or 'reproduced' 75 | public_type: string, 'all' or 'friend' or 'password' 76 | watch_password: string, if public_type is password. 77 | latitude: double. 78 | longitude: double. 79 | shoot_time: datetime. 80 | 81 | Returns: 82 | dict params that upload/create method need. 83 | """ 84 | params = {} 85 | if title is None: 86 | title = self.file_name 87 | elif len(title) > 80: 88 | title = title[:80] 89 | 90 | if len(description) > 2000: 91 | description = description[0:2000] 92 | 93 | params['title'] = title 94 | params['tags'] = tags 95 | params['description'] = description 96 | params['copyright_type'] = copyright_type 97 | params['public_type'] = public_type 98 | if category: 99 | params['category'] = category 100 | if watch_password: 101 | params['watch_password'] = watch_password 102 | if latitude: 103 | params['latitude'] = latitude 104 | if longitude: 105 | params['longitude'] = longitude 106 | if shoot_time: 107 | params['shoot_time'] = shoot_time 108 | 109 | return params 110 | 111 | def create(self, params): 112 | # prepare file info 113 | params['file_name'] = self.file_name 114 | params['file_size'] = self.file_size 115 | params['file_md5'] = self.file_md5 = self.checksum_md5file(self.file) 116 | self.logger.info('upload file %s, size: %d bytes' % 117 | (self.file_name, self.file_size)) 118 | self.logger.info('md5 of %s: %s' % 119 | (self.file_name, self.file_md5)) 120 | 121 | params['client_id'] = self.client_id 122 | params['access_token'] = self.access_token 123 | 124 | url = 'https://api.youku.com/uploads/create.json' 125 | r = requests.get(url, params=params) 126 | check_error(r, 201) 127 | result = r.json() 128 | 129 | self.upload_token = result['upload_token'] 130 | self.logger.info('upload token of %s: %s' % 131 | (self.file_name, self.upload_token)) 132 | 133 | self.upload_server_ip = socket.gethostbyname( 134 | result['upload_server_uri']) 135 | self.logger.info('upload_server_ip of %s: %s' % 136 | (self.file_name, self.upload_server_ip)) 137 | 138 | def _save_upload_state_to_file(self): 139 | """if create and create_file has execute, save upload state 140 | to file for next resume upload if current upload process is 141 | interrupted. 142 | """ 143 | if os.access(self.file_dir, os.W_OK | os.R_OK | os.X_OK): 144 | save_file = self.file + '.upload' 145 | data = { 146 | 'upload_token': self.upload_token, 147 | 'upload_server_ip': self.upload_server_ip 148 | } 149 | with open(save_file, 'w') as f: 150 | json.dump(data, f) 151 | 152 | def _read_upload_state_from_file(self): 153 | save_file = self.file + '.upload' 154 | try: 155 | with open(save_file) as f: 156 | data = json.load(f) 157 | self.upload_token = data['upload_token'] 158 | self.upload_server_ip = data['upload_server_ip'] 159 | # check upload_token expired 160 | try: 161 | self.check() 162 | except YoukuError as e: 163 | if e.code == 120010223: 164 | # Expired upload token 165 | self.upload_token = None 166 | self.upload_server_ip = None 167 | self._delete_upload_state_file() 168 | except: 169 | pass 170 | 171 | def _delete_upload_state_file(self): 172 | try: 173 | os.remove(self.file + '.upload') 174 | except: 175 | pass 176 | 177 | def checksum_md5file(self, filename): 178 | md5 = hashlib.md5() 179 | with open(filename, 'rb') as f: 180 | for chunk in iter(lambda: f.read(8192), b''): 181 | md5.update(chunk) 182 | return md5.hexdigest() 183 | 184 | def checksum_md5data(self, data): 185 | md5 = hashlib.md5() 186 | md5.update(data) 187 | return md5.hexdigest() 188 | 189 | def create_file(self): 190 | params = { 191 | 'upload_token': self.upload_token, 192 | 'file_size': self.file_size, # Byte 193 | 'ext': self.file_ext, 194 | 'slice_length': 2048 # KB 195 | } 196 | url = 'http://%s/gupload/create_file' % self.upload_server_ip 197 | r = requests.post(url, data=params) 198 | check_error(r, 201) 199 | 200 | # save upload state to resume upload 201 | self._save_upload_state_to_file() 202 | 203 | def new_slice(self): 204 | params = { 205 | 'upload_token': self.upload_token 206 | } 207 | url = 'http://%s/gupload/new_slice' % self.upload_server_ip 208 | r = requests.get(url, params=params) 209 | check_error(r, 201) 210 | self._save_slice_state(r.json()) 211 | 212 | def _save_slice_state(self, result): 213 | self.slice_task_id = result['slice_task_id'] 214 | self.slice_offset = result['offset'] 215 | self.slice_length = result['length'] 216 | self.transferred = result['transferred'] 217 | self.finished = result['finished'] 218 | 219 | def upload_slice(self): 220 | data = None 221 | with open(self.file, 'rb') as f: 222 | f.seek(self.slice_offset) 223 | data = f.read(self.slice_length) 224 | params = { 225 | 'upload_token': self.upload_token, 226 | 'slice_task_id': self.slice_task_id, 227 | 'offset': self.slice_offset, 228 | 'length': self.slice_length, # Byte 229 | 'hash': self.checksum_md5data(data) 230 | } 231 | url = 'http://%s/gupload/upload_slice' % self.upload_server_ip 232 | r = requests.post(url, params=params, data=data) 233 | check_error(r, 201) 234 | self._save_slice_state(r.json()) 235 | 236 | def check(self): 237 | params = { 238 | 'upload_token': self.upload_token 239 | } 240 | url = 'http://%s/gupload/check' % self.upload_server_ip 241 | r = requests.get(url, params=params) 242 | check_error(r, 200) 243 | return r.json() 244 | 245 | def commit(self): 246 | status = self.check() 247 | if status['status'] == 4: 248 | raise ValueError('upload has not complete, should not commit') 249 | while status['status'] != 1: # status is 2 or 3 250 | sleep(10) 251 | status = self.check() 252 | 253 | params = { 254 | 'access_token': self.access_token, 255 | 'client_id': self.client_id, 256 | 'upload_token': self.upload_token, 257 | 'upload_server_ip': status['upload_server_ip'] 258 | } 259 | url = 'https://api.youku.com/uploads/commit.json' 260 | r = requests.post(url, data=params) 261 | check_error(r, 200) 262 | self.finished = True 263 | self._delete_upload_state_file() 264 | return r.json()['video_id'] 265 | 266 | def cancel(self): 267 | status = self.check() 268 | params = { 269 | 'access_token': self.access_token, 270 | 'client_id': self.client_id, 271 | 'upload_token': self.upload_token, 272 | 'upload_server_ip': status['upload_server_ip'] 273 | } 274 | url = 'https://api.youku.com/uploads/cancel.json' 275 | r = requests.get(url, params=params) 276 | check_error(r, 200) 277 | self._delete_upload_state_file() 278 | return r.json()['upload_token'] 279 | 280 | def spec(self): 281 | url = 'https://api.youku.com/schemas/upload/spec.json' 282 | r = requests.get(url) 283 | check_error(r, 200) 284 | return r.json() 285 | 286 | def transferred_percent(self): 287 | """return current transferred percent 288 | """ 289 | return int(self.transferred / self.file_size) 290 | 291 | def upload(self, params={}): 292 | """start uploading the file until upload is complete or error. 293 | This is the main method to used, If you do not care about 294 | state of process. 295 | 296 | Args: 297 | params: a dict object describe video info, eg title, 298 | tags, description, category. 299 | all video params see the doc of prepare_video_params. 300 | 301 | Returns: 302 | return video_id if upload successfully 303 | """ 304 | if self.upload_token is not None: 305 | # resume upload 306 | status = self.check() 307 | if status['status'] != 4: 308 | return self.commit() 309 | else: 310 | self.new_slice() 311 | while self.slice_task_id != 0: 312 | self.upload_slice() 313 | return self.commit() 314 | else: 315 | # new upload 316 | self.create(self.prepare_video_params(**params)) 317 | self.create_file() 318 | self.new_slice() 319 | while self.slice_task_id != 0: 320 | self.upload_slice() 321 | return self.commit() 322 | -------------------------------------------------------------------------------- /youku/youku_users.py: -------------------------------------------------------------------------------- 1 | """Youku Open API V2 Python Client 2 | 3 | doc: http://open.youku.com/docs/tech_doc.html 4 | """ 5 | 6 | import requests 7 | from .util import check_error, remove_none_value 8 | 9 | 10 | class YoukuUsers(object): 11 | 12 | """Youku Users API. 13 | 14 | doc: http://open.youku.com/docs/api_users.html 15 | """ 16 | 17 | def __init__(self, client_id): 18 | super(YoukuUsers, self).__init__() 19 | self.client_id = client_id 20 | 21 | def my_info(self, access_token): 22 | """doc: http://open.youku.com/docs/doc?id=23 23 | """ 24 | url = 'https://openapi.youku.com/v2/users/myinfo.json' 25 | data = {'client_id': self.client_id, 26 | 'access_token': access_token} 27 | r = requests.post(url, data=data) 28 | check_error(r) 29 | return r.json() 30 | 31 | def find_user_by_id(self, user_id): 32 | """doc: http://open.youku.com/docs/doc?id=24 33 | """ 34 | return self._find_user(user_id=user_id) 35 | 36 | def find_user_by_name(self, user_name): 37 | """doc: http://open.youku.com/docs/doc?id=24 38 | """ 39 | return self._find_user(user_name=user_name) 40 | 41 | def find_users_by_ids(self, user_ids): 42 | """doc: http://open.youku.com/docs/doc?id=25 43 | """ 44 | return self._find_users(user_ids=user_ids) 45 | 46 | def find_users_by_names(self, user_names): 47 | """doc: http://open.youku.com/docs/doc?id=25 48 | """ 49 | return self._find_users(user_names=user_names) 50 | 51 | def _find_user(self, user_id=None, user_name=None): 52 | url = 'https://openapi.youku.com/v2/users/show.json' 53 | data = { 54 | 'client_id': self.client_id, 55 | 'user_id': user_id, 56 | 'user_name': user_name 57 | } 58 | data = remove_none_value(data) 59 | r = requests.post(url, data=data) 60 | if r.status_code == 400: 61 | # Youku return 400 if no result, but this is not friendly. 62 | return None 63 | check_error(r) 64 | return r.json() 65 | 66 | def _find_users(self, user_ids=None, user_names=None): 67 | url = 'https://openapi.youku.com/v2/users/show_batch.json' 68 | data = { 69 | 'client_id': self.client_id, 70 | 'user_ids': user_ids, 71 | 'user_names': user_names 72 | } 73 | data = remove_none_value(data) 74 | r = requests.post(url, data=data) 75 | if r.status_code == 400: 76 | # Youku return 400 if no result, but this is not friendly. 77 | return None 78 | check_error(r) 79 | return r.json() 80 | 81 | def friendship_followings(self, user_id=None, user_name=None, 82 | page=1, count=20): 83 | """doc: http://open.youku.com/docs/doc?id=26 84 | """ 85 | url = 'https://openapi.youku.com/v2/users/friendship/followings.json' 86 | data = { 87 | 'client_id': self.client_id, 88 | 'page': page, 89 | 'count': count, 90 | 'user_id': user_id, 91 | 'user_name': user_name 92 | } 93 | data = remove_none_value(data) 94 | r = requests.post(url, data=data) 95 | check_error(r) 96 | return r.json() 97 | 98 | def friendship_followers(self, user_id=None, user_name=None, 99 | page=1, count=20): 100 | """doc: http://open.youku.com/docs/doc?id=27 101 | """ 102 | url = 'https://openapi.youku.com/v2/users/friendship/followers.json' 103 | data = { 104 | 'client_id': self.client_id, 105 | 'page': page, 106 | 'count': count, 107 | 'user_id': user_id, 108 | 'user_name': user_name 109 | } 110 | data = remove_none_value(data) 111 | r = requests.post(url, data=data) 112 | check_error(r) 113 | return r.json() 114 | 115 | def create_friendship(self, access_token, 116 | user_id=None, user_name=None): 117 | """doc: http://open.youku.com/docs/doc?id=28 118 | """ 119 | url = 'https://openapi.youku.com/v2/users/friendship/create.json' 120 | data = { 121 | 'client_id': self.client_id, 122 | 'access_token': access_token, 123 | 'user_id': user_id, 124 | 'user_name': user_name 125 | } 126 | data = remove_none_value(data) 127 | r = requests.post(url, data=data) 128 | check_error(r) 129 | return r.json() 130 | 131 | def destroy_friendship(self, access_token, 132 | user_id=None, user_name=None): 133 | """doc: ?? 134 | """ 135 | url = 'https://openapi.youku.com/v2/users/friendship/destroy.json' 136 | data = { 137 | 'client_id': self.client_id, 138 | 'access_token': access_token, 139 | 'user_id': user_id, 140 | 'user_name': user_name 141 | } 142 | data = remove_none_value(data) 143 | r = requests.post(url, data=data) 144 | check_error(r) 145 | return r.json() 146 | 147 | def create_subscribe(self, access_token, show_id): 148 | """doc: http://open.youku.com/docs/doc?id=29 149 | """ 150 | url = 'https://openapi.youku.com/v2/users/subscribe/create.json' 151 | params = { 152 | 'client_id': self.client_id, 153 | 'access_token': access_token, 154 | 'show_id': show_id 155 | } 156 | r = requests.get(url, params=params) 157 | check_error(r) 158 | return r.json()['result'] == 0 159 | 160 | def cancel_subscribe(self, access_token, show_id): 161 | """doc: ?? 162 | """ 163 | url = 'https://openapi.youku.com/v2/users/subscribe/cancel.json' 164 | params = { 165 | 'client_id': self.client_id, 166 | 'access_token': access_token, 167 | 'show_id': show_id 168 | } 169 | r = requests.post(url, data=params) 170 | check_error(r) 171 | return r.json()['result'] == 0 172 | 173 | def subscribe_get(self, access_token, page=1, count=20): 174 | """doc: http://open.youku.com/docs/doc?id=30 175 | """ 176 | url = 'https://openapi.youku.com/v2/users/subscribe/get.json' 177 | params = { 178 | 'client_id': self.client_id, 179 | 'access_token': access_token, 180 | 'page': page, 181 | 'count': count 182 | } 183 | r = requests.get(url, params=params) 184 | check_error(r) 185 | return r.json() 186 | 187 | def subscribe_notice(self, access_token): 188 | """doc: http://open.youku.com/docs/doc?id=31 189 | """ 190 | url = 'https://openapi.youku.com/v2/users/subscribe/notice.json' 191 | params = { 192 | 'client_id': self.client_id, 193 | 'access_token': access_token 194 | } 195 | r = requests.get(url, params=params) 196 | check_error(r) 197 | return r.json() 198 | -------------------------------------------------------------------------------- /youku/youku_videos.py: -------------------------------------------------------------------------------- 1 | """Youku Open API V2 Python Client 2 | 3 | doc: http://open.youku.com/docs/tech_doc.html 4 | """ 5 | 6 | import requests 7 | from .util import check_error, remove_none_value 8 | 9 | 10 | class YoukuVideos(object): 11 | 12 | """Youku Videos API. 13 | 14 | doc:http://open.youku.com/docs/api_videos.html 15 | """ 16 | 17 | def __init__(self, client_id): 18 | super(YoukuVideos, self).__init__() 19 | self.client_id = client_id 20 | 21 | def find_video_by_id(self, video_id): 22 | """doc: http://open.youku.com/docs/doc?id=44 23 | """ 24 | url = 'https://openapi.youku.com/v2/videos/show_basic.json' 25 | params = { 26 | 'client_id': self.client_id, 27 | 'video_id': video_id 28 | } 29 | r = requests.get(url, params=params) 30 | check_error(r) 31 | return r.json() 32 | 33 | def find_video_by_url(self, video_url): 34 | """doc: http://open.youku.com/docs/doc?id=44 35 | """ 36 | url = 'https://openapi.youku.com/v2/videos/show_basic.json' 37 | params = { 38 | 'client_id': self.client_id, 39 | 'video_url': video_url 40 | } 41 | r = requests.get(url, params=params) 42 | check_error(r) 43 | return r.json() 44 | 45 | def find_videos_by_ids(self, video_ids): 46 | """doc: http://open.youku.com/docs/doc?id=45 47 | """ 48 | url = 'https://openapi.youku.com/v2/videos/show_basic_batch.json' 49 | params = { 50 | 'client_id': self.client_id, 51 | 'video_ids': video_ids 52 | } 53 | r = requests.get(url, params=params) 54 | check_error(r) 55 | return r.json() 56 | 57 | def find_video_detail_by_id(self, video_id, ext=None): 58 | """doc: http://cloud.youku.com/docs?id=46 59 | """ 60 | url = 'https://api.youku.com/videos/show.json' 61 | params = { 62 | 'client_id': self.client_id, 63 | 'video_id': video_id 64 | } 65 | if ext: 66 | params['ext'] = ext 67 | r = requests.get(url, params=params) 68 | check_error(r) 69 | return r.json() 70 | 71 | def find_video_details_by_ids(self, video_ids, ext=None): 72 | """doc: http://open.youku.com/docs/doc?id=47 73 | """ 74 | url = 'https://openapi.youku.com/v2/videos/show_batch.json' 75 | params = { 76 | 'client_id': self.client_id, 77 | 'video_ids': video_ids 78 | } 79 | if ext: 80 | params['ext'] = ext 81 | r = requests.get(url, params=params) 82 | check_error(r) 83 | return r.json() 84 | 85 | def find_videos_by_me(self, access_token, orderby='published', 86 | page=1, count=20): 87 | """doc: http://cloud.youku.com/docs?id=48 88 | """ 89 | url = 'https://api.youku.com/videos/by_me.json' 90 | params = { 91 | 'client_id': self.client_id, 92 | 'access_token': access_token, 93 | 'orderby': orderby, 94 | 'page': page, 95 | 'count': count 96 | } 97 | r = requests.get(url, params=params) 98 | check_error(r) 99 | return r.json() 100 | 101 | def find_videos_by_userid(self, user_id, orderby='published', 102 | page=1, count=20): 103 | """doc: http://open.youku.com/docs/doc?id=49 104 | """ 105 | url = 'https://openapi.youku.com/v2/videos/by_user.json' 106 | params = { 107 | 'client_id': self.client_id, 108 | 'user_id': user_id, 109 | 'orderby': orderby, 110 | 'page': page, 111 | 'count': count 112 | } 113 | r = requests.get(url, params=params) 114 | check_error(r) 115 | return r.json() 116 | 117 | def find_videos_by_username(self, user_name, orderby='published', 118 | page=1, count=20): 119 | """doc: http://open.youku.com/docs/doc?id=49 120 | """ 121 | url = 'https://openapi.youku.com/v2/videos/by_user.json' 122 | params = { 123 | 'client_id': self.client_id, 124 | 'user_name': user_name, 125 | 'orderby': orderby, 126 | 'page': page, 127 | 'count': count 128 | } 129 | r = requests.get(url, params=params) 130 | check_error(r) 131 | return r.json() 132 | 133 | def update_video(self, access_token, video_id, title=None, 134 | tags=None, category=None, copyright_type=None, 135 | public_type=None, watch_password=None, 136 | description=None, thumbnail_seq=None): 137 | """doc: http://open.youku.com/docs/doc?id=50 138 | """ 139 | url = 'https://openapi.youku.com/v2/videos/update.json' 140 | data = { 141 | 'client_id': self.client_id, 142 | 'access_token': access_token, 143 | 'video_id': video_id, 144 | 'title': title, 145 | 'tags': tags, 146 | 'category': category, 147 | 'copyright_type': copyright_type, 148 | 'public_type': public_type, 149 | 'watch_password': watch_password, 150 | 'description': description, 151 | 'thumbnail_seq': thumbnail_seq 152 | } 153 | data = remove_none_value(data) 154 | r = requests.post(url, data=data) 155 | check_error(r) 156 | return r.json()['id'] 157 | 158 | def destroy_video(self, access_token, video_id): 159 | """doc: http://open.youku.com/docs/doc?id=51 160 | """ 161 | url = 'https://openapi.youku.com/v2/videos/destroy.json' 162 | data = { 163 | 'client_id': self.client_id, 164 | 'access_token': access_token, 165 | 'video_id': video_id 166 | } 167 | r = requests.post(url, data=data) 168 | check_error(r) 169 | return r.json()['id'] 170 | 171 | def find_videos_by_related(self, video_id, count=20): 172 | """doc: http://open.youku.com/docs/doc?id=52 173 | """ 174 | url = 'https://openapi.youku.com/v2/videos/by_related.json' 175 | params = { 176 | 'client_id': self.client_id, 177 | 'video_id': video_id, 178 | 'count': count 179 | } 180 | r = requests.get(url, params=params) 181 | check_error(r) 182 | return r.json() 183 | 184 | def find_favorite_videos_by_me(self, access_token, orderby='favorite-time', 185 | page=1, count=20): 186 | """doc: http://open.youku.com/docs/doc?id=53 187 | """ 188 | url = 'https://openapi.youku.com/v2/videos/favorite/by_me.json' 189 | params = { 190 | 'client_id': self.client_id, 191 | 'access_token': access_token, 192 | 'orderby': orderby, 193 | 'page': page, 194 | 'count': count 195 | } 196 | r = requests.get(url, params=params) 197 | check_error(r) 198 | return r.json() 199 | 200 | def find_favorite_videos_by_userid(self, user_id, 201 | orderby='favorite-time', 202 | page=1, count=20): 203 | """doc: http://open.youku.com/docs/doc?id=54 204 | """ 205 | url = 'https://openapi.youku.com/v2/videos/favorite/by_user.json' 206 | params = { 207 | 'client_id': self.client_id, 208 | 'user_id': user_id, 209 | 'orderby': orderby, 210 | 'page': page, 211 | 'count': count 212 | } 213 | r = requests.get(url, params=params) 214 | check_error(r) 215 | return r.json() 216 | 217 | def find_favorite_videos_by_username(self, user_name, 218 | orderby='favorite-time', 219 | page=1, count=20): 220 | """doc: http://open.youku.com/docs/doc?id=54 221 | """ 222 | url = 'https://openapi.youku.com/v2/videos/favorite/by_user.json' 223 | params = { 224 | 'client_id': self.client_id, 225 | 'user_name': user_name, 226 | 'orderby': orderby, 227 | 'page': page, 228 | 'count': count 229 | } 230 | r = requests.get(url, params=params) 231 | check_error(r) 232 | return r.json() 233 | 234 | def create_favorite_video(self, access_token, video_id): 235 | """doc: http://open.youku.com/docs/doc?id=55 236 | """ 237 | url = 'https://openapi.youku.com/v2/videos/favorite/create.json' 238 | data = { 239 | 'client_id': self.client_id, 240 | 'access_token': access_token, 241 | 'video_id': video_id 242 | } 243 | r = requests.post(url, data=data) 244 | check_error(r) 245 | return r.json()['id'] 246 | 247 | def destroy_favorite_video(self, access_token, video_id): 248 | """doc: http://open.youku.com/docs/doc?id=56 249 | """ 250 | url = 'https://openapi.youku.com/v2/videos/favorite/destroy.json' 251 | data = { 252 | 'client_id': self.client_id, 253 | 'access_token': access_token, 254 | 'video_id': video_id 255 | } 256 | r = requests.post(url, data=data) 257 | check_error(r) 258 | return r.json()['id'] 259 | 260 | def find_videos_by_category(self, category, genre=None, 261 | period='today', 262 | orderby='view-count', 263 | page=1, count=20): 264 | """doc: http://open.youku.com/docs/doc?id=57 265 | """ 266 | url = 'https://openapi.youku.com/v2/videos/by_category.json' 267 | params = { 268 | 'client_id': self.client_id, 269 | 'category': category, 270 | 'period': period, 271 | 'orderby': orderby, 272 | 'page': page, 273 | 'count': count 274 | } 275 | if genre: 276 | params['genre'] = genre 277 | r = requests.get(url, params=params) 278 | check_error(r) 279 | return r.json() 280 | --------------------------------------------------------------------------------