├── LICENSE ├── README.md ├── app.yaml ├── config.py ├── handlers ├── BaseHandler.py ├── LoginHandler.py ├── LogoutHandler.py ├── MainHandler.py ├── ProfileHandler.py ├── PromoteHandler.py ├── RepoEditHandler.py ├── RepoHandler.py └── __init__.py ├── imports.py ├── index.yaml ├── main.py ├── models ├── Datastore.py └── __init__.py ├── path.py ├── requests ├── __init__.py ├── __init__.pyc ├── adapters.py ├── adapters.pyc ├── api.py ├── api.pyc ├── auth.py ├── auth.pyc ├── cacert.pem ├── certs.py ├── certs.pyc ├── compat.py ├── compat.pyc ├── cookies.py ├── cookies.pyc ├── exceptions.py ├── exceptions.pyc ├── hooks.py ├── hooks.pyc ├── models.py ├── models.pyc ├── packages │ ├── __init__.py │ ├── __init__.pyc │ ├── chardet │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── big5freq.py │ │ ├── big5prober.py │ │ ├── chardetect.py │ │ ├── chardistribution.py │ │ ├── charsetgroupprober.py │ │ ├── charsetprober.py │ │ ├── codingstatemachine.py │ │ ├── compat.py │ │ ├── constants.py │ │ ├── cp949prober.py │ │ ├── escprober.py │ │ ├── escsm.py │ │ ├── eucjpprober.py │ │ ├── euckrfreq.py │ │ ├── euckrprober.py │ │ ├── euctwfreq.py │ │ ├── euctwprober.py │ │ ├── gb2312freq.py │ │ ├── gb2312prober.py │ │ ├── hebrewprober.py │ │ ├── jisfreq.py │ │ ├── jpcntx.py │ │ ├── langbulgarianmodel.py │ │ ├── langcyrillicmodel.py │ │ ├── langgreekmodel.py │ │ ├── langhebrewmodel.py │ │ ├── langhungarianmodel.py │ │ ├── langthaimodel.py │ │ ├── latin1prober.py │ │ ├── mbcharsetprober.py │ │ ├── mbcsgroupprober.py │ │ ├── mbcssm.py │ │ ├── sbcharsetprober.py │ │ ├── sbcsgroupprober.py │ │ ├── sjisprober.py │ │ ├── universaldetector.py │ │ └── utf8prober.py │ └── urllib3 │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── _collections.py │ │ ├── _collections.pyc │ │ ├── connection.py │ │ ├── connection.pyc │ │ ├── connectionpool.py │ │ ├── connectionpool.pyc │ │ ├── contrib │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── ntlmpool.py │ │ ├── pyopenssl.py │ │ └── pyopenssl.pyc │ │ ├── exceptions.py │ │ ├── exceptions.pyc │ │ ├── fields.py │ │ ├── fields.pyc │ │ ├── filepost.py │ │ ├── filepost.pyc │ │ ├── packages │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── ordered_dict.py │ │ ├── ordered_dict.pyc │ │ ├── six.py │ │ ├── six.pyc │ │ └── ssl_match_hostname │ │ │ ├── __init__.py │ │ │ ├── __init__.pyc │ │ │ ├── _implementation.py │ │ │ └── _implementation.pyc │ │ ├── poolmanager.py │ │ ├── poolmanager.pyc │ │ ├── request.py │ │ ├── request.pyc │ │ ├── response.py │ │ ├── response.pyc │ │ └── util │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── connection.py │ │ ├── connection.pyc │ │ ├── request.py │ │ ├── request.pyc │ │ ├── response.py │ │ ├── response.pyc │ │ ├── ssl_.py │ │ ├── ssl_.pyc │ │ ├── timeout.py │ │ ├── timeout.pyc │ │ ├── url.py │ │ └── url.pyc ├── sessions.py ├── sessions.pyc ├── status_codes.py ├── status_codes.pyc ├── structures.py ├── structures.pyc ├── utils.py └── utils.pyc ├── routes.py ├── static ├── css │ ├── homepage.css │ ├── reset.css │ ├── style.css │ └── stylesidebar.css ├── dist │ └── README.md ├── images │ ├── Open-logo.png │ ├── cd-arrow.svg │ ├── cd-nav-icons.svg │ ├── cd-search.svg │ ├── dpp.PNG │ ├── logo.png │ ├── of.png │ ├── oie_png.png │ ├── openflock-ss.png │ ├── pattern.png │ └── safari.png └── js │ ├── bower.json │ ├── homepage.js │ ├── jquery.menu-aim.js │ ├── main.js │ ├── modernizr.js │ ├── pretty.js │ └── remodal.js └── templates ├── HallOfFame.html ├── editrepo.html ├── homepage.html ├── index.html ├── index.html~ ├── promoted_repos.html ├── promoting.html ├── repo_info.html └── userprofile.html /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Wasim Thabraze 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #[Openflock](http://www.openflock.co) 2 | ![Openflock](http://www.openflock.co/images/of.png) 3 | 4 | Gain contributors to your project or get your issues resolved by promoting them on Openflock. 5 | * Find awesome projects or issues to work on. Also filter your feed according to your favourite language or topic. 6 | * Is your Open source project really useful for the community? Fill in [this form](http://goo.gl/forms/5jLE4J89gK) to get your project on Openflock Hall of Fame. 7 | 8 | ### Install 9 | 10 | * Openflock has been written in Python (Webapp2 framework) on top of Google App Engine. 11 | * We use Google datastore to store data. 12 | 13 | 14 | #### Here's how you can install Openflock locally... 15 | 16 | * [Download Google App Engine](https://cloud.google.com/appengine/downloads#Google_App_Engine_SDK_for_Python) 17 | * Clone the repository. 18 | * Download Semantic-UI 2.1.8 (https://github.com/Semantic-Org/Semantic-UI/releases/tag/2.1.8), extract it and place the extracted content in the folder `/static/dist/`. 19 | * Openflock runs on GitHub API. To run Openflock locally, you also need a GitHub client id and client secret id. So [register](https://github.com/settings/applications/new) your GitHub application with `Homepage url` as `http://localhost:8080` and `callback url` as `http://localhost:9000/authorization`. Now you have a client id and client secret id. 20 | * Now open `/handlers/LoginHandler.py` and place client id, client secret id, callback url in the places mentioned in the `LoginHandler.py` file. 21 | * Run the command `python /path/of/dev_appserver.py /path/of/Openflock` (`dev_appserver.py` lies in google_appengine folder) 22 | * Now you can find Openflock running `localhost:8080` and admin server running at `localhost:8000`. 23 | * Raise an issue or contact me if you face any problems in installing Openflock locally. 24 | 25 | 26 | -------------------------------------------------------------------------------- /app.yaml: -------------------------------------------------------------------------------- 1 | application: openflock 2 | version: 1 3 | runtime: python27 4 | api_version: 1 5 | threadsafe: yes 6 | 7 | 8 | handlers: 9 | - url: /(.*\.css) 10 | mime_type: text/css 11 | static_files: static/\1 12 | upload: static/(.*\.css) 13 | 14 | - url: /(.*\.html) 15 | mime_type: text/html 16 | static_files: static/\1 17 | upload: static/(.*\.html) 18 | 19 | - url: /(.*\.js) 20 | mime_type: text/javascript 21 | static_files: static/\1 22 | upload: static/(.*\.js) 23 | 24 | # image files 25 | - url: /(.*\.(bmp|gif|ico|jpeg|jpg|png)) 26 | static_files: static/\1 27 | upload: static/(.*\.(bmp|gif|ico|jpeg|jpg|png)) 28 | 29 | # index files 30 | - url: /(.+)/ 31 | static_files: static/\1/index.html 32 | upload: static/(.+)/index.html 33 | 34 | 35 | # site root 36 | 37 | - url: /.* 38 | script: main.app 39 | 40 | 41 | 42 | libraries: 43 | - name: jinja2 44 | version: latest -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | 3 | config = {} 4 | config['webapp2_extras.sessions'] = {'secret_key': ' ','cookie_args':{'max_age':86400}} -------------------------------------------------------------------------------- /handlers/BaseHandler.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | 3 | def render_str(template, **params): 4 | t = jinja_env.get_template(template) 5 | return t.render(params) 6 | 7 | 8 | class BaseHandler(webapp2.RequestHandler): 9 | def dispatch(self): 10 | # Get a session store for this request. 11 | self.session_store = sessions.get_store(request=self.request) 12 | 13 | try: 14 | # Dispatch the request. 15 | webapp2.RequestHandler.dispatch(self) 16 | finally: 17 | # Save all sessions. 18 | self.session_store.save_sessions(self.response) 19 | 20 | 21 | @webapp2.cached_property 22 | def session(self): 23 | # Returns a session using the default cookie key. 24 | return self.session_store.get_session() 25 | 26 | def render(self, template, **kw): 27 | self.response.out.write(render_str(template, **kw)) 28 | -------------------------------------------------------------------------------- /handlers/LoginHandler.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | from config import * 3 | from routes import * 4 | from handlers import * 5 | from models import * 6 | 7 | redirect__uri = 'http://www.openflock.co/authorization' 8 | client__id = 'ADD YOUR CLIENT_ID HERE' 9 | client__secret = 'ADD YOUR CLIENT SECRET ID HERE' 10 | 11 | 12 | class AuthRedirect(BaseHandler): 13 | def get(self): 14 | self.redirect('https://github.com/login/oauth/authorize?state=openflock&redirect_uri='+redirect__uri+'&client_id='+client__id) 15 | 16 | 17 | class Authorization(BaseHandler): 18 | def get(self): 19 | headers = { 20 | 'User-Agent': 'Openflock' 21 | } 22 | 23 | url_queries = self.request.GET 24 | state = url_queries['state'] 25 | code = url_queries['code'] 26 | url = 'https://github.com/login/oauth/access_token?client_id='+client__id+'&client_secret='+client__secret+'&redirect_uri='+redirect__uri+'&scope=&code='+str(code) 27 | req = requests.post(url,headers=headers) 28 | req = str(req.content) 29 | access_token = "" 30 | i=13 31 | while(req[i]!='&'): 32 | access_token = access_token + req[i] 33 | i = i + 1 34 | 35 | user_api_url = 'https://api.github.com/user?access_token='+str(access_token) 36 | user_json_data = requests.get(user_api_url,headers=headers) 37 | d = json.loads(user_json_data.content) 38 | username = d['login'] 39 | 40 | self.response.out.write(str(access_token)+user_api_url) 41 | if d['name']: 42 | fullname = d['name'] 43 | else: 44 | fullname = str(username) 45 | 46 | self.session['username'] = username 47 | avatar_url = d['avatar_url'] 48 | user_html_url = d['html_url'] 49 | 50 | if d['blog']: 51 | website = d['blog'] 52 | else: 53 | website="" 54 | 55 | if d['email']: 56 | email = d['email'] 57 | else: 58 | email="" 59 | 60 | if d['location']: 61 | location = d['location'] 62 | else: 63 | location="" 64 | 65 | public_repos = d['public_repos'] 66 | followers = d['followers'] 67 | following = d['following'] 68 | repos_url = d['repos_url'] 69 | 70 | repos_url = repos_url + "?access_token="+access_token 71 | lang = [] 72 | res = requests.get(repos_url,headers=headers) 73 | response_code = res.status_code 74 | if(response_code != 200): 75 | self.response.out.write(str(response_code) + " " + str(res.headers) + " Something's wrong with GitHub API!") 76 | return 77 | elif response_code == 200: 78 | cont = res.json() 79 | for item in cont: 80 | if item['fork']==False and item['private']==False: 81 | reponame = item['name'] 82 | repo_html_url = item['html_url'] 83 | username = item['owner']['login'] 84 | if item['language']: 85 | language = item['language'] 86 | lang.append(language) 87 | else: 88 | language="none" 89 | forks = item['forks'] 90 | stars = item['stargazers_count'] 91 | homepage = item['homepage'] 92 | description = item['description'] 93 | 94 | repo_instance = RepoData(key_name=reponame,reponame=reponame,repo_html_url=repo_html_url,username=username,language=language,forks=str(forks),stars=str(stars),website=homepage,description=description) 95 | repo_instance.put() 96 | lang_list = list(set(lang)) 97 | if None in lang_list: 98 | lang_list.remove(None) 99 | 100 | 101 | 102 | orgs_url = 'https://api.github.com/users/'+str(username)+'/orgs?access_token='+str(access_token) 103 | orgs=[] 104 | org_details = requests.get(orgs_url,headers=headers) 105 | response_code=org_details.status_code 106 | if response_code != 200: 107 | self.response.out.write(str(response_code)+" Something's wrong...Moslty with interaction of Openflock with GitHub API!") 108 | elif response_code == 200: 109 | result = org_details.json() 110 | for org in result: 111 | org_username = org['login'] 112 | orgs.append(org_username) 113 | 114 | 115 | 116 | user_instance = UserData(key_name=username,fullname=fullname,username=username,orgs=orgs,access_token=str(access_token),email=email,location=location,website=website,lang_list=lang_list,public_repos=str(public_repos),followers=str(followers),following=str(following),avatar_url=avatar_url) 117 | user_instance.put() 118 | self.redirect('/') 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /handlers/LogoutHandler.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | from config import * 3 | from routes import * 4 | from handlers import * 5 | 6 | class LogoutHandler(BaseHandler): 7 | def get(self): 8 | if self.session.get('username'): 9 | del self.session['username'] 10 | self.redirect('/') -------------------------------------------------------------------------------- /handlers/MainHandler.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | from config import * 3 | from routes import * 4 | from handlers import * 5 | 6 | 7 | 8 | 9 | class MainHandler(BaseHandler): 10 | def get(self): 11 | if self.session.get('username'): 12 | username = self.session.get('username') 13 | userdata = db.GqlQuery("SELECT * FROM UserData WHERE username= :u",u=username) 14 | f = self.request.get('filter') 15 | value = self.request.get('value') 16 | if f == 'language': 17 | repodata = db.GqlQuery("SELECT * FROM PromotedRepos WHERE language= :l",l=str(value)) 18 | elif f== 'genre': 19 | repodata = db.GqlQuery("SELECT * FROM PromotedRepos WHERE genre= :g",g=str(value)) 20 | elif f == 'bitesize': 21 | repodata = db.GqlQuery("SELECT * FROM PromotedRepos WHERE is_beginner= :b",b='Beginner') 22 | 23 | else: 24 | repodata = db.GqlQuery("SELECT * FROM PromotedRepos ORDER BY promoted_time DESC") 25 | if repodata.get(): 26 | self.render('homepage.html',repodata=repodata,userdata=userdata) 27 | else: 28 | self.render('homepage.html',repodata="",userdata=userdata,value=value) 29 | else: 30 | self.render('index.html') 31 | 32 | 33 | 34 | class HallOfFame(BaseHandler): 35 | def get(self): 36 | if self.session.get('username'): 37 | username_session = self.session.get('username') 38 | userdata = db.GqlQuery("SELECT * FROM UserData WHERE username= :u",u=username_session) 39 | data = db.GqlQuery("SELECT * FROM PromotedRepos WHERE hof= :h",h=True) 40 | self.render('HallOfFame.html',data=data,userdata=userdata) 41 | else: 42 | data = db.GqlQuery("SELECT * FROM PromotedRepos WHERE hof= :h",h=True) 43 | self.render('HallOfFame.html',data=data,userdata="") 44 | -------------------------------------------------------------------------------- /handlers/ProfileHandler.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | from config import * 3 | from routes import * 4 | from handlers import * 5 | from datetime import timedelta 6 | 7 | 8 | 9 | class ProfileHandler(BaseHandler): 10 | def get(self): 11 | username_session = self.session.get('username') 12 | if username_session: 13 | navdata = db.GqlQuery("SELECT * FROM UserData WHERE username= :u",u=username_session).get() 14 | len_lang_list = len(navdata.lang_list) 15 | none="" 16 | lang_list = navdata.lang_list 17 | 18 | fullnam = navdata.fullname 19 | avatar_url = navdata.avatar_url 20 | current_url = self.request.url 21 | username_url = current_url.split('/')[4] 22 | isuser = db.GqlQuery("SELECT * FROM UserData WHERE username= :u",u=username_url).fetch(limit=2) 23 | if len(isuser)==0: 24 | self.response.out.write("There's no such user currently on Openflock.") 25 | return 26 | userdata = db.GqlQuery("SELECT * FROM UserData WHERE username= :u",u=username_url) 27 | repodata = db.GqlQuery("SELECT * FROM RepoData WHERE username= :u",u=username_url) 28 | noofrepos = repodata.fetch(limit=2) 29 | self.render('userprofile.html',userdata=userdata,repodata=repodata,avatar_url=avatar_url,navfullname=fullnam,noofrepos=noofrepos,navusername=username_session,len_lang_list=len_lang_list,lang_list=lang_list) 30 | else: 31 | current_url = self.request.url 32 | username_url = current_url.split('/')[4] 33 | isuser = db.GqlQuery("SELECT * FROM UserData WHERE username= :u",u=username_url).fetch(limit=2) 34 | if len(isuser)==0: 35 | self.response.out.write("There's no such user currently on Openflock.") 36 | return 37 | userdata = db.GqlQuery("SELECT * FROM UserData WHERE username= :u",u=username_url) 38 | repodata = db.GqlQuery("SELECT * FROM RepoData WHERE username= :u",u=username_url) 39 | self.render('userprofile.html',userdata=userdata,repodata=repodata,navfullname="") 40 | -------------------------------------------------------------------------------- /handlers/RepoEditHandler.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | from config import * 3 | from routes import * 4 | from handlers import * 5 | from datetime import timedelta 6 | 7 | class RepoEditHandler(BaseHandler): 8 | def get(self): 9 | if self.session.get('username'): 10 | username_session = self.session.get('username') 11 | current_url = self.request.url 12 | old_uid = current_url.split('/')[4].split('?')[0] 13 | is_issue = self.request.get('issue') 14 | if is_issue == 'True': 15 | state = 'open' 16 | else: 17 | state = 'none' 18 | url = self.request.get('url') 19 | v = db.GqlQuery("SELECT * FROM PromotedRepos WHERE uid= :r",r=old_uid).fetch(limit=2) 20 | if len(v) == 0: 21 | self.response.out.write("") 22 | 23 | verify = db.GqlQuery("SELECT * FROM PromotedRepos WHERE uid= :r",r=old_uid).get() 24 | 25 | if str(verify.promoting_user) != str(username_session): 26 | self.response.out.write("You cannot edit someone else's promoted repository!") 27 | return 28 | navdata = db.GqlQuery("SELECT * FROM UserData WHERE username= :u",u=username_session).get() 29 | avatar_url = navdata.avatar_url 30 | repodata = db.GqlQuery("SELECT * FROM PromotedRepos WHERE uid= :r",r=str(old_uid)) 31 | self.render('editrepo.html', username=str(username_session),navfullname=str(navdata.fullname),avatar_url=str(avatar_url),repodata=repodata,issue=is_issue,url=url,state=state) 32 | else: 33 | self.response.out.write("You are not authorized to access this URL.") 34 | 35 | def post(self): 36 | if self.session.get('username'): 37 | current_url = self.request.url 38 | old_uid = current_url.split('/')[4].split('?')[0] 39 | old_instance = db.GqlQuery("SELECT * FROM PromotedRepos WHERE uid= :r",r=old_uid).get() 40 | old_view_of = int(old_instance.views_of) 41 | old_views_gh = int(old_instance.views_gh) 42 | 43 | old_instance.delete() 44 | promoting_user = self.session.get('username') 45 | reponame = self.request.get('issue_title') 46 | description = self.request.get('issue_description') 47 | simple_reason = self.request.get('reason') 48 | detailed_reason = self.request.get('detailed_reason') 49 | contact_link = self.request.get('contact_link') 50 | language = self.request.get('language') 51 | issue = self.request.get('issue') 52 | state = self.request.get('state') 53 | is_beginner = self.request.get('isbeginner') 54 | genre = self.request.get('genre') 55 | hof = False 56 | if genre == "0": 57 | genre="" 58 | url_entered = self.request.get('url_entered') 59 | 60 | ud = db.GqlQuery("SELECT * FROM UserData WHERE username= :u",u=promoting_user).get() 61 | pi = PromotedRepos(promoting_user=promoting_user,is_beginner=is_beginner,genre=genre,repo_html_url=url_entered,reponame=reponame,promoting_user_avatar=ud.avatar_url,description=description,language=language,simple_reason=simple_reason,detailed_reason=detailed_reason,contact_link=contact_link,issue=issue,state=state) 62 | pi.put() 63 | vid = pi.key().id() 64 | pi.uid=str(vid) 65 | pi.views_of = old_view_of 66 | pi.views_gh = old_views_gh 67 | pi.put() 68 | self.redirect('/') 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /handlers/RepoHandler.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | from config import * 3 | from routes import * 4 | from handlers import * 5 | from datetime import timedelta 6 | 7 | 8 | class RepoHandler(BaseHandler): 9 | def get(self): 10 | username="" 11 | fullname="" 12 | avatar_url="" 13 | if self.session.get('username'): 14 | username_session = self.session.get('username') 15 | navdata = db.GqlQuery("SELECT * FROM UserData WHERE username= :u",u=username_session).get() 16 | username = navdata.username 17 | fullname=navdata.fullname 18 | avatar_url = navdata.avatar_url 19 | current_url = self.request.url 20 | promoted_repo_uid = current_url.split('/')[4] 21 | verify = db.GqlQuery("SELECT * FROM PromotedRepos WHERE uid= :r",r=promoted_repo_uid).fetch(limit=2) 22 | 23 | 24 | if len(verify) > 0: 25 | clicked = self.request.cookies.get(str(promoted_repo_uid)) 26 | repodata = db.GqlQuery("SELECT * FROM PromotedRepos WHERE uid= :r",r=promoted_repo_uid) 27 | repodata_views = repodata.get() 28 | genre = repodata_views.genre 29 | difficulty = repodata_views.is_beginner 30 | if clicked != 'True': 31 | self.response.set_cookie(str(promoted_repo_uid),'True',max_age=10800,path='/') 32 | repodata_views.views_of += 1 33 | repodata_views.put() 34 | self.render('repo_info.html',repodata=repodata,genre=genre,difficulty=difficulty,username=username,fullname=fullname,avatar_url=avatar_url) 35 | else: 36 | self.response.out.write("Repository/Issue with such name hasn't yet been promoted!") 37 | return 38 | 39 | 40 | class GitHubView(BaseHandler): 41 | def get(self): 42 | current_url = self.request.url 43 | uid = current_url.split('?')[0].split('/')[4] 44 | url = current_url.split('?')[1].split('=')[1] 45 | clicked = self.request.cookies.get(str(uid+'gh')) 46 | if clicked != 'True': 47 | self.response.set_cookie(str(uid+'gh'),'True',max_age=10800,path='/') 48 | repodata_views = db.GqlQuery("SELECT * FROM PromotedRepos WHERE uid= :u",u=uid).get() 49 | repodata_views.views_gh += 1 50 | repodata_views.put() 51 | self.redirect(url) 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /handlers/__init__.py: -------------------------------------------------------------------------------- 1 | from BaseHandler import * 2 | from LoginHandler import * 3 | from MainHandler import * 4 | from ProfileHandler import * 5 | from PromoteHandler import * 6 | from LogoutHandler import * 7 | from RepoHandler import * 8 | from RepoEditHandler import * -------------------------------------------------------------------------------- /imports.py: -------------------------------------------------------------------------------- 1 | import webapp2 2 | import jinja2 3 | import requests 4 | import os 5 | import sys 6 | import time 7 | import logging 8 | import urllib2 9 | import json 10 | import re 11 | from operator import itemgetter 12 | from datetime import datetime 13 | from google.appengine.ext import db 14 | from webapp2_extras import sessions 15 | from google.appengine.api import mail 16 | 17 | template_dir = os.path.join(os.path.dirname(__file__), 'templates') 18 | jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), 19 | autoescape = True) -------------------------------------------------------------------------------- /index.yaml: -------------------------------------------------------------------------------- 1 | indexes: 2 | - kind: PromotedRepos 3 | properties: 4 | - name: language_tag 5 | - name: promoted_time 6 | direction: desc -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #Bismillah 2 | 3 | from imports import * 4 | from config import * 5 | from routes import * 6 | from handlers import * 7 | 8 | 9 | app = webapp2.WSGIApplication(routes,config=config, debug=True) -------------------------------------------------------------------------------- /models/Datastore.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | from config import * 3 | from routes import * 4 | from handlers import * 5 | 6 | 7 | class UserData(db.Model): 8 | username = db.StringProperty() 9 | email = db.StringProperty() 10 | fullname = db.StringProperty() 11 | website = db.StringProperty() 12 | location = db.StringProperty() 13 | lang_list = db.ListProperty(str,default=[]) 14 | public_repos = db.StringProperty() 15 | followers = db.StringProperty() 16 | following = db.StringProperty() 17 | avatar_url = db.StringProperty() 18 | access_token = db.StringProperty() 19 | orgs = db.ListProperty(str,default=[]) 20 | 21 | 22 | class RepoData(db.Model): 23 | reponame=db.StringProperty() 24 | repo_html_url=db.StringProperty() 25 | username = db.StringProperty() 26 | language = db.StringProperty() 27 | forks = db.StringProperty() 28 | stars = db.StringProperty() 29 | website = db.StringProperty() 30 | description = db.StringProperty() 31 | 32 | 33 | class PromotedRepos(db.Model): 34 | promoting_user = db.StringProperty() 35 | reponame = db.StringProperty() 36 | uid = db.StringProperty() 37 | language = db.StringProperty() 38 | is_beginner = db.StringProperty() 39 | repo_html_url=db.StringProperty() 40 | description=db.StringProperty(multiline=True) 41 | simple_reason = db.StringProperty() 42 | detailed_reason = db.StringProperty(multiline=True) 43 | promoted_time = db.DateTimeProperty(auto_now_add=True) 44 | contact_link = db.StringProperty() 45 | promoting_user_avatar = db.StringProperty() 46 | issue = db.StringProperty() 47 | state = db.StringProperty() 48 | genre = db.StringProperty() 49 | views_of = db.IntegerProperty(default=0) 50 | views_gh = db.IntegerProperty(default=0) 51 | hof = db.BooleanProperty() 52 | -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | from Datastore import * -------------------------------------------------------------------------------- /path.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | 3 | template_dir = os.path.join(os.path.dirname(__file__), 'templates') 4 | jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), 5 | autoescape = True) -------------------------------------------------------------------------------- /requests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # __ 4 | # /__) _ _ _ _ _/ _ 5 | # / ( (- (/ (/ (- _) / _) 6 | # / 7 | 8 | """ 9 | requests HTTP library 10 | ~~~~~~~~~~~~~~~~~~~~~ 11 | 12 | Requests is an HTTP library, written in Python, for human beings. Basic GET 13 | usage: 14 | 15 | >>> import requests 16 | >>> r = requests.get('http://python.org') 17 | >>> r.status_code 18 | 200 19 | >>> 'Python is a programming language' in r.content 20 | True 21 | 22 | ... or POST: 23 | 24 | >>> payload = dict(key1='value1', key2='value2') 25 | >>> r = requests.post("http://httpbin.org/post", data=payload) 26 | >>> print(r.text) 27 | { 28 | ... 29 | "form": { 30 | "key2": "value2", 31 | "key1": "value1" 32 | }, 33 | ... 34 | } 35 | 36 | The other HTTP methods are supported - see `requests.api`. Full documentation 37 | is at . 38 | 39 | :copyright: (c) 2014 by Kenneth Reitz. 40 | :license: Apache 2.0, see LICENSE for more details. 41 | 42 | """ 43 | 44 | __title__ = 'requests' 45 | __version__ = '2.3.0' 46 | __build__ = 0x020300 47 | __author__ = 'Kenneth Reitz' 48 | __license__ = 'Apache 2.0' 49 | __copyright__ = 'Copyright 2014 Kenneth Reitz' 50 | 51 | # Attempt to enable urllib3's SNI support, if possible 52 | try: 53 | from .packages.urllib3.contrib import pyopenssl 54 | pyopenssl.inject_into_urllib3() 55 | except ImportError: 56 | pass 57 | 58 | from . import utils 59 | from .models import Request, Response, PreparedRequest 60 | from .api import request, get, head, post, patch, put, delete, options 61 | from .sessions import session, Session 62 | from .status_codes import codes 63 | from .exceptions import ( 64 | RequestException, Timeout, URLRequired, 65 | TooManyRedirects, HTTPError, ConnectionError 66 | ) 67 | 68 | # Set default logging handler to avoid "No handler found" warnings. 69 | import logging 70 | try: # Python 2.7+ 71 | from logging import NullHandler 72 | except ImportError: 73 | class NullHandler(logging.Handler): 74 | def emit(self, record): 75 | pass 76 | 77 | logging.getLogger(__name__).addHandler(NullHandler()) 78 | -------------------------------------------------------------------------------- /requests/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/__init__.pyc -------------------------------------------------------------------------------- /requests/adapters.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/adapters.pyc -------------------------------------------------------------------------------- /requests/api.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.api 5 | ~~~~~~~~~~~~ 6 | 7 | This module implements the Requests API. 8 | 9 | :copyright: (c) 2012 by Kenneth Reitz. 10 | :license: Apache2, see LICENSE for more details. 11 | 12 | """ 13 | 14 | from . import sessions 15 | 16 | 17 | def request(method, url, **kwargs): 18 | """Constructs and sends a :class:`Request `. 19 | Returns :class:`Response ` object. 20 | 21 | :param method: method for the new :class:`Request` object. 22 | :param url: URL for the new :class:`Request` object. 23 | :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. 24 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. 25 | :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. 26 | :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. 27 | :param files: (optional) Dictionary of 'name': file-like-objects (or {'name': ('filename', fileobj)}) for multipart encoding upload. 28 | :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. 29 | :param timeout: (optional) Float describing the timeout of the request in seconds. 30 | :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. 31 | :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. 32 | :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided. 33 | :param stream: (optional) if ``False``, the response content will be immediately downloaded. 34 | :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. 35 | 36 | Usage:: 37 | 38 | >>> import requests 39 | >>> req = requests.request('GET', 'http://httpbin.org/get') 40 | 41 | """ 42 | 43 | session = sessions.Session() 44 | return session.request(method=method, url=url, **kwargs) 45 | 46 | 47 | def get(url, **kwargs): 48 | """Sends a GET request. Returns :class:`Response` object. 49 | 50 | :param url: URL for the new :class:`Request` object. 51 | :param \*\*kwargs: Optional arguments that ``request`` takes. 52 | """ 53 | 54 | kwargs.setdefault('allow_redirects', True) 55 | return request('get', url, **kwargs) 56 | 57 | 58 | def options(url, **kwargs): 59 | """Sends a OPTIONS request. Returns :class:`Response` object. 60 | 61 | :param url: URL for the new :class:`Request` object. 62 | :param \*\*kwargs: Optional arguments that ``request`` takes. 63 | """ 64 | 65 | kwargs.setdefault('allow_redirects', True) 66 | return request('options', url, **kwargs) 67 | 68 | 69 | def head(url, **kwargs): 70 | """Sends a HEAD request. Returns :class:`Response` object. 71 | 72 | :param url: URL for the new :class:`Request` object. 73 | :param \*\*kwargs: Optional arguments that ``request`` takes. 74 | """ 75 | 76 | kwargs.setdefault('allow_redirects', False) 77 | return request('head', url, **kwargs) 78 | 79 | 80 | def post(url, data=None, **kwargs): 81 | """Sends a POST request. Returns :class:`Response` object. 82 | 83 | :param url: URL for the new :class:`Request` object. 84 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. 85 | :param \*\*kwargs: Optional arguments that ``request`` takes. 86 | """ 87 | 88 | return request('post', url, data=data, **kwargs) 89 | 90 | 91 | def put(url, data=None, **kwargs): 92 | """Sends a PUT request. Returns :class:`Response` object. 93 | 94 | :param url: URL for the new :class:`Request` object. 95 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. 96 | :param \*\*kwargs: Optional arguments that ``request`` takes. 97 | """ 98 | 99 | return request('put', url, data=data, **kwargs) 100 | 101 | 102 | def patch(url, data=None, **kwargs): 103 | """Sends a PATCH request. Returns :class:`Response` object. 104 | 105 | :param url: URL for the new :class:`Request` object. 106 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. 107 | :param \*\*kwargs: Optional arguments that ``request`` takes. 108 | """ 109 | 110 | return request('patch', url, data=data, **kwargs) 111 | 112 | 113 | def delete(url, **kwargs): 114 | """Sends a DELETE request. Returns :class:`Response` object. 115 | 116 | :param url: URL for the new :class:`Request` object. 117 | :param \*\*kwargs: Optional arguments that ``request`` takes. 118 | """ 119 | 120 | return request('delete', url, **kwargs) 121 | -------------------------------------------------------------------------------- /requests/api.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/api.pyc -------------------------------------------------------------------------------- /requests/auth.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.auth 5 | ~~~~~~~~~~~~~ 6 | 7 | This module contains the authentication handlers for Requests. 8 | """ 9 | 10 | import os 11 | import re 12 | import time 13 | import hashlib 14 | 15 | from base64 import b64encode 16 | 17 | from .compat import urlparse, str 18 | from .cookies import extract_cookies_to_jar 19 | from .utils import parse_dict_header 20 | 21 | CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded' 22 | CONTENT_TYPE_MULTI_PART = 'multipart/form-data' 23 | 24 | 25 | def _basic_auth_str(username, password): 26 | """Returns a Basic Auth string.""" 27 | 28 | return 'Basic ' + b64encode(('%s:%s' % (username, password)).encode('latin1')).strip().decode('latin1') 29 | 30 | 31 | class AuthBase(object): 32 | """Base class that all auth implementations derive from""" 33 | 34 | def __call__(self, r): 35 | raise NotImplementedError('Auth hooks must be callable.') 36 | 37 | 38 | class HTTPBasicAuth(AuthBase): 39 | """Attaches HTTP Basic Authentication to the given Request object.""" 40 | def __init__(self, username, password): 41 | self.username = username 42 | self.password = password 43 | 44 | def __call__(self, r): 45 | r.headers['Authorization'] = _basic_auth_str(self.username, self.password) 46 | return r 47 | 48 | 49 | class HTTPProxyAuth(HTTPBasicAuth): 50 | """Attaches HTTP Proxy Authentication to a given Request object.""" 51 | def __call__(self, r): 52 | r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password) 53 | return r 54 | 55 | 56 | class HTTPDigestAuth(AuthBase): 57 | """Attaches HTTP Digest Authentication to the given Request object.""" 58 | def __init__(self, username, password): 59 | self.username = username 60 | self.password = password 61 | self.last_nonce = '' 62 | self.nonce_count = 0 63 | self.chal = {} 64 | self.pos = None 65 | 66 | def build_digest_header(self, method, url): 67 | 68 | realm = self.chal['realm'] 69 | nonce = self.chal['nonce'] 70 | qop = self.chal.get('qop') 71 | algorithm = self.chal.get('algorithm') 72 | opaque = self.chal.get('opaque') 73 | 74 | if algorithm is None: 75 | _algorithm = 'MD5' 76 | else: 77 | _algorithm = algorithm.upper() 78 | # lambdas assume digest modules are imported at the top level 79 | if _algorithm == 'MD5' or _algorithm == 'MD5-SESS': 80 | def md5_utf8(x): 81 | if isinstance(x, str): 82 | x = x.encode('utf-8') 83 | return hashlib.md5(x).hexdigest() 84 | hash_utf8 = md5_utf8 85 | elif _algorithm == 'SHA': 86 | def sha_utf8(x): 87 | if isinstance(x, str): 88 | x = x.encode('utf-8') 89 | return hashlib.sha1(x).hexdigest() 90 | hash_utf8 = sha_utf8 91 | 92 | KD = lambda s, d: hash_utf8("%s:%s" % (s, d)) 93 | 94 | if hash_utf8 is None: 95 | return None 96 | 97 | # XXX not implemented yet 98 | entdig = None 99 | p_parsed = urlparse(url) 100 | path = p_parsed.path 101 | if p_parsed.query: 102 | path += '?' + p_parsed.query 103 | 104 | A1 = '%s:%s:%s' % (self.username, realm, self.password) 105 | A2 = '%s:%s' % (method, path) 106 | 107 | HA1 = hash_utf8(A1) 108 | HA2 = hash_utf8(A2) 109 | 110 | if nonce == self.last_nonce: 111 | self.nonce_count += 1 112 | else: 113 | self.nonce_count = 1 114 | ncvalue = '%08x' % self.nonce_count 115 | s = str(self.nonce_count).encode('utf-8') 116 | s += nonce.encode('utf-8') 117 | s += time.ctime().encode('utf-8') 118 | s += os.urandom(8) 119 | 120 | cnonce = (hashlib.sha1(s).hexdigest()[:16]) 121 | noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, HA2) 122 | if _algorithm == 'MD5-SESS': 123 | HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce)) 124 | 125 | if qop is None: 126 | respdig = KD(HA1, "%s:%s" % (nonce, HA2)) 127 | elif qop == 'auth' or 'auth' in qop.split(','): 128 | respdig = KD(HA1, noncebit) 129 | else: 130 | # XXX handle auth-int. 131 | return None 132 | 133 | self.last_nonce = nonce 134 | 135 | # XXX should the partial digests be encoded too? 136 | base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \ 137 | 'response="%s"' % (self.username, realm, nonce, path, respdig) 138 | if opaque: 139 | base += ', opaque="%s"' % opaque 140 | if algorithm: 141 | base += ', algorithm="%s"' % algorithm 142 | if entdig: 143 | base += ', digest="%s"' % entdig 144 | if qop: 145 | base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce) 146 | 147 | return 'Digest %s' % (base) 148 | 149 | def handle_401(self, r, **kwargs): 150 | """Takes the given response and tries digest-auth, if needed.""" 151 | 152 | if self.pos is not None: 153 | # Rewind the file position indicator of the body to where 154 | # it was to resend the request. 155 | r.request.body.seek(self.pos) 156 | num_401_calls = getattr(self, 'num_401_calls', 1) 157 | s_auth = r.headers.get('www-authenticate', '') 158 | 159 | if 'digest' in s_auth.lower() and num_401_calls < 2: 160 | 161 | setattr(self, 'num_401_calls', num_401_calls + 1) 162 | pat = re.compile(r'digest ', flags=re.IGNORECASE) 163 | self.chal = parse_dict_header(pat.sub('', s_auth, count=1)) 164 | 165 | # Consume content and release the original connection 166 | # to allow our new request to reuse the same one. 167 | r.content 168 | r.raw.release_conn() 169 | prep = r.request.copy() 170 | extract_cookies_to_jar(prep._cookies, r.request, r.raw) 171 | prep.prepare_cookies(prep._cookies) 172 | 173 | prep.headers['Authorization'] = self.build_digest_header( 174 | prep.method, prep.url) 175 | _r = r.connection.send(prep, **kwargs) 176 | _r.history.append(r) 177 | _r.request = prep 178 | 179 | return _r 180 | 181 | setattr(self, 'num_401_calls', 1) 182 | return r 183 | 184 | def __call__(self, r): 185 | # If we have a saved nonce, skip the 401 186 | if self.last_nonce: 187 | r.headers['Authorization'] = self.build_digest_header(r.method, r.url) 188 | try: 189 | self.pos = r.body.tell() 190 | except AttributeError: 191 | pass 192 | r.register_hook('response', self.handle_401) 193 | return r 194 | -------------------------------------------------------------------------------- /requests/auth.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/auth.pyc -------------------------------------------------------------------------------- /requests/certs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | certs.py 6 | ~~~~~~~~ 7 | 8 | This module returns the preferred default CA certificate bundle. 9 | 10 | If you are packaging Requests, e.g., for a Linux distribution or a managed 11 | environment, you can change the definition of where() to return a separately 12 | packaged CA bundle. 13 | """ 14 | 15 | import os.path 16 | 17 | 18 | def where(): 19 | """Return the preferred certificate bundle.""" 20 | # vendored bundle inside Requests 21 | return os.path.join(os.path.dirname(__file__), 'cacert.pem') 22 | 23 | if __name__ == '__main__': 24 | print(where()) 25 | -------------------------------------------------------------------------------- /requests/certs.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/certs.pyc -------------------------------------------------------------------------------- /requests/compat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | pythoncompat 5 | """ 6 | 7 | from .packages import chardet 8 | 9 | import sys 10 | 11 | # ------- 12 | # Pythons 13 | # ------- 14 | 15 | # Syntax sugar. 16 | _ver = sys.version_info 17 | 18 | #: Python 2.x? 19 | is_py2 = (_ver[0] == 2) 20 | 21 | #: Python 3.x? 22 | is_py3 = (_ver[0] == 3) 23 | 24 | #: Python 3.0.x 25 | is_py30 = (is_py3 and _ver[1] == 0) 26 | 27 | #: Python 3.1.x 28 | is_py31 = (is_py3 and _ver[1] == 1) 29 | 30 | #: Python 3.2.x 31 | is_py32 = (is_py3 and _ver[1] == 2) 32 | 33 | #: Python 3.3.x 34 | is_py33 = (is_py3 and _ver[1] == 3) 35 | 36 | #: Python 3.4.x 37 | is_py34 = (is_py3 and _ver[1] == 4) 38 | 39 | #: Python 2.7.x 40 | is_py27 = (is_py2 and _ver[1] == 7) 41 | 42 | #: Python 2.6.x 43 | is_py26 = (is_py2 and _ver[1] == 6) 44 | 45 | #: Python 2.5.x 46 | is_py25 = (is_py2 and _ver[1] == 5) 47 | 48 | #: Python 2.4.x 49 | is_py24 = (is_py2 and _ver[1] == 4) # I'm assuming this is not by choice. 50 | 51 | 52 | # --------- 53 | # Platforms 54 | # --------- 55 | 56 | 57 | # Syntax sugar. 58 | _ver = sys.version.lower() 59 | 60 | is_pypy = ('pypy' in _ver) 61 | is_jython = ('jython' in _ver) 62 | is_ironpython = ('iron' in _ver) 63 | 64 | # Assume CPython, if nothing else. 65 | is_cpython = not any((is_pypy, is_jython, is_ironpython)) 66 | 67 | # Windows-based system. 68 | is_windows = 'win32' in str(sys.platform).lower() 69 | 70 | # Standard Linux 2+ system. 71 | is_linux = ('linux' in str(sys.platform).lower()) 72 | is_osx = ('darwin' in str(sys.platform).lower()) 73 | is_hpux = ('hpux' in str(sys.platform).lower()) # Complete guess. 74 | is_solaris = ('solar==' in str(sys.platform).lower()) # Complete guess. 75 | 76 | try: 77 | import simplejson as json 78 | except ImportError: 79 | import json 80 | 81 | # --------- 82 | # Specifics 83 | # --------- 84 | 85 | if is_py2: 86 | from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass 87 | from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag 88 | from urllib2 import parse_http_list 89 | import cookielib 90 | from Cookie import Morsel 91 | from StringIO import StringIO 92 | from .packages.urllib3.packages.ordered_dict import OrderedDict 93 | from httplib import IncompleteRead 94 | 95 | builtin_str = str 96 | bytes = str 97 | str = unicode 98 | basestring = basestring 99 | numeric_types = (int, long, float) 100 | 101 | 102 | elif is_py3: 103 | from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag 104 | from urllib.request import parse_http_list, getproxies, proxy_bypass 105 | from http import cookiejar as cookielib 106 | from http.cookies import Morsel 107 | from io import StringIO 108 | from collections import OrderedDict 109 | from http.client import IncompleteRead 110 | 111 | builtin_str = str 112 | str = str 113 | bytes = bytes 114 | basestring = (str, bytes) 115 | numeric_types = (int, float) 116 | -------------------------------------------------------------------------------- /requests/compat.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/compat.pyc -------------------------------------------------------------------------------- /requests/cookies.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/cookies.pyc -------------------------------------------------------------------------------- /requests/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.exceptions 5 | ~~~~~~~~~~~~~~~~~~~ 6 | 7 | This module contains the set of Requests' exceptions. 8 | 9 | """ 10 | from .packages.urllib3.exceptions import HTTPError as BaseHTTPError 11 | 12 | 13 | class RequestException(IOError): 14 | """There was an ambiguous exception that occurred while handling your 15 | request.""" 16 | 17 | def __init__(self, *args, **kwargs): 18 | """ 19 | Initialize RequestException with `request` and `response` objects. 20 | """ 21 | response = kwargs.pop('response', None) 22 | self.response = response 23 | self.request = kwargs.pop('request', None) 24 | if (response is not None and not self.request and 25 | hasattr(response, 'request')): 26 | self.request = self.response.request 27 | super(RequestException, self).__init__(*args, **kwargs) 28 | 29 | 30 | class HTTPError(RequestException): 31 | """An HTTP error occurred.""" 32 | 33 | 34 | class ConnectionError(RequestException): 35 | """A Connection error occurred.""" 36 | 37 | 38 | class ProxyError(ConnectionError): 39 | """A proxy error occurred.""" 40 | 41 | 42 | class SSLError(ConnectionError): 43 | """An SSL error occurred.""" 44 | 45 | 46 | class Timeout(RequestException): 47 | """The request timed out.""" 48 | 49 | 50 | class URLRequired(RequestException): 51 | """A valid URL is required to make a request.""" 52 | 53 | 54 | class TooManyRedirects(RequestException): 55 | """Too many redirects.""" 56 | 57 | 58 | class MissingSchema(RequestException, ValueError): 59 | """The URL schema (e.g. http or https) is missing.""" 60 | 61 | 62 | class InvalidSchema(RequestException, ValueError): 63 | """See defaults.py for valid schemas.""" 64 | 65 | 66 | class InvalidURL(RequestException, ValueError): 67 | """ The URL provided was somehow invalid. """ 68 | 69 | 70 | class ChunkedEncodingError(RequestException): 71 | """The server declared chunked encoding but sent an invalid chunk.""" 72 | 73 | 74 | class ContentDecodingError(RequestException, BaseHTTPError): 75 | """Failed to decode response content""" 76 | -------------------------------------------------------------------------------- /requests/exceptions.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/exceptions.pyc -------------------------------------------------------------------------------- /requests/hooks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.hooks 5 | ~~~~~~~~~~~~~~ 6 | 7 | This module provides the capabilities for the Requests hooks system. 8 | 9 | Available hooks: 10 | 11 | ``response``: 12 | The response generated from a Request. 13 | 14 | """ 15 | 16 | 17 | HOOKS = ['response'] 18 | 19 | 20 | def default_hooks(): 21 | hooks = {} 22 | for event in HOOKS: 23 | hooks[event] = [] 24 | return hooks 25 | 26 | # TODO: response is the only one 27 | 28 | 29 | def dispatch_hook(key, hooks, hook_data, **kwargs): 30 | """Dispatches a hook dictionary on a given piece of data.""" 31 | 32 | hooks = hooks or dict() 33 | 34 | if key in hooks: 35 | hooks = hooks.get(key) 36 | 37 | if hasattr(hooks, '__call__'): 38 | hooks = [hooks] 39 | 40 | for hook in hooks: 41 | _hook_data = hook(hook_data, **kwargs) 42 | if _hook_data is not None: 43 | hook_data = _hook_data 44 | 45 | return hook_data 46 | -------------------------------------------------------------------------------- /requests/hooks.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/hooks.pyc -------------------------------------------------------------------------------- /requests/models.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/models.pyc -------------------------------------------------------------------------------- /requests/packages/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from . import urllib3 4 | -------------------------------------------------------------------------------- /requests/packages/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/__init__.pyc -------------------------------------------------------------------------------- /requests/packages/chardet/__init__.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # This library is free software; you can redistribute it and/or 3 | # modify it under the terms of the GNU Lesser General Public 4 | # License as published by the Free Software Foundation; either 5 | # version 2.1 of the License, or (at your option) any later version. 6 | # 7 | # This library is distributed in the hope that it will be useful, 8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | # Lesser General Public License for more details. 11 | # 12 | # You should have received a copy of the GNU Lesser General Public 13 | # License along with this library; if not, write to the Free Software 14 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 15 | # 02110-1301 USA 16 | ######################### END LICENSE BLOCK ######################### 17 | 18 | __version__ = "2.2.1" 19 | from sys import version_info 20 | 21 | 22 | def detect(aBuf): 23 | if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or 24 | (version_info >= (3, 0) and not isinstance(aBuf, bytes))): 25 | raise ValueError('Expected a bytes object, not a unicode object') 26 | 27 | from . import universaldetector 28 | u = universaldetector.UniversalDetector() 29 | u.reset() 30 | u.feed(aBuf) 31 | u.close() 32 | return u.result 33 | -------------------------------------------------------------------------------- /requests/packages/chardet/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/chardet/__init__.pyc -------------------------------------------------------------------------------- /requests/packages/chardet/big5prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Communicator client code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import Big5DistributionAnalysis 31 | from .mbcssm import Big5SMModel 32 | 33 | 34 | class Big5Prober(MultiByteCharSetProber): 35 | def __init__(self): 36 | MultiByteCharSetProber.__init__(self) 37 | self._mCodingSM = CodingStateMachine(Big5SMModel) 38 | self._mDistributionAnalyzer = Big5DistributionAnalysis() 39 | self.reset() 40 | 41 | def get_charset_name(self): 42 | return "Big5" 43 | -------------------------------------------------------------------------------- /requests/packages/chardet/chardetect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Script which takes one or more file paths and reports on their detected 4 | encodings 5 | 6 | Example:: 7 | 8 | % chardetect somefile someotherfile 9 | somefile: windows-1252 with confidence 0.5 10 | someotherfile: ascii with confidence 1.0 11 | 12 | If no paths are provided, it takes its input from stdin. 13 | 14 | """ 15 | from io import open 16 | from sys import argv, stdin 17 | 18 | from chardet.universaldetector import UniversalDetector 19 | 20 | 21 | def description_of(file, name='stdin'): 22 | """Return a string describing the probable encoding of a file.""" 23 | u = UniversalDetector() 24 | for line in file: 25 | u.feed(line) 26 | u.close() 27 | result = u.result 28 | if result['encoding']: 29 | return '%s: %s with confidence %s' % (name, 30 | result['encoding'], 31 | result['confidence']) 32 | else: 33 | return '%s: no result' % name 34 | 35 | 36 | def main(): 37 | if len(argv) <= 1: 38 | print(description_of(stdin)) 39 | else: 40 | for path in argv[1:]: 41 | with open(path, 'rb') as f: 42 | print(description_of(f, path)) 43 | 44 | 45 | if __name__ == '__main__': 46 | main() 47 | -------------------------------------------------------------------------------- /requests/packages/chardet/charsetgroupprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Communicator client code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from . import constants 29 | import sys 30 | from .charsetprober import CharSetProber 31 | 32 | 33 | class CharSetGroupProber(CharSetProber): 34 | def __init__(self): 35 | CharSetProber.__init__(self) 36 | self._mActiveNum = 0 37 | self._mProbers = [] 38 | self._mBestGuessProber = None 39 | 40 | def reset(self): 41 | CharSetProber.reset(self) 42 | self._mActiveNum = 0 43 | for prober in self._mProbers: 44 | if prober: 45 | prober.reset() 46 | prober.active = True 47 | self._mActiveNum += 1 48 | self._mBestGuessProber = None 49 | 50 | def get_charset_name(self): 51 | if not self._mBestGuessProber: 52 | self.get_confidence() 53 | if not self._mBestGuessProber: 54 | return None 55 | # self._mBestGuessProber = self._mProbers[0] 56 | return self._mBestGuessProber.get_charset_name() 57 | 58 | def feed(self, aBuf): 59 | for prober in self._mProbers: 60 | if not prober: 61 | continue 62 | if not prober.active: 63 | continue 64 | st = prober.feed(aBuf) 65 | if not st: 66 | continue 67 | if st == constants.eFoundIt: 68 | self._mBestGuessProber = prober 69 | return self.get_state() 70 | elif st == constants.eNotMe: 71 | prober.active = False 72 | self._mActiveNum -= 1 73 | if self._mActiveNum <= 0: 74 | self._mState = constants.eNotMe 75 | return self.get_state() 76 | return self.get_state() 77 | 78 | def get_confidence(self): 79 | st = self.get_state() 80 | if st == constants.eFoundIt: 81 | return 0.99 82 | elif st == constants.eNotMe: 83 | return 0.01 84 | bestConf = 0.0 85 | self._mBestGuessProber = None 86 | for prober in self._mProbers: 87 | if not prober: 88 | continue 89 | if not prober.active: 90 | if constants._debug: 91 | sys.stderr.write(prober.get_charset_name() 92 | + ' not active\n') 93 | continue 94 | cf = prober.get_confidence() 95 | if constants._debug: 96 | sys.stderr.write('%s confidence = %s\n' % 97 | (prober.get_charset_name(), cf)) 98 | if bestConf < cf: 99 | bestConf = cf 100 | self._mBestGuessProber = prober 101 | if not self._mBestGuessProber: 102 | return 0.0 103 | return bestConf 104 | # else: 105 | # self._mBestGuessProber = self._mProbers[0] 106 | # return self._mBestGuessProber.get_confidence() 107 | -------------------------------------------------------------------------------- /requests/packages/chardet/charsetprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | from . import constants 30 | import re 31 | 32 | 33 | class CharSetProber: 34 | def __init__(self): 35 | pass 36 | 37 | def reset(self): 38 | self._mState = constants.eDetecting 39 | 40 | def get_charset_name(self): 41 | return None 42 | 43 | def feed(self, aBuf): 44 | pass 45 | 46 | def get_state(self): 47 | return self._mState 48 | 49 | def get_confidence(self): 50 | return 0.0 51 | 52 | def filter_high_bit_only(self, aBuf): 53 | aBuf = re.sub(b'([\x00-\x7F])+', b' ', aBuf) 54 | return aBuf 55 | 56 | def filter_without_english_letters(self, aBuf): 57 | aBuf = re.sub(b'([A-Za-z])+', b' ', aBuf) 58 | return aBuf 59 | 60 | def filter_with_english_letters(self, aBuf): 61 | # TODO 62 | return aBuf 63 | -------------------------------------------------------------------------------- /requests/packages/chardet/codingstatemachine.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .constants import eStart 29 | from .compat import wrap_ord 30 | 31 | 32 | class CodingStateMachine: 33 | def __init__(self, sm): 34 | self._mModel = sm 35 | self._mCurrentBytePos = 0 36 | self._mCurrentCharLen = 0 37 | self.reset() 38 | 39 | def reset(self): 40 | self._mCurrentState = eStart 41 | 42 | def next_state(self, c): 43 | # for each byte we get its class 44 | # if it is first byte, we also get byte length 45 | # PY3K: aBuf is a byte stream, so c is an int, not a byte 46 | byteCls = self._mModel['classTable'][wrap_ord(c)] 47 | if self._mCurrentState == eStart: 48 | self._mCurrentBytePos = 0 49 | self._mCurrentCharLen = self._mModel['charLenTable'][byteCls] 50 | # from byte's class and stateTable, we get its next state 51 | curr_state = (self._mCurrentState * self._mModel['classFactor'] 52 | + byteCls) 53 | self._mCurrentState = self._mModel['stateTable'][curr_state] 54 | self._mCurrentBytePos += 1 55 | return self._mCurrentState 56 | 57 | def get_current_charlen(self): 58 | return self._mCurrentCharLen 59 | 60 | def get_coding_state_machine(self): 61 | return self._mModel['name'] 62 | -------------------------------------------------------------------------------- /requests/packages/chardet/compat.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # Contributor(s): 3 | # Ian Cordasco - port to Python 4 | # 5 | # This library is free software; you can redistribute it and/or 6 | # modify it under the terms of the GNU Lesser General Public 7 | # License as published by the Free Software Foundation; either 8 | # version 2.1 of the License, or (at your option) any later version. 9 | # 10 | # This library is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | # Lesser General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU Lesser General Public 16 | # License along with this library; if not, write to the Free Software 17 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 18 | # 02110-1301 USA 19 | ######################### END LICENSE BLOCK ######################### 20 | 21 | import sys 22 | 23 | 24 | if sys.version_info < (3, 0): 25 | base_str = (str, unicode) 26 | else: 27 | base_str = (bytes, str) 28 | 29 | 30 | def wrap_ord(a): 31 | if sys.version_info < (3, 0) and isinstance(a, base_str): 32 | return ord(a) 33 | else: 34 | return a 35 | -------------------------------------------------------------------------------- /requests/packages/chardet/constants.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | _debug = 0 30 | 31 | eDetecting = 0 32 | eFoundIt = 1 33 | eNotMe = 2 34 | 35 | eStart = 0 36 | eError = 1 37 | eItsMe = 2 38 | 39 | SHORTCUT_THRESHOLD = 0.95 40 | -------------------------------------------------------------------------------- /requests/packages/chardet/cp949prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCKRDistributionAnalysis 31 | from .mbcssm import CP949SMModel 32 | 33 | 34 | class CP949Prober(MultiByteCharSetProber): 35 | def __init__(self): 36 | MultiByteCharSetProber.__init__(self) 37 | self._mCodingSM = CodingStateMachine(CP949SMModel) 38 | # NOTE: CP949 is a superset of EUC-KR, so the distribution should be 39 | # not different. 40 | self._mDistributionAnalyzer = EUCKRDistributionAnalysis() 41 | self.reset() 42 | 43 | def get_charset_name(self): 44 | return "CP949" 45 | -------------------------------------------------------------------------------- /requests/packages/chardet/escprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from . import constants 29 | from .escsm import (HZSMModel, ISO2022CNSMModel, ISO2022JPSMModel, 30 | ISO2022KRSMModel) 31 | from .charsetprober import CharSetProber 32 | from .codingstatemachine import CodingStateMachine 33 | from .compat import wrap_ord 34 | 35 | 36 | class EscCharSetProber(CharSetProber): 37 | def __init__(self): 38 | CharSetProber.__init__(self) 39 | self._mCodingSM = [ 40 | CodingStateMachine(HZSMModel), 41 | CodingStateMachine(ISO2022CNSMModel), 42 | CodingStateMachine(ISO2022JPSMModel), 43 | CodingStateMachine(ISO2022KRSMModel) 44 | ] 45 | self.reset() 46 | 47 | def reset(self): 48 | CharSetProber.reset(self) 49 | for codingSM in self._mCodingSM: 50 | if not codingSM: 51 | continue 52 | codingSM.active = True 53 | codingSM.reset() 54 | self._mActiveSM = len(self._mCodingSM) 55 | self._mDetectedCharset = None 56 | 57 | def get_charset_name(self): 58 | return self._mDetectedCharset 59 | 60 | def get_confidence(self): 61 | if self._mDetectedCharset: 62 | return 0.99 63 | else: 64 | return 0.00 65 | 66 | def feed(self, aBuf): 67 | for c in aBuf: 68 | # PY3K: aBuf is a byte array, so c is an int, not a byte 69 | for codingSM in self._mCodingSM: 70 | if not codingSM: 71 | continue 72 | if not codingSM.active: 73 | continue 74 | codingState = codingSM.next_state(wrap_ord(c)) 75 | if codingState == constants.eError: 76 | codingSM.active = False 77 | self._mActiveSM -= 1 78 | if self._mActiveSM <= 0: 79 | self._mState = constants.eNotMe 80 | return self.get_state() 81 | elif codingState == constants.eItsMe: 82 | self._mState = constants.eFoundIt 83 | self._mDetectedCharset = codingSM.get_coding_state_machine() # nopep8 84 | return self.get_state() 85 | 86 | return self.get_state() 87 | -------------------------------------------------------------------------------- /requests/packages/chardet/eucjpprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | import sys 29 | from . import constants 30 | from .mbcharsetprober import MultiByteCharSetProber 31 | from .codingstatemachine import CodingStateMachine 32 | from .chardistribution import EUCJPDistributionAnalysis 33 | from .jpcntx import EUCJPContextAnalysis 34 | from .mbcssm import EUCJPSMModel 35 | 36 | 37 | class EUCJPProber(MultiByteCharSetProber): 38 | def __init__(self): 39 | MultiByteCharSetProber.__init__(self) 40 | self._mCodingSM = CodingStateMachine(EUCJPSMModel) 41 | self._mDistributionAnalyzer = EUCJPDistributionAnalysis() 42 | self._mContextAnalyzer = EUCJPContextAnalysis() 43 | self.reset() 44 | 45 | def reset(self): 46 | MultiByteCharSetProber.reset(self) 47 | self._mContextAnalyzer.reset() 48 | 49 | def get_charset_name(self): 50 | return "EUC-JP" 51 | 52 | def feed(self, aBuf): 53 | aLen = len(aBuf) 54 | for i in range(0, aLen): 55 | # PY3K: aBuf is a byte array, so aBuf[i] is an int, not a byte 56 | codingState = self._mCodingSM.next_state(aBuf[i]) 57 | if codingState == constants.eError: 58 | if constants._debug: 59 | sys.stderr.write(self.get_charset_name() 60 | + ' prober hit error at byte ' + str(i) 61 | + '\n') 62 | self._mState = constants.eNotMe 63 | break 64 | elif codingState == constants.eItsMe: 65 | self._mState = constants.eFoundIt 66 | break 67 | elif codingState == constants.eStart: 68 | charLen = self._mCodingSM.get_current_charlen() 69 | if i == 0: 70 | self._mLastChar[1] = aBuf[0] 71 | self._mContextAnalyzer.feed(self._mLastChar, charLen) 72 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen) 73 | else: 74 | self._mContextAnalyzer.feed(aBuf[i - 1:i + 1], charLen) 75 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], 76 | charLen) 77 | 78 | self._mLastChar[0] = aBuf[aLen - 1] 79 | 80 | if self.get_state() == constants.eDetecting: 81 | if (self._mContextAnalyzer.got_enough_data() and 82 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): 83 | self._mState = constants.eFoundIt 84 | 85 | return self.get_state() 86 | 87 | def get_confidence(self): 88 | contxtCf = self._mContextAnalyzer.get_confidence() 89 | distribCf = self._mDistributionAnalyzer.get_confidence() 90 | return max(contxtCf, distribCf) 91 | -------------------------------------------------------------------------------- /requests/packages/chardet/euckrprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCKRDistributionAnalysis 31 | from .mbcssm import EUCKRSMModel 32 | 33 | 34 | class EUCKRProber(MultiByteCharSetProber): 35 | def __init__(self): 36 | MultiByteCharSetProber.__init__(self) 37 | self._mCodingSM = CodingStateMachine(EUCKRSMModel) 38 | self._mDistributionAnalyzer = EUCKRDistributionAnalysis() 39 | self.reset() 40 | 41 | def get_charset_name(self): 42 | return "EUC-KR" 43 | -------------------------------------------------------------------------------- /requests/packages/chardet/euctwprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCTWDistributionAnalysis 31 | from .mbcssm import EUCTWSMModel 32 | 33 | class EUCTWProber(MultiByteCharSetProber): 34 | def __init__(self): 35 | MultiByteCharSetProber.__init__(self) 36 | self._mCodingSM = CodingStateMachine(EUCTWSMModel) 37 | self._mDistributionAnalyzer = EUCTWDistributionAnalysis() 38 | self.reset() 39 | 40 | def get_charset_name(self): 41 | return "EUC-TW" 42 | -------------------------------------------------------------------------------- /requests/packages/chardet/gb2312prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import GB2312DistributionAnalysis 31 | from .mbcssm import GB2312SMModel 32 | 33 | class GB2312Prober(MultiByteCharSetProber): 34 | def __init__(self): 35 | MultiByteCharSetProber.__init__(self) 36 | self._mCodingSM = CodingStateMachine(GB2312SMModel) 37 | self._mDistributionAnalyzer = GB2312DistributionAnalysis() 38 | self.reset() 39 | 40 | def get_charset_name(self): 41 | return "GB2312" 42 | -------------------------------------------------------------------------------- /requests/packages/chardet/latin1prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | from .charsetprober import CharSetProber 30 | from .constants import eNotMe 31 | from .compat import wrap_ord 32 | 33 | FREQ_CAT_NUM = 4 34 | 35 | UDF = 0 # undefined 36 | OTH = 1 # other 37 | ASC = 2 # ascii capital letter 38 | ASS = 3 # ascii small letter 39 | ACV = 4 # accent capital vowel 40 | ACO = 5 # accent capital other 41 | ASV = 6 # accent small vowel 42 | ASO = 7 # accent small other 43 | CLASS_NUM = 8 # total classes 44 | 45 | Latin1_CharToClass = ( 46 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 00 - 07 47 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 08 - 0F 48 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 10 - 17 49 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 18 - 1F 50 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 20 - 27 51 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 28 - 2F 52 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 30 - 37 53 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 38 - 3F 54 | OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 40 - 47 55 | ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 48 - 4F 56 | ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 50 - 57 57 | ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, # 58 - 5F 58 | OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 60 - 67 59 | ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 68 - 6F 60 | ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 70 - 77 61 | ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, # 78 - 7F 62 | OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, # 80 - 87 63 | OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, # 88 - 8F 64 | UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 90 - 97 65 | OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, # 98 - 9F 66 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A0 - A7 67 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A8 - AF 68 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B0 - B7 69 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B8 - BF 70 | ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, # C0 - C7 71 | ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, # C8 - CF 72 | ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, # D0 - D7 73 | ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, # D8 - DF 74 | ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, # E0 - E7 75 | ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, # E8 - EF 76 | ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, # F0 - F7 77 | ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, # F8 - FF 78 | ) 79 | 80 | # 0 : illegal 81 | # 1 : very unlikely 82 | # 2 : normal 83 | # 3 : very likely 84 | Latin1ClassModel = ( 85 | # UDF OTH ASC ASS ACV ACO ASV ASO 86 | 0, 0, 0, 0, 0, 0, 0, 0, # UDF 87 | 0, 3, 3, 3, 3, 3, 3, 3, # OTH 88 | 0, 3, 3, 3, 3, 3, 3, 3, # ASC 89 | 0, 3, 3, 3, 1, 1, 3, 3, # ASS 90 | 0, 3, 3, 3, 1, 2, 1, 2, # ACV 91 | 0, 3, 3, 3, 3, 3, 3, 3, # ACO 92 | 0, 3, 1, 3, 1, 1, 1, 3, # ASV 93 | 0, 3, 1, 3, 1, 1, 3, 3, # ASO 94 | ) 95 | 96 | 97 | class Latin1Prober(CharSetProber): 98 | def __init__(self): 99 | CharSetProber.__init__(self) 100 | self.reset() 101 | 102 | def reset(self): 103 | self._mLastCharClass = OTH 104 | self._mFreqCounter = [0] * FREQ_CAT_NUM 105 | CharSetProber.reset(self) 106 | 107 | def get_charset_name(self): 108 | return "windows-1252" 109 | 110 | def feed(self, aBuf): 111 | aBuf = self.filter_with_english_letters(aBuf) 112 | for c in aBuf: 113 | charClass = Latin1_CharToClass[wrap_ord(c)] 114 | freq = Latin1ClassModel[(self._mLastCharClass * CLASS_NUM) 115 | + charClass] 116 | if freq == 0: 117 | self._mState = eNotMe 118 | break 119 | self._mFreqCounter[freq] += 1 120 | self._mLastCharClass = charClass 121 | 122 | return self.get_state() 123 | 124 | def get_confidence(self): 125 | if self.get_state() == eNotMe: 126 | return 0.01 127 | 128 | total = sum(self._mFreqCounter) 129 | if total < 0.01: 130 | confidence = 0.0 131 | else: 132 | confidence = ((self._mFreqCounter[3] / total) 133 | - (self._mFreqCounter[1] * 20.0 / total)) 134 | if confidence < 0.0: 135 | confidence = 0.0 136 | # lower the confidence of latin1 so that other more accurate 137 | # detector can take priority. 138 | confidence = confidence * 0.5 139 | return confidence 140 | -------------------------------------------------------------------------------- /requests/packages/chardet/mbcharsetprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # Proofpoint, Inc. 13 | # 14 | # This library is free software; you can redistribute it and/or 15 | # modify it under the terms of the GNU Lesser General Public 16 | # License as published by the Free Software Foundation; either 17 | # version 2.1 of the License, or (at your option) any later version. 18 | # 19 | # This library is distributed in the hope that it will be useful, 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 22 | # Lesser General Public License for more details. 23 | # 24 | # You should have received a copy of the GNU Lesser General Public 25 | # License along with this library; if not, write to the Free Software 26 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 27 | # 02110-1301 USA 28 | ######################### END LICENSE BLOCK ######################### 29 | 30 | import sys 31 | from . import constants 32 | from .charsetprober import CharSetProber 33 | 34 | 35 | class MultiByteCharSetProber(CharSetProber): 36 | def __init__(self): 37 | CharSetProber.__init__(self) 38 | self._mDistributionAnalyzer = None 39 | self._mCodingSM = None 40 | self._mLastChar = [0, 0] 41 | 42 | def reset(self): 43 | CharSetProber.reset(self) 44 | if self._mCodingSM: 45 | self._mCodingSM.reset() 46 | if self._mDistributionAnalyzer: 47 | self._mDistributionAnalyzer.reset() 48 | self._mLastChar = [0, 0] 49 | 50 | def get_charset_name(self): 51 | pass 52 | 53 | def feed(self, aBuf): 54 | aLen = len(aBuf) 55 | for i in range(0, aLen): 56 | codingState = self._mCodingSM.next_state(aBuf[i]) 57 | if codingState == constants.eError: 58 | if constants._debug: 59 | sys.stderr.write(self.get_charset_name() 60 | + ' prober hit error at byte ' + str(i) 61 | + '\n') 62 | self._mState = constants.eNotMe 63 | break 64 | elif codingState == constants.eItsMe: 65 | self._mState = constants.eFoundIt 66 | break 67 | elif codingState == constants.eStart: 68 | charLen = self._mCodingSM.get_current_charlen() 69 | if i == 0: 70 | self._mLastChar[1] = aBuf[0] 71 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen) 72 | else: 73 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], 74 | charLen) 75 | 76 | self._mLastChar[0] = aBuf[aLen - 1] 77 | 78 | if self.get_state() == constants.eDetecting: 79 | if (self._mDistributionAnalyzer.got_enough_data() and 80 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): 81 | self._mState = constants.eFoundIt 82 | 83 | return self.get_state() 84 | 85 | def get_confidence(self): 86 | return self._mDistributionAnalyzer.get_confidence() 87 | -------------------------------------------------------------------------------- /requests/packages/chardet/mbcsgroupprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # Proofpoint, Inc. 13 | # 14 | # This library is free software; you can redistribute it and/or 15 | # modify it under the terms of the GNU Lesser General Public 16 | # License as published by the Free Software Foundation; either 17 | # version 2.1 of the License, or (at your option) any later version. 18 | # 19 | # This library is distributed in the hope that it will be useful, 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 22 | # Lesser General Public License for more details. 23 | # 24 | # You should have received a copy of the GNU Lesser General Public 25 | # License along with this library; if not, write to the Free Software 26 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 27 | # 02110-1301 USA 28 | ######################### END LICENSE BLOCK ######################### 29 | 30 | from .charsetgroupprober import CharSetGroupProber 31 | from .utf8prober import UTF8Prober 32 | from .sjisprober import SJISProber 33 | from .eucjpprober import EUCJPProber 34 | from .gb2312prober import GB2312Prober 35 | from .euckrprober import EUCKRProber 36 | from .cp949prober import CP949Prober 37 | from .big5prober import Big5Prober 38 | from .euctwprober import EUCTWProber 39 | 40 | 41 | class MBCSGroupProber(CharSetGroupProber): 42 | def __init__(self): 43 | CharSetGroupProber.__init__(self) 44 | self._mProbers = [ 45 | UTF8Prober(), 46 | SJISProber(), 47 | EUCJPProber(), 48 | GB2312Prober(), 49 | EUCKRProber(), 50 | CP949Prober(), 51 | Big5Prober(), 52 | EUCTWProber() 53 | ] 54 | self.reset() 55 | -------------------------------------------------------------------------------- /requests/packages/chardet/sbcharsetprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | import sys 30 | from . import constants 31 | from .charsetprober import CharSetProber 32 | from .compat import wrap_ord 33 | 34 | SAMPLE_SIZE = 64 35 | SB_ENOUGH_REL_THRESHOLD = 1024 36 | POSITIVE_SHORTCUT_THRESHOLD = 0.95 37 | NEGATIVE_SHORTCUT_THRESHOLD = 0.05 38 | SYMBOL_CAT_ORDER = 250 39 | NUMBER_OF_SEQ_CAT = 4 40 | POSITIVE_CAT = NUMBER_OF_SEQ_CAT - 1 41 | #NEGATIVE_CAT = 0 42 | 43 | 44 | class SingleByteCharSetProber(CharSetProber): 45 | def __init__(self, model, reversed=False, nameProber=None): 46 | CharSetProber.__init__(self) 47 | self._mModel = model 48 | # TRUE if we need to reverse every pair in the model lookup 49 | self._mReversed = reversed 50 | # Optional auxiliary prober for name decision 51 | self._mNameProber = nameProber 52 | self.reset() 53 | 54 | def reset(self): 55 | CharSetProber.reset(self) 56 | # char order of last character 57 | self._mLastOrder = 255 58 | self._mSeqCounters = [0] * NUMBER_OF_SEQ_CAT 59 | self._mTotalSeqs = 0 60 | self._mTotalChar = 0 61 | # characters that fall in our sampling range 62 | self._mFreqChar = 0 63 | 64 | def get_charset_name(self): 65 | if self._mNameProber: 66 | return self._mNameProber.get_charset_name() 67 | else: 68 | return self._mModel['charsetName'] 69 | 70 | def feed(self, aBuf): 71 | if not self._mModel['keepEnglishLetter']: 72 | aBuf = self.filter_without_english_letters(aBuf) 73 | aLen = len(aBuf) 74 | if not aLen: 75 | return self.get_state() 76 | for c in aBuf: 77 | order = self._mModel['charToOrderMap'][wrap_ord(c)] 78 | if order < SYMBOL_CAT_ORDER: 79 | self._mTotalChar += 1 80 | if order < SAMPLE_SIZE: 81 | self._mFreqChar += 1 82 | if self._mLastOrder < SAMPLE_SIZE: 83 | self._mTotalSeqs += 1 84 | if not self._mReversed: 85 | i = (self._mLastOrder * SAMPLE_SIZE) + order 86 | model = self._mModel['precedenceMatrix'][i] 87 | else: # reverse the order of the letters in the lookup 88 | i = (order * SAMPLE_SIZE) + self._mLastOrder 89 | model = self._mModel['precedenceMatrix'][i] 90 | self._mSeqCounters[model] += 1 91 | self._mLastOrder = order 92 | 93 | if self.get_state() == constants.eDetecting: 94 | if self._mTotalSeqs > SB_ENOUGH_REL_THRESHOLD: 95 | cf = self.get_confidence() 96 | if cf > POSITIVE_SHORTCUT_THRESHOLD: 97 | if constants._debug: 98 | sys.stderr.write('%s confidence = %s, we have a' 99 | 'winner\n' % 100 | (self._mModel['charsetName'], cf)) 101 | self._mState = constants.eFoundIt 102 | elif cf < NEGATIVE_SHORTCUT_THRESHOLD: 103 | if constants._debug: 104 | sys.stderr.write('%s confidence = %s, below negative' 105 | 'shortcut threshhold %s\n' % 106 | (self._mModel['charsetName'], cf, 107 | NEGATIVE_SHORTCUT_THRESHOLD)) 108 | self._mState = constants.eNotMe 109 | 110 | return self.get_state() 111 | 112 | def get_confidence(self): 113 | r = 0.01 114 | if self._mTotalSeqs > 0: 115 | r = ((1.0 * self._mSeqCounters[POSITIVE_CAT]) / self._mTotalSeqs 116 | / self._mModel['mTypicalPositiveRatio']) 117 | r = r * self._mFreqChar / self._mTotalChar 118 | if r >= 1.0: 119 | r = 0.99 120 | return r 121 | -------------------------------------------------------------------------------- /requests/packages/chardet/sbcsgroupprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | from .charsetgroupprober import CharSetGroupProber 30 | from .sbcharsetprober import SingleByteCharSetProber 31 | from .langcyrillicmodel import (Win1251CyrillicModel, Koi8rModel, 32 | Latin5CyrillicModel, MacCyrillicModel, 33 | Ibm866Model, Ibm855Model) 34 | from .langgreekmodel import Latin7GreekModel, Win1253GreekModel 35 | from .langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel 36 | from .langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel 37 | from .langthaimodel import TIS620ThaiModel 38 | from .langhebrewmodel import Win1255HebrewModel 39 | from .hebrewprober import HebrewProber 40 | 41 | 42 | class SBCSGroupProber(CharSetGroupProber): 43 | def __init__(self): 44 | CharSetGroupProber.__init__(self) 45 | self._mProbers = [ 46 | SingleByteCharSetProber(Win1251CyrillicModel), 47 | SingleByteCharSetProber(Koi8rModel), 48 | SingleByteCharSetProber(Latin5CyrillicModel), 49 | SingleByteCharSetProber(MacCyrillicModel), 50 | SingleByteCharSetProber(Ibm866Model), 51 | SingleByteCharSetProber(Ibm855Model), 52 | SingleByteCharSetProber(Latin7GreekModel), 53 | SingleByteCharSetProber(Win1253GreekModel), 54 | SingleByteCharSetProber(Latin5BulgarianModel), 55 | SingleByteCharSetProber(Win1251BulgarianModel), 56 | SingleByteCharSetProber(Latin2HungarianModel), 57 | SingleByteCharSetProber(Win1250HungarianModel), 58 | SingleByteCharSetProber(TIS620ThaiModel), 59 | ] 60 | hebrewProber = HebrewProber() 61 | logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, 62 | False, hebrewProber) 63 | visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, True, 64 | hebrewProber) 65 | hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber) 66 | self._mProbers.extend([hebrewProber, logicalHebrewProber, 67 | visualHebrewProber]) 68 | 69 | self.reset() 70 | -------------------------------------------------------------------------------- /requests/packages/chardet/sjisprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | import sys 29 | from .mbcharsetprober import MultiByteCharSetProber 30 | from .codingstatemachine import CodingStateMachine 31 | from .chardistribution import SJISDistributionAnalysis 32 | from .jpcntx import SJISContextAnalysis 33 | from .mbcssm import SJISSMModel 34 | from . import constants 35 | 36 | 37 | class SJISProber(MultiByteCharSetProber): 38 | def __init__(self): 39 | MultiByteCharSetProber.__init__(self) 40 | self._mCodingSM = CodingStateMachine(SJISSMModel) 41 | self._mDistributionAnalyzer = SJISDistributionAnalysis() 42 | self._mContextAnalyzer = SJISContextAnalysis() 43 | self.reset() 44 | 45 | def reset(self): 46 | MultiByteCharSetProber.reset(self) 47 | self._mContextAnalyzer.reset() 48 | 49 | def get_charset_name(self): 50 | return "SHIFT_JIS" 51 | 52 | def feed(self, aBuf): 53 | aLen = len(aBuf) 54 | for i in range(0, aLen): 55 | codingState = self._mCodingSM.next_state(aBuf[i]) 56 | if codingState == constants.eError: 57 | if constants._debug: 58 | sys.stderr.write(self.get_charset_name() 59 | + ' prober hit error at byte ' + str(i) 60 | + '\n') 61 | self._mState = constants.eNotMe 62 | break 63 | elif codingState == constants.eItsMe: 64 | self._mState = constants.eFoundIt 65 | break 66 | elif codingState == constants.eStart: 67 | charLen = self._mCodingSM.get_current_charlen() 68 | if i == 0: 69 | self._mLastChar[1] = aBuf[0] 70 | self._mContextAnalyzer.feed(self._mLastChar[2 - charLen:], 71 | charLen) 72 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen) 73 | else: 74 | self._mContextAnalyzer.feed(aBuf[i + 1 - charLen:i + 3 75 | - charLen], charLen) 76 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], 77 | charLen) 78 | 79 | self._mLastChar[0] = aBuf[aLen - 1] 80 | 81 | if self.get_state() == constants.eDetecting: 82 | if (self._mContextAnalyzer.got_enough_data() and 83 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): 84 | self._mState = constants.eFoundIt 85 | 86 | return self.get_state() 87 | 88 | def get_confidence(self): 89 | contxtCf = self._mContextAnalyzer.get_confidence() 90 | distribCf = self._mDistributionAnalyzer.get_confidence() 91 | return max(contxtCf, distribCf) 92 | -------------------------------------------------------------------------------- /requests/packages/chardet/utf8prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from . import constants 29 | from .charsetprober import CharSetProber 30 | from .codingstatemachine import CodingStateMachine 31 | from .mbcssm import UTF8SMModel 32 | 33 | ONE_CHAR_PROB = 0.5 34 | 35 | 36 | class UTF8Prober(CharSetProber): 37 | def __init__(self): 38 | CharSetProber.__init__(self) 39 | self._mCodingSM = CodingStateMachine(UTF8SMModel) 40 | self.reset() 41 | 42 | def reset(self): 43 | CharSetProber.reset(self) 44 | self._mCodingSM.reset() 45 | self._mNumOfMBChar = 0 46 | 47 | def get_charset_name(self): 48 | return "utf-8" 49 | 50 | def feed(self, aBuf): 51 | for c in aBuf: 52 | codingState = self._mCodingSM.next_state(c) 53 | if codingState == constants.eError: 54 | self._mState = constants.eNotMe 55 | break 56 | elif codingState == constants.eItsMe: 57 | self._mState = constants.eFoundIt 58 | break 59 | elif codingState == constants.eStart: 60 | if self._mCodingSM.get_current_charlen() >= 2: 61 | self._mNumOfMBChar += 1 62 | 63 | if self.get_state() == constants.eDetecting: 64 | if self.get_confidence() > constants.SHORTCUT_THRESHOLD: 65 | self._mState = constants.eFoundIt 66 | 67 | return self.get_state() 68 | 69 | def get_confidence(self): 70 | unlike = 0.99 71 | if self._mNumOfMBChar < 6: 72 | for i in range(0, self._mNumOfMBChar): 73 | unlike = unlike * ONE_CHAR_PROB 74 | return 1.0 - unlike 75 | else: 76 | return unlike 77 | -------------------------------------------------------------------------------- /requests/packages/urllib3/__init__.py: -------------------------------------------------------------------------------- 1 | # urllib3/__init__.py 2 | # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) 3 | # 4 | # This module is part of urllib3 and is released under 5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php 6 | 7 | """ 8 | urllib3 - Thread-safe connection pooling and re-using. 9 | """ 10 | 11 | __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)' 12 | __license__ = 'MIT' 13 | __version__ = 'dev' 14 | 15 | 16 | from .connectionpool import ( 17 | HTTPConnectionPool, 18 | HTTPSConnectionPool, 19 | connection_from_url 20 | ) 21 | 22 | from . import exceptions 23 | from .filepost import encode_multipart_formdata 24 | from .poolmanager import PoolManager, ProxyManager, proxy_from_url 25 | from .response import HTTPResponse 26 | from .util import make_headers, get_host, Timeout 27 | 28 | 29 | # Set default logging handler to avoid "No handler found" warnings. 30 | import logging 31 | try: # Python 2.7+ 32 | from logging import NullHandler 33 | except ImportError: 34 | class NullHandler(logging.Handler): 35 | def emit(self, record): 36 | pass 37 | 38 | logging.getLogger(__name__).addHandler(NullHandler()) 39 | 40 | def add_stderr_logger(level=logging.DEBUG): 41 | """ 42 | Helper for quickly adding a StreamHandler to the logger. Useful for 43 | debugging. 44 | 45 | Returns the handler after adding it. 46 | """ 47 | # This method needs to be in this __init__.py to get the __name__ correct 48 | # even if urllib3 is vendored within another package. 49 | logger = logging.getLogger(__name__) 50 | handler = logging.StreamHandler() 51 | handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) 52 | logger.addHandler(handler) 53 | logger.setLevel(level) 54 | logger.debug('Added an stderr logging handler to logger: %s' % __name__) 55 | return handler 56 | 57 | # ... Clean up. 58 | del NullHandler 59 | -------------------------------------------------------------------------------- /requests/packages/urllib3/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/__init__.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/_collections.py: -------------------------------------------------------------------------------- 1 | # urllib3/_collections.py 2 | # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) 3 | # 4 | # This module is part of urllib3 and is released under 5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php 6 | 7 | from collections import Mapping, MutableMapping 8 | try: 9 | from threading import RLock 10 | except ImportError: # Platform-specific: No threads available 11 | class RLock: 12 | def __enter__(self): 13 | pass 14 | 15 | def __exit__(self, exc_type, exc_value, traceback): 16 | pass 17 | 18 | 19 | try: # Python 2.7+ 20 | from collections import OrderedDict 21 | except ImportError: 22 | from .packages.ordered_dict import OrderedDict 23 | from .packages.six import itervalues 24 | 25 | 26 | __all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict'] 27 | 28 | 29 | _Null = object() 30 | 31 | 32 | class RecentlyUsedContainer(MutableMapping): 33 | """ 34 | Provides a thread-safe dict-like container which maintains up to 35 | ``maxsize`` keys while throwing away the least-recently-used keys beyond 36 | ``maxsize``. 37 | 38 | :param maxsize: 39 | Maximum number of recent elements to retain. 40 | 41 | :param dispose_func: 42 | Every time an item is evicted from the container, 43 | ``dispose_func(value)`` is called. Callback which will get called 44 | """ 45 | 46 | ContainerCls = OrderedDict 47 | 48 | def __init__(self, maxsize=10, dispose_func=None): 49 | self._maxsize = maxsize 50 | self.dispose_func = dispose_func 51 | 52 | self._container = self.ContainerCls() 53 | self.lock = RLock() 54 | 55 | def __getitem__(self, key): 56 | # Re-insert the item, moving it to the end of the eviction line. 57 | with self.lock: 58 | item = self._container.pop(key) 59 | self._container[key] = item 60 | return item 61 | 62 | def __setitem__(self, key, value): 63 | evicted_value = _Null 64 | with self.lock: 65 | # Possibly evict the existing value of 'key' 66 | evicted_value = self._container.get(key, _Null) 67 | self._container[key] = value 68 | 69 | # If we didn't evict an existing value, we might have to evict the 70 | # least recently used item from the beginning of the container. 71 | if len(self._container) > self._maxsize: 72 | _key, evicted_value = self._container.popitem(last=False) 73 | 74 | if self.dispose_func and evicted_value is not _Null: 75 | self.dispose_func(evicted_value) 76 | 77 | def __delitem__(self, key): 78 | with self.lock: 79 | value = self._container.pop(key) 80 | 81 | if self.dispose_func: 82 | self.dispose_func(value) 83 | 84 | def __len__(self): 85 | with self.lock: 86 | return len(self._container) 87 | 88 | def __iter__(self): 89 | raise NotImplementedError('Iteration over this class is unlikely to be threadsafe.') 90 | 91 | def clear(self): 92 | with self.lock: 93 | # Copy pointers to all values, then wipe the mapping 94 | # under Python 2, this copies the list of values twice :-| 95 | values = list(self._container.values()) 96 | self._container.clear() 97 | 98 | if self.dispose_func: 99 | for value in values: 100 | self.dispose_func(value) 101 | 102 | def keys(self): 103 | with self.lock: 104 | return self._container.keys() 105 | 106 | 107 | class HTTPHeaderDict(MutableMapping): 108 | """ 109 | :param headers: 110 | An iterable of field-value pairs. Must not contain multiple field names 111 | when compared case-insensitively. 112 | 113 | :param kwargs: 114 | Additional field-value pairs to pass in to ``dict.update``. 115 | 116 | A ``dict`` like container for storing HTTP Headers. 117 | 118 | Field names are stored and compared case-insensitively in compliance with 119 | RFC 2616. Iteration provides the first case-sensitive key seen for each 120 | case-insensitive pair. 121 | 122 | Using ``__setitem__`` syntax overwrites fields that compare equal 123 | case-insensitively in order to maintain ``dict``'s api. For fields that 124 | compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add`` 125 | in a loop. 126 | 127 | If multiple fields that are equal case-insensitively are passed to the 128 | constructor or ``.update``, the behavior is undefined and some will be 129 | lost. 130 | 131 | >>> headers = HTTPHeaderDict() 132 | >>> headers.add('Set-Cookie', 'foo=bar') 133 | >>> headers.add('set-cookie', 'baz=quxx') 134 | >>> headers['content-length'] = '7' 135 | >>> headers['SET-cookie'] 136 | 'foo=bar, baz=quxx' 137 | >>> headers['Content-Length'] 138 | '7' 139 | 140 | If you want to access the raw headers with their original casing 141 | for debugging purposes you can access the private ``._data`` attribute 142 | which is a normal python ``dict`` that maps the case-insensitive key to a 143 | list of tuples stored as (case-sensitive-original-name, value). Using the 144 | structure from above as our example: 145 | 146 | >>> headers._data 147 | {'set-cookie': [('Set-Cookie', 'foo=bar'), ('set-cookie', 'baz=quxx')], 148 | 'content-length': [('content-length', '7')]} 149 | """ 150 | 151 | def __init__(self, headers=None, **kwargs): 152 | self._data = {} 153 | if headers is None: 154 | headers = {} 155 | self.update(headers, **kwargs) 156 | 157 | def add(self, key, value): 158 | """Adds a (name, value) pair, doesn't overwrite the value if it already 159 | exists. 160 | 161 | >>> headers = HTTPHeaderDict(foo='bar') 162 | >>> headers.add('Foo', 'baz') 163 | >>> headers['foo'] 164 | 'bar, baz' 165 | """ 166 | self._data.setdefault(key.lower(), []).append((key, value)) 167 | 168 | def getlist(self, key): 169 | """Returns a list of all the values for the named field. Returns an 170 | empty list if the key doesn't exist.""" 171 | return self[key].split(', ') if key in self else [] 172 | 173 | def copy(self): 174 | h = HTTPHeaderDict() 175 | for key in self._data: 176 | for rawkey, value in self._data[key]: 177 | h.add(rawkey, value) 178 | return h 179 | 180 | def __eq__(self, other): 181 | if not isinstance(other, Mapping): 182 | return False 183 | other = HTTPHeaderDict(other) 184 | return dict((k1, self[k1]) for k1 in self._data) == \ 185 | dict((k2, other[k2]) for k2 in other._data) 186 | 187 | def __getitem__(self, key): 188 | values = self._data[key.lower()] 189 | return ', '.join(value[1] for value in values) 190 | 191 | def __setitem__(self, key, value): 192 | self._data[key.lower()] = [(key, value)] 193 | 194 | def __delitem__(self, key): 195 | del self._data[key.lower()] 196 | 197 | def __len__(self): 198 | return len(self._data) 199 | 200 | def __iter__(self): 201 | for headers in itervalues(self._data): 202 | yield headers[0][0] 203 | 204 | def __repr__(self): 205 | return '%s(%r)' % (self.__class__.__name__, dict(self.items())) 206 | -------------------------------------------------------------------------------- /requests/packages/urllib3/_collections.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/_collections.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/connection.py: -------------------------------------------------------------------------------- 1 | # urllib3/connection.py 2 | # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) 3 | # 4 | # This module is part of urllib3 and is released under 5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php 6 | 7 | import sys 8 | import socket 9 | from socket import timeout as SocketTimeout 10 | 11 | try: # Python 3 12 | from http.client import HTTPConnection as _HTTPConnection, HTTPException 13 | except ImportError: 14 | from httplib import HTTPConnection as _HTTPConnection, HTTPException 15 | 16 | class DummyConnection(object): 17 | "Used to detect a failed ConnectionCls import." 18 | pass 19 | 20 | try: # Compiled with SSL? 21 | ssl = None 22 | HTTPSConnection = DummyConnection 23 | 24 | class BaseSSLError(BaseException): 25 | pass 26 | 27 | try: # Python 3 28 | from http.client import HTTPSConnection as _HTTPSConnection 29 | except ImportError: 30 | from httplib import HTTPSConnection as _HTTPSConnection 31 | 32 | import ssl 33 | BaseSSLError = ssl.SSLError 34 | 35 | except (ImportError, AttributeError): # Platform-specific: No SSL. 36 | pass 37 | 38 | from .exceptions import ( 39 | ConnectTimeoutError, 40 | ) 41 | from .packages.ssl_match_hostname import match_hostname 42 | from .packages import six 43 | from .util import ( 44 | assert_fingerprint, 45 | resolve_cert_reqs, 46 | resolve_ssl_version, 47 | ssl_wrap_socket, 48 | ) 49 | 50 | 51 | port_by_scheme = { 52 | 'http': 80, 53 | 'https': 443, 54 | } 55 | 56 | 57 | class HTTPConnection(_HTTPConnection, object): 58 | """ 59 | Based on httplib.HTTPConnection but provides an extra constructor 60 | backwards-compatibility layer between older and newer Pythons. 61 | """ 62 | 63 | default_port = port_by_scheme['http'] 64 | 65 | # By default, disable Nagle's Algorithm. 66 | tcp_nodelay = 1 67 | 68 | def __init__(self, *args, **kw): 69 | if six.PY3: # Python 3 70 | kw.pop('strict', None) 71 | if sys.version_info < (2, 7): # Python 2.6 and older 72 | kw.pop('source_address', None) 73 | 74 | # Pre-set source_address in case we have an older Python like 2.6. 75 | self.source_address = kw.get('source_address') 76 | 77 | # Superclass also sets self.source_address in Python 2.7+. 78 | _HTTPConnection.__init__(self, *args, **kw) 79 | 80 | def _new_conn(self): 81 | """ Establish a socket connection and set nodelay settings on it. 82 | 83 | :return: a new socket connection 84 | """ 85 | extra_args = [] 86 | if self.source_address: # Python 2.7+ 87 | extra_args.append(self.source_address) 88 | 89 | conn = socket.create_connection( 90 | (self.host, self.port), self.timeout, *extra_args) 91 | conn.setsockopt( 92 | socket.IPPROTO_TCP, socket.TCP_NODELAY, self.tcp_nodelay) 93 | 94 | return conn 95 | 96 | def _prepare_conn(self, conn): 97 | self.sock = conn 98 | # the _tunnel_host attribute was added in python 2.6.3 (via 99 | # http://hg.python.org/cpython/rev/0f57b30a152f) so pythons 2.6(0-2) do 100 | # not have them. 101 | if getattr(self, '_tunnel_host', None): 102 | # TODO: Fix tunnel so it doesn't depend on self.sock state. 103 | self._tunnel() 104 | 105 | def connect(self): 106 | conn = self._new_conn() 107 | self._prepare_conn(conn) 108 | 109 | 110 | class HTTPSConnection(HTTPConnection): 111 | default_port = port_by_scheme['https'] 112 | 113 | def __init__(self, host, port=None, key_file=None, cert_file=None, 114 | strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kw): 115 | 116 | HTTPConnection.__init__(self, host, port, strict=strict, 117 | timeout=timeout, **kw) 118 | 119 | self.key_file = key_file 120 | self.cert_file = cert_file 121 | 122 | # Required property for Google AppEngine 1.9.0 which otherwise causes 123 | # HTTPS requests to go out as HTTP. (See Issue #356) 124 | self._protocol = 'https' 125 | 126 | def connect(self): 127 | conn = self._new_conn() 128 | self._prepare_conn(conn) 129 | self.sock = ssl.wrap_socket(conn, self.key_file, self.cert_file) 130 | 131 | 132 | class VerifiedHTTPSConnection(HTTPSConnection): 133 | """ 134 | Based on httplib.HTTPSConnection but wraps the socket with 135 | SSL certification. 136 | """ 137 | cert_reqs = None 138 | ca_certs = None 139 | ssl_version = None 140 | conn_kw = {} 141 | 142 | def set_cert(self, key_file=None, cert_file=None, 143 | cert_reqs=None, ca_certs=None, 144 | assert_hostname=None, assert_fingerprint=None): 145 | 146 | self.key_file = key_file 147 | self.cert_file = cert_file 148 | self.cert_reqs = cert_reqs 149 | self.ca_certs = ca_certs 150 | self.assert_hostname = assert_hostname 151 | self.assert_fingerprint = assert_fingerprint 152 | 153 | def connect(self): 154 | # Add certificate verification 155 | 156 | try: 157 | sock = socket.create_connection( 158 | address=(self.host, self.port), timeout=self.timeout, 159 | **self.conn_kw) 160 | except SocketTimeout: 161 | raise ConnectTimeoutError( 162 | self, "Connection to %s timed out. (connect timeout=%s)" % 163 | (self.host, self.timeout)) 164 | 165 | sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 166 | self.tcp_nodelay) 167 | 168 | resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs) 169 | resolved_ssl_version = resolve_ssl_version(self.ssl_version) 170 | 171 | hostname = self.host 172 | if getattr(self, '_tunnel_host', None): 173 | # _tunnel_host was added in Python 2.6.3 174 | # (See: http://hg.python.org/cpython/rev/0f57b30a152f) 175 | 176 | self.sock = sock 177 | # Calls self._set_hostport(), so self.host is 178 | # self._tunnel_host below. 179 | self._tunnel() 180 | 181 | # Override the host with the one we're requesting data from. 182 | hostname = self._tunnel_host 183 | 184 | # Wrap socket using verification with the root certs in 185 | # trusted_root_certs 186 | self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file, 187 | cert_reqs=resolved_cert_reqs, 188 | ca_certs=self.ca_certs, 189 | server_hostname=hostname, 190 | ssl_version=resolved_ssl_version) 191 | 192 | if resolved_cert_reqs != ssl.CERT_NONE: 193 | if self.assert_fingerprint: 194 | assert_fingerprint(self.sock.getpeercert(binary_form=True), 195 | self.assert_fingerprint) 196 | elif self.assert_hostname is not False: 197 | match_hostname(self.sock.getpeercert(), 198 | self.assert_hostname or hostname) 199 | 200 | 201 | if ssl: 202 | # Make a copy for testing. 203 | UnverifiedHTTPSConnection = HTTPSConnection 204 | HTTPSConnection = VerifiedHTTPSConnection 205 | -------------------------------------------------------------------------------- /requests/packages/urllib3/connection.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/connection.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/connectionpool.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/connectionpool.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/contrib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/contrib/__init__.py -------------------------------------------------------------------------------- /requests/packages/urllib3/contrib/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/contrib/__init__.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/contrib/ntlmpool.py: -------------------------------------------------------------------------------- 1 | # urllib3/contrib/ntlmpool.py 2 | # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) 3 | # 4 | # This module is part of urllib3 and is released under 5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php 6 | 7 | """ 8 | NTLM authenticating pool, contributed by erikcederstran 9 | 10 | Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 11 | """ 12 | 13 | try: 14 | from http.client import HTTPSConnection 15 | except ImportError: 16 | from httplib import HTTPSConnection 17 | from logging import getLogger 18 | from ntlm import ntlm 19 | 20 | from urllib3 import HTTPSConnectionPool 21 | 22 | 23 | log = getLogger(__name__) 24 | 25 | 26 | class NTLMConnectionPool(HTTPSConnectionPool): 27 | """ 28 | Implements an NTLM authentication version of an urllib3 connection pool 29 | """ 30 | 31 | scheme = 'https' 32 | 33 | def __init__(self, user, pw, authurl, *args, **kwargs): 34 | """ 35 | authurl is a random URL on the server that is protected by NTLM. 36 | user is the Windows user, probably in the DOMAIN\\username format. 37 | pw is the password for the user. 38 | """ 39 | super(NTLMConnectionPool, self).__init__(*args, **kwargs) 40 | self.authurl = authurl 41 | self.rawuser = user 42 | user_parts = user.split('\\', 1) 43 | self.domain = user_parts[0].upper() 44 | self.user = user_parts[1] 45 | self.pw = pw 46 | 47 | def _new_conn(self): 48 | # Performs the NTLM handshake that secures the connection. The socket 49 | # must be kept open while requests are performed. 50 | self.num_connections += 1 51 | log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s' % 52 | (self.num_connections, self.host, self.authurl)) 53 | 54 | headers = {} 55 | headers['Connection'] = 'Keep-Alive' 56 | req_header = 'Authorization' 57 | resp_header = 'www-authenticate' 58 | 59 | conn = HTTPSConnection(host=self.host, port=self.port) 60 | 61 | # Send negotiation message 62 | headers[req_header] = ( 63 | 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser)) 64 | log.debug('Request headers: %s' % headers) 65 | conn.request('GET', self.authurl, None, headers) 66 | res = conn.getresponse() 67 | reshdr = dict(res.getheaders()) 68 | log.debug('Response status: %s %s' % (res.status, res.reason)) 69 | log.debug('Response headers: %s' % reshdr) 70 | log.debug('Response data: %s [...]' % res.read(100)) 71 | 72 | # Remove the reference to the socket, so that it can not be closed by 73 | # the response object (we want to keep the socket open) 74 | res.fp = None 75 | 76 | # Server should respond with a challenge message 77 | auth_header_values = reshdr[resp_header].split(', ') 78 | auth_header_value = None 79 | for s in auth_header_values: 80 | if s[:5] == 'NTLM ': 81 | auth_header_value = s[5:] 82 | if auth_header_value is None: 83 | raise Exception('Unexpected %s response header: %s' % 84 | (resp_header, reshdr[resp_header])) 85 | 86 | # Send authentication message 87 | ServerChallenge, NegotiateFlags = \ 88 | ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value) 89 | auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, 90 | self.user, 91 | self.domain, 92 | self.pw, 93 | NegotiateFlags) 94 | headers[req_header] = 'NTLM %s' % auth_msg 95 | log.debug('Request headers: %s' % headers) 96 | conn.request('GET', self.authurl, None, headers) 97 | res = conn.getresponse() 98 | log.debug('Response status: %s %s' % (res.status, res.reason)) 99 | log.debug('Response headers: %s' % dict(res.getheaders())) 100 | log.debug('Response data: %s [...]' % res.read()[:100]) 101 | if res.status != 200: 102 | if res.status == 401: 103 | raise Exception('Server rejected request: wrong ' 104 | 'username or password') 105 | raise Exception('Wrong server response: %s %s' % 106 | (res.status, res.reason)) 107 | 108 | res.fp = None 109 | log.debug('Connection established') 110 | return conn 111 | 112 | def urlopen(self, method, url, body=None, headers=None, retries=3, 113 | redirect=True, assert_same_host=True): 114 | if headers is None: 115 | headers = {} 116 | headers['Connection'] = 'Keep-Alive' 117 | return super(NTLMConnectionPool, self).urlopen(method, url, body, 118 | headers, retries, 119 | redirect, 120 | assert_same_host) 121 | -------------------------------------------------------------------------------- /requests/packages/urllib3/contrib/pyopenssl.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/contrib/pyopenssl.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/exceptions.py: -------------------------------------------------------------------------------- 1 | # urllib3/exceptions.py 2 | # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) 3 | # 4 | # This module is part of urllib3 and is released under 5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php 6 | 7 | 8 | ## Base Exceptions 9 | 10 | class HTTPError(Exception): 11 | "Base exception used by this module." 12 | pass 13 | 14 | 15 | class PoolError(HTTPError): 16 | "Base exception for errors caused within a pool." 17 | def __init__(self, pool, message): 18 | self.pool = pool 19 | HTTPError.__init__(self, "%s: %s" % (pool, message)) 20 | 21 | def __reduce__(self): 22 | # For pickling purposes. 23 | return self.__class__, (None, None) 24 | 25 | 26 | class RequestError(PoolError): 27 | "Base exception for PoolErrors that have associated URLs." 28 | def __init__(self, pool, url, message): 29 | self.url = url 30 | PoolError.__init__(self, pool, message) 31 | 32 | def __reduce__(self): 33 | # For pickling purposes. 34 | return self.__class__, (None, self.url, None) 35 | 36 | 37 | class SSLError(HTTPError): 38 | "Raised when SSL certificate fails in an HTTPS connection." 39 | pass 40 | 41 | 42 | class ProxyError(HTTPError): 43 | "Raised when the connection to a proxy fails." 44 | pass 45 | 46 | 47 | class ConnectionError(HTTPError): 48 | "Raised when a normal connection fails." 49 | pass 50 | 51 | 52 | class DecodeError(HTTPError): 53 | "Raised when automatic decoding based on Content-Type fails." 54 | pass 55 | 56 | 57 | ## Leaf Exceptions 58 | 59 | class MaxRetryError(RequestError): 60 | "Raised when the maximum number of retries is exceeded." 61 | 62 | def __init__(self, pool, url, reason=None): 63 | self.reason = reason 64 | 65 | message = "Max retries exceeded with url: %s" % url 66 | if reason: 67 | message += " (Caused by %s: %s)" % (type(reason), reason) 68 | else: 69 | message += " (Caused by redirect)" 70 | 71 | RequestError.__init__(self, pool, url, message) 72 | 73 | 74 | class HostChangedError(RequestError): 75 | "Raised when an existing pool gets a request for a foreign host." 76 | 77 | def __init__(self, pool, url, retries=3): 78 | message = "Tried to open a foreign host with url: %s" % url 79 | RequestError.__init__(self, pool, url, message) 80 | self.retries = retries 81 | 82 | 83 | class TimeoutStateError(HTTPError): 84 | """ Raised when passing an invalid state to a timeout """ 85 | pass 86 | 87 | 88 | class TimeoutError(HTTPError): 89 | """ Raised when a socket timeout error occurs. 90 | 91 | Catching this error will catch both :exc:`ReadTimeoutErrors 92 | ` and :exc:`ConnectTimeoutErrors `. 93 | """ 94 | pass 95 | 96 | 97 | class ReadTimeoutError(TimeoutError, RequestError): 98 | "Raised when a socket timeout occurs while receiving data from a server" 99 | pass 100 | 101 | 102 | # This timeout error does not have a URL attached and needs to inherit from the 103 | # base HTTPError 104 | class ConnectTimeoutError(TimeoutError): 105 | "Raised when a socket timeout occurs while connecting to a server" 106 | pass 107 | 108 | 109 | class EmptyPoolError(PoolError): 110 | "Raised when a pool runs out of connections and no more are allowed." 111 | pass 112 | 113 | 114 | class ClosedPoolError(PoolError): 115 | "Raised when a request enters a pool after the pool has been closed." 116 | pass 117 | 118 | 119 | class LocationParseError(ValueError, HTTPError): 120 | "Raised when get_host or similar fails to parse the URL input." 121 | 122 | def __init__(self, location): 123 | message = "Failed to parse: %s" % location 124 | HTTPError.__init__(self, message) 125 | 126 | self.location = location 127 | -------------------------------------------------------------------------------- /requests/packages/urllib3/exceptions.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/exceptions.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/fields.py: -------------------------------------------------------------------------------- 1 | # urllib3/fields.py 2 | # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) 3 | # 4 | # This module is part of urllib3 and is released under 5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php 6 | 7 | import email.utils 8 | import mimetypes 9 | 10 | from .packages import six 11 | 12 | 13 | def guess_content_type(filename, default='application/octet-stream'): 14 | """ 15 | Guess the "Content-Type" of a file. 16 | 17 | :param filename: 18 | The filename to guess the "Content-Type" of using :mod:`mimetypes`. 19 | :param default: 20 | If no "Content-Type" can be guessed, default to `default`. 21 | """ 22 | if filename: 23 | return mimetypes.guess_type(filename)[0] or default 24 | return default 25 | 26 | 27 | def format_header_param(name, value): 28 | """ 29 | Helper function to format and quote a single header parameter. 30 | 31 | Particularly useful for header parameters which might contain 32 | non-ASCII values, like file names. This follows RFC 2231, as 33 | suggested by RFC 2388 Section 4.4. 34 | 35 | :param name: 36 | The name of the parameter, a string expected to be ASCII only. 37 | :param value: 38 | The value of the parameter, provided as a unicode string. 39 | """ 40 | if not any(ch in value for ch in '"\\\r\n'): 41 | result = '%s="%s"' % (name, value) 42 | try: 43 | result.encode('ascii') 44 | except UnicodeEncodeError: 45 | pass 46 | else: 47 | return result 48 | if not six.PY3: # Python 2: 49 | value = value.encode('utf-8') 50 | value = email.utils.encode_rfc2231(value, 'utf-8') 51 | value = '%s*=%s' % (name, value) 52 | return value 53 | 54 | 55 | class RequestField(object): 56 | """ 57 | A data container for request body parameters. 58 | 59 | :param name: 60 | The name of this request field. 61 | :param data: 62 | The data/value body. 63 | :param filename: 64 | An optional filename of the request field. 65 | :param headers: 66 | An optional dict-like object of headers to initially use for the field. 67 | """ 68 | def __init__(self, name, data, filename=None, headers=None): 69 | self._name = name 70 | self._filename = filename 71 | self.data = data 72 | self.headers = {} 73 | if headers: 74 | self.headers = dict(headers) 75 | 76 | @classmethod 77 | def from_tuples(cls, fieldname, value): 78 | """ 79 | A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. 80 | 81 | Supports constructing :class:`~urllib3.fields.RequestField` from parameter 82 | of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) 83 | tuple where the MIME type is optional. For example: :: 84 | 85 | 'foo': 'bar', 86 | 'fakefile': ('foofile.txt', 'contents of foofile'), 87 | 'realfile': ('barfile.txt', open('realfile').read()), 88 | 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 89 | 'nonamefile': 'contents of nonamefile field', 90 | 91 | Field names and filenames must be unicode. 92 | """ 93 | if isinstance(value, tuple): 94 | if len(value) == 3: 95 | filename, data, content_type = value 96 | else: 97 | filename, data = value 98 | content_type = guess_content_type(filename) 99 | else: 100 | filename = None 101 | content_type = None 102 | data = value 103 | 104 | request_param = cls(fieldname, data, filename=filename) 105 | request_param.make_multipart(content_type=content_type) 106 | 107 | return request_param 108 | 109 | def _render_part(self, name, value): 110 | """ 111 | Overridable helper function to format a single header parameter. 112 | 113 | :param name: 114 | The name of the parameter, a string expected to be ASCII only. 115 | :param value: 116 | The value of the parameter, provided as a unicode string. 117 | """ 118 | return format_header_param(name, value) 119 | 120 | def _render_parts(self, header_parts): 121 | """ 122 | Helper function to format and quote a single header. 123 | 124 | Useful for single headers that are composed of multiple items. E.g., 125 | 'Content-Disposition' fields. 126 | 127 | :param header_parts: 128 | A sequence of (k, v) typles or a :class:`dict` of (k, v) to format as 129 | `k1="v1"; k2="v2"; ...`. 130 | """ 131 | parts = [] 132 | iterable = header_parts 133 | if isinstance(header_parts, dict): 134 | iterable = header_parts.items() 135 | 136 | for name, value in iterable: 137 | if value: 138 | parts.append(self._render_part(name, value)) 139 | 140 | return '; '.join(parts) 141 | 142 | def render_headers(self): 143 | """ 144 | Renders the headers for this request field. 145 | """ 146 | lines = [] 147 | 148 | sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location'] 149 | for sort_key in sort_keys: 150 | if self.headers.get(sort_key, False): 151 | lines.append('%s: %s' % (sort_key, self.headers[sort_key])) 152 | 153 | for header_name, header_value in self.headers.items(): 154 | if header_name not in sort_keys: 155 | if header_value: 156 | lines.append('%s: %s' % (header_name, header_value)) 157 | 158 | lines.append('\r\n') 159 | return '\r\n'.join(lines) 160 | 161 | def make_multipart(self, content_disposition=None, content_type=None, content_location=None): 162 | """ 163 | Makes this request field into a multipart request field. 164 | 165 | This method overrides "Content-Disposition", "Content-Type" and 166 | "Content-Location" headers to the request parameter. 167 | 168 | :param content_type: 169 | The 'Content-Type' of the request body. 170 | :param content_location: 171 | The 'Content-Location' of the request body. 172 | 173 | """ 174 | self.headers['Content-Disposition'] = content_disposition or 'form-data' 175 | self.headers['Content-Disposition'] += '; '.join(['', self._render_parts((('name', self._name), ('filename', self._filename)))]) 176 | self.headers['Content-Type'] = content_type 177 | self.headers['Content-Location'] = content_location 178 | -------------------------------------------------------------------------------- /requests/packages/urllib3/fields.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/fields.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/filepost.py: -------------------------------------------------------------------------------- 1 | # urllib3/filepost.py 2 | # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) 3 | # 4 | # This module is part of urllib3 and is released under 5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php 6 | 7 | import codecs 8 | import mimetypes 9 | 10 | from uuid import uuid4 11 | from io import BytesIO 12 | 13 | from .packages import six 14 | from .packages.six import b 15 | from .fields import RequestField 16 | 17 | writer = codecs.lookup('utf-8')[3] 18 | 19 | 20 | def choose_boundary(): 21 | """ 22 | Our embarassingly-simple replacement for mimetools.choose_boundary. 23 | """ 24 | return uuid4().hex 25 | 26 | 27 | def iter_field_objects(fields): 28 | """ 29 | Iterate over fields. 30 | 31 | Supports list of (k, v) tuples and dicts, and lists of 32 | :class:`~urllib3.fields.RequestField`. 33 | 34 | """ 35 | if isinstance(fields, dict): 36 | i = six.iteritems(fields) 37 | else: 38 | i = iter(fields) 39 | 40 | for field in i: 41 | if isinstance(field, RequestField): 42 | yield field 43 | else: 44 | yield RequestField.from_tuples(*field) 45 | 46 | 47 | def iter_fields(fields): 48 | """ 49 | .. deprecated:: 1.6 50 | 51 | Iterate over fields. 52 | 53 | The addition of :class:`~urllib3.fields.RequestField` makes this function 54 | obsolete. Instead, use :func:`iter_field_objects`, which returns 55 | :class:`~urllib3.fields.RequestField` objects. 56 | 57 | Supports list of (k, v) tuples and dicts. 58 | """ 59 | if isinstance(fields, dict): 60 | return ((k, v) for k, v in six.iteritems(fields)) 61 | 62 | return ((k, v) for k, v in fields) 63 | 64 | 65 | def encode_multipart_formdata(fields, boundary=None): 66 | """ 67 | Encode a dictionary of ``fields`` using the multipart/form-data MIME format. 68 | 69 | :param fields: 70 | Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). 71 | 72 | :param boundary: 73 | If not specified, then a random boundary will be generated using 74 | :func:`mimetools.choose_boundary`. 75 | """ 76 | body = BytesIO() 77 | if boundary is None: 78 | boundary = choose_boundary() 79 | 80 | for field in iter_field_objects(fields): 81 | body.write(b('--%s\r\n' % (boundary))) 82 | 83 | writer(body).write(field.render_headers()) 84 | data = field.data 85 | 86 | if isinstance(data, int): 87 | data = str(data) # Backwards compatibility 88 | 89 | if isinstance(data, six.text_type): 90 | writer(body).write(data) 91 | else: 92 | body.write(data) 93 | 94 | body.write(b'\r\n') 95 | 96 | body.write(b('--%s--\r\n' % (boundary))) 97 | 98 | content_type = str('multipart/form-data; boundary=%s' % boundary) 99 | 100 | return body.getvalue(), content_type 101 | -------------------------------------------------------------------------------- /requests/packages/urllib3/filepost.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/filepost.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/packages/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from . import ssl_match_hostname 4 | 5 | -------------------------------------------------------------------------------- /requests/packages/urllib3/packages/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/packages/__init__.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/packages/ordered_dict.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/packages/ordered_dict.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/packages/six.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/packages/six.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/packages/ssl_match_hostname/__init__.py: -------------------------------------------------------------------------------- 1 | try: 2 | # Python 3.2+ 3 | from ssl import CertificateError, match_hostname 4 | except ImportError: 5 | try: 6 | # Backport of the function from a pypi module 7 | from backports.ssl_match_hostname import CertificateError, match_hostname 8 | except ImportError: 9 | # Our vendored copy 10 | from ._implementation import CertificateError, match_hostname 11 | 12 | # Not needed, but documenting what we provide. 13 | __all__ = ('CertificateError', 'match_hostname') 14 | -------------------------------------------------------------------------------- /requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py: -------------------------------------------------------------------------------- 1 | """The match_hostname() function from Python 3.3.3, essential when using SSL.""" 2 | 3 | # Note: This file is under the PSF license as the code comes from the python 4 | # stdlib. http://docs.python.org/3/license.html 5 | 6 | import re 7 | 8 | __version__ = '3.4.0.2' 9 | 10 | class CertificateError(ValueError): 11 | pass 12 | 13 | 14 | def _dnsname_match(dn, hostname, max_wildcards=1): 15 | """Matching according to RFC 6125, section 6.4.3 16 | 17 | http://tools.ietf.org/html/rfc6125#section-6.4.3 18 | """ 19 | pats = [] 20 | if not dn: 21 | return False 22 | 23 | # Ported from python3-syntax: 24 | # leftmost, *remainder = dn.split(r'.') 25 | parts = dn.split(r'.') 26 | leftmost = parts[0] 27 | remainder = parts[1:] 28 | 29 | wildcards = leftmost.count('*') 30 | if wildcards > max_wildcards: 31 | # Issue #17980: avoid denials of service by refusing more 32 | # than one wildcard per fragment. A survey of established 33 | # policy among SSL implementations showed it to be a 34 | # reasonable choice. 35 | raise CertificateError( 36 | "too many wildcards in certificate DNS name: " + repr(dn)) 37 | 38 | # speed up common case w/o wildcards 39 | if not wildcards: 40 | return dn.lower() == hostname.lower() 41 | 42 | # RFC 6125, section 6.4.3, subitem 1. 43 | # The client SHOULD NOT attempt to match a presented identifier in which 44 | # the wildcard character comprises a label other than the left-most label. 45 | if leftmost == '*': 46 | # When '*' is a fragment by itself, it matches a non-empty dotless 47 | # fragment. 48 | pats.append('[^.]+') 49 | elif leftmost.startswith('xn--') or hostname.startswith('xn--'): 50 | # RFC 6125, section 6.4.3, subitem 3. 51 | # The client SHOULD NOT attempt to match a presented identifier 52 | # where the wildcard character is embedded within an A-label or 53 | # U-label of an internationalized domain name. 54 | pats.append(re.escape(leftmost)) 55 | else: 56 | # Otherwise, '*' matches any dotless string, e.g. www* 57 | pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) 58 | 59 | # add the remaining fragments, ignore any wildcards 60 | for frag in remainder: 61 | pats.append(re.escape(frag)) 62 | 63 | pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) 64 | return pat.match(hostname) 65 | 66 | 67 | def match_hostname(cert, hostname): 68 | """Verify that *cert* (in decoded format as returned by 69 | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 70 | rules are followed, but IP addresses are not accepted for *hostname*. 71 | 72 | CertificateError is raised on failure. On success, the function 73 | returns nothing. 74 | """ 75 | if not cert: 76 | raise ValueError("empty or no certificate") 77 | dnsnames = [] 78 | san = cert.get('subjectAltName', ()) 79 | for key, value in san: 80 | if key == 'DNS': 81 | if _dnsname_match(value, hostname): 82 | return 83 | dnsnames.append(value) 84 | if not dnsnames: 85 | # The subject is only checked when there is no dNSName entry 86 | # in subjectAltName 87 | for sub in cert.get('subject', ()): 88 | for key, value in sub: 89 | # XXX according to RFC 2818, the most specific Common Name 90 | # must be used. 91 | if key == 'commonName': 92 | if _dnsname_match(value, hostname): 93 | return 94 | dnsnames.append(value) 95 | if len(dnsnames) > 1: 96 | raise CertificateError("hostname %r " 97 | "doesn't match either of %s" 98 | % (hostname, ', '.join(map(repr, dnsnames)))) 99 | elif len(dnsnames) == 1: 100 | raise CertificateError("hostname %r " 101 | "doesn't match %r" 102 | % (hostname, dnsnames[0])) 103 | else: 104 | raise CertificateError("no appropriate commonName or " 105 | "subjectAltName fields were found") 106 | -------------------------------------------------------------------------------- /requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/poolmanager.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/poolmanager.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/request.py: -------------------------------------------------------------------------------- 1 | # urllib3/request.py 2 | # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) 3 | # 4 | # This module is part of urllib3 and is released under 5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php 6 | 7 | try: 8 | from urllib.parse import urlencode 9 | except ImportError: 10 | from urllib import urlencode 11 | 12 | from .filepost import encode_multipart_formdata 13 | 14 | 15 | __all__ = ['RequestMethods'] 16 | 17 | 18 | class RequestMethods(object): 19 | """ 20 | Convenience mixin for classes who implement a :meth:`urlopen` method, such 21 | as :class:`~urllib3.connectionpool.HTTPConnectionPool` and 22 | :class:`~urllib3.poolmanager.PoolManager`. 23 | 24 | Provides behavior for making common types of HTTP request methods and 25 | decides which type of request field encoding to use. 26 | 27 | Specifically, 28 | 29 | :meth:`.request_encode_url` is for sending requests whose fields are encoded 30 | in the URL (such as GET, HEAD, DELETE). 31 | 32 | :meth:`.request_encode_body` is for sending requests whose fields are 33 | encoded in the *body* of the request using multipart or www-form-urlencoded 34 | (such as for POST, PUT, PATCH). 35 | 36 | :meth:`.request` is for making any kind of request, it will look up the 37 | appropriate encoding format and use one of the above two methods to make 38 | the request. 39 | 40 | Initializer parameters: 41 | 42 | :param headers: 43 | Headers to include with all requests, unless other headers are given 44 | explicitly. 45 | """ 46 | 47 | _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS']) 48 | 49 | def __init__(self, headers=None): 50 | self.headers = headers or {} 51 | 52 | def urlopen(self, method, url, body=None, headers=None, 53 | encode_multipart=True, multipart_boundary=None, 54 | **kw): # Abstract 55 | raise NotImplemented("Classes extending RequestMethods must implement " 56 | "their own ``urlopen`` method.") 57 | 58 | def request(self, method, url, fields=None, headers=None, **urlopen_kw): 59 | """ 60 | Make a request using :meth:`urlopen` with the appropriate encoding of 61 | ``fields`` based on the ``method`` used. 62 | 63 | This is a convenience method that requires the least amount of manual 64 | effort. It can be used in most situations, while still having the option 65 | to drop down to more specific methods when necessary, such as 66 | :meth:`request_encode_url`, :meth:`request_encode_body`, 67 | or even the lowest level :meth:`urlopen`. 68 | """ 69 | method = method.upper() 70 | 71 | if method in self._encode_url_methods: 72 | return self.request_encode_url(method, url, fields=fields, 73 | headers=headers, 74 | **urlopen_kw) 75 | else: 76 | return self.request_encode_body(method, url, fields=fields, 77 | headers=headers, 78 | **urlopen_kw) 79 | 80 | def request_encode_url(self, method, url, fields=None, **urlopen_kw): 81 | """ 82 | Make a request using :meth:`urlopen` with the ``fields`` encoded in 83 | the url. This is useful for request methods like GET, HEAD, DELETE, etc. 84 | """ 85 | if fields: 86 | url += '?' + urlencode(fields) 87 | return self.urlopen(method, url, **urlopen_kw) 88 | 89 | def request_encode_body(self, method, url, fields=None, headers=None, 90 | encode_multipart=True, multipart_boundary=None, 91 | **urlopen_kw): 92 | """ 93 | Make a request using :meth:`urlopen` with the ``fields`` encoded in 94 | the body. This is useful for request methods like POST, PUT, PATCH, etc. 95 | 96 | When ``encode_multipart=True`` (default), then 97 | :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the 98 | payload with the appropriate content type. Otherwise 99 | :meth:`urllib.urlencode` is used with the 100 | 'application/x-www-form-urlencoded' content type. 101 | 102 | Multipart encoding must be used when posting files, and it's reasonably 103 | safe to use it in other times too. However, it may break request signing, 104 | such as with OAuth. 105 | 106 | Supports an optional ``fields`` parameter of key/value strings AND 107 | key/filetuple. A filetuple is a (filename, data, MIME type) tuple where 108 | the MIME type is optional. For example: :: 109 | 110 | fields = { 111 | 'foo': 'bar', 112 | 'fakefile': ('foofile.txt', 'contents of foofile'), 113 | 'realfile': ('barfile.txt', open('realfile').read()), 114 | 'typedfile': ('bazfile.bin', open('bazfile').read(), 115 | 'image/jpeg'), 116 | 'nonamefile': 'contents of nonamefile field', 117 | } 118 | 119 | When uploading a file, providing a filename (the first parameter of the 120 | tuple) is optional but recommended to best mimick behavior of browsers. 121 | 122 | Note that if ``headers`` are supplied, the 'Content-Type' header will be 123 | overwritten because it depends on the dynamic random boundary string 124 | which is used to compose the body of the request. The random boundary 125 | string can be explicitly set with the ``multipart_boundary`` parameter. 126 | """ 127 | if encode_multipart: 128 | body, content_type = encode_multipart_formdata(fields or {}, 129 | boundary=multipart_boundary) 130 | else: 131 | body, content_type = (urlencode(fields or {}), 132 | 'application/x-www-form-urlencoded') 133 | 134 | if headers is None: 135 | headers = self.headers 136 | 137 | headers_ = {'Content-Type': content_type} 138 | headers_.update(headers) 139 | 140 | return self.urlopen(method, url, body=body, headers=headers_, 141 | **urlopen_kw) 142 | -------------------------------------------------------------------------------- /requests/packages/urllib3/request.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/request.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/response.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/response.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/util/__init__.py: -------------------------------------------------------------------------------- 1 | # urllib3/util/__init__.py 2 | # Copyright 2008-2014 Andrey Petrov and contributors (see CONTRIBUTORS.txt) 3 | # 4 | # This module is part of urllib3 and is released under 5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php 6 | 7 | from .connection import is_connection_dropped 8 | from .request import make_headers 9 | from .response import is_fp_closed 10 | from .ssl_ import ( 11 | SSLContext, 12 | HAS_SNI, 13 | assert_fingerprint, 14 | resolve_cert_reqs, 15 | resolve_ssl_version, 16 | ssl_wrap_socket, 17 | ) 18 | from .timeout import ( 19 | current_time, 20 | Timeout, 21 | ) 22 | from .url import ( 23 | get_host, 24 | parse_url, 25 | split_first, 26 | Url, 27 | ) 28 | -------------------------------------------------------------------------------- /requests/packages/urllib3/util/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/util/__init__.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/util/connection.py: -------------------------------------------------------------------------------- 1 | from socket import error as SocketError 2 | try: 3 | from select import poll, POLLIN 4 | except ImportError: # `poll` doesn't exist on OSX and other platforms 5 | poll = False 6 | try: 7 | from select import select 8 | except ImportError: # `select` doesn't exist on AppEngine. 9 | select = False 10 | 11 | def is_connection_dropped(conn): # Platform-specific 12 | """ 13 | Returns True if the connection is dropped and should be closed. 14 | 15 | :param conn: 16 | :class:`httplib.HTTPConnection` object. 17 | 18 | Note: For platforms like AppEngine, this will always return ``False`` to 19 | let the platform handle connection recycling transparently for us. 20 | """ 21 | sock = getattr(conn, 'sock', False) 22 | if sock is False: # Platform-specific: AppEngine 23 | return False 24 | if sock is None: # Connection already closed (such as by httplib). 25 | return False 26 | 27 | if not poll: 28 | if not select: # Platform-specific: AppEngine 29 | return False 30 | 31 | try: 32 | return select([sock], [], [], 0.0)[0] 33 | except SocketError: 34 | return True 35 | 36 | # This version is better on platforms that support it. 37 | p = poll() 38 | p.register(sock, POLLIN) 39 | for (fno, ev) in p.poll(0.0): 40 | if fno == sock.fileno(): 41 | # Either data is buffered (bad), or the connection is dropped. 42 | return True 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /requests/packages/urllib3/util/connection.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/util/connection.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/util/request.py: -------------------------------------------------------------------------------- 1 | from base64 import b64encode 2 | 3 | from ..packages import six 4 | 5 | 6 | ACCEPT_ENCODING = 'gzip,deflate' 7 | 8 | 9 | def make_headers(keep_alive=None, accept_encoding=None, user_agent=None, 10 | basic_auth=None, proxy_basic_auth=None): 11 | """ 12 | Shortcuts for generating request headers. 13 | 14 | :param keep_alive: 15 | If ``True``, adds 'connection: keep-alive' header. 16 | 17 | :param accept_encoding: 18 | Can be a boolean, list, or string. 19 | ``True`` translates to 'gzip,deflate'. 20 | List will get joined by comma. 21 | String will be used as provided. 22 | 23 | :param user_agent: 24 | String representing the user-agent you want, such as 25 | "python-urllib3/0.6" 26 | 27 | :param basic_auth: 28 | Colon-separated username:password string for 'authorization: basic ...' 29 | auth header. 30 | 31 | :param proxy_basic_auth: 32 | Colon-separated username:password string for 'proxy-authorization: basic ...' 33 | auth header. 34 | 35 | Example: :: 36 | 37 | >>> make_headers(keep_alive=True, user_agent="Batman/1.0") 38 | {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} 39 | >>> make_headers(accept_encoding=True) 40 | {'accept-encoding': 'gzip,deflate'} 41 | """ 42 | headers = {} 43 | if accept_encoding: 44 | if isinstance(accept_encoding, str): 45 | pass 46 | elif isinstance(accept_encoding, list): 47 | accept_encoding = ','.join(accept_encoding) 48 | else: 49 | accept_encoding = ACCEPT_ENCODING 50 | headers['accept-encoding'] = accept_encoding 51 | 52 | if user_agent: 53 | headers['user-agent'] = user_agent 54 | 55 | if keep_alive: 56 | headers['connection'] = 'keep-alive' 57 | 58 | if basic_auth: 59 | headers['authorization'] = 'Basic ' + \ 60 | b64encode(six.b(basic_auth)).decode('utf-8') 61 | 62 | if proxy_basic_auth: 63 | headers['proxy-authorization'] = 'Basic ' + \ 64 | b64encode(six.b(proxy_basic_auth)).decode('utf-8') 65 | 66 | return headers 67 | 68 | 69 | -------------------------------------------------------------------------------- /requests/packages/urllib3/util/request.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/util/request.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/util/response.py: -------------------------------------------------------------------------------- 1 | def is_fp_closed(obj): 2 | """ 3 | Checks whether a given file-like object is closed. 4 | 5 | :param obj: 6 | The file-like object to check. 7 | """ 8 | if hasattr(obj, 'fp'): 9 | # Object is a container for another file-like object that gets released 10 | # on exhaustion (e.g. HTTPResponse) 11 | return obj.fp is None 12 | 13 | return obj.closed 14 | -------------------------------------------------------------------------------- /requests/packages/urllib3/util/response.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/util/response.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/util/ssl_.py: -------------------------------------------------------------------------------- 1 | from binascii import hexlify, unhexlify 2 | from hashlib import md5, sha1 3 | 4 | from ..exceptions import SSLError 5 | 6 | 7 | try: # Test for SSL features 8 | SSLContext = None 9 | HAS_SNI = False 10 | 11 | import ssl 12 | from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23 13 | from ssl import SSLContext # Modern SSL? 14 | from ssl import HAS_SNI # Has SNI? 15 | except ImportError: 16 | pass 17 | 18 | 19 | def assert_fingerprint(cert, fingerprint): 20 | """ 21 | Checks if given fingerprint matches the supplied certificate. 22 | 23 | :param cert: 24 | Certificate as bytes object. 25 | :param fingerprint: 26 | Fingerprint as string of hexdigits, can be interspersed by colons. 27 | """ 28 | 29 | # Maps the length of a digest to a possible hash function producing 30 | # this digest. 31 | hashfunc_map = { 32 | 16: md5, 33 | 20: sha1 34 | } 35 | 36 | fingerprint = fingerprint.replace(':', '').lower() 37 | 38 | digest_length, rest = divmod(len(fingerprint), 2) 39 | 40 | if rest or digest_length not in hashfunc_map: 41 | raise SSLError('Fingerprint is of invalid length.') 42 | 43 | # We need encode() here for py32; works on py2 and p33. 44 | fingerprint_bytes = unhexlify(fingerprint.encode()) 45 | 46 | hashfunc = hashfunc_map[digest_length] 47 | 48 | cert_digest = hashfunc(cert).digest() 49 | 50 | if not cert_digest == fingerprint_bytes: 51 | raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' 52 | .format(hexlify(fingerprint_bytes), 53 | hexlify(cert_digest))) 54 | 55 | 56 | def resolve_cert_reqs(candidate): 57 | """ 58 | Resolves the argument to a numeric constant, which can be passed to 59 | the wrap_socket function/method from the ssl module. 60 | Defaults to :data:`ssl.CERT_NONE`. 61 | If given a string it is assumed to be the name of the constant in the 62 | :mod:`ssl` module or its abbrevation. 63 | (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. 64 | If it's neither `None` nor a string we assume it is already the numeric 65 | constant which can directly be passed to wrap_socket. 66 | """ 67 | if candidate is None: 68 | return CERT_NONE 69 | 70 | if isinstance(candidate, str): 71 | res = getattr(ssl, candidate, None) 72 | if res is None: 73 | res = getattr(ssl, 'CERT_' + candidate) 74 | return res 75 | 76 | return candidate 77 | 78 | 79 | def resolve_ssl_version(candidate): 80 | """ 81 | like resolve_cert_reqs 82 | """ 83 | if candidate is None: 84 | return PROTOCOL_SSLv23 85 | 86 | if isinstance(candidate, str): 87 | res = getattr(ssl, candidate, None) 88 | if res is None: 89 | res = getattr(ssl, 'PROTOCOL_' + candidate) 90 | return res 91 | 92 | return candidate 93 | 94 | 95 | if SSLContext is not None: # Python 3.2+ 96 | def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, 97 | ca_certs=None, server_hostname=None, 98 | ssl_version=None): 99 | """ 100 | All arguments except `server_hostname` have the same meaning as for 101 | :func:`ssl.wrap_socket` 102 | 103 | :param server_hostname: 104 | Hostname of the expected certificate 105 | """ 106 | context = SSLContext(ssl_version) 107 | context.verify_mode = cert_reqs 108 | 109 | # Disable TLS compression to migitate CRIME attack (issue #309) 110 | OP_NO_COMPRESSION = 0x20000 111 | context.options |= OP_NO_COMPRESSION 112 | 113 | if ca_certs: 114 | try: 115 | context.load_verify_locations(ca_certs) 116 | # Py32 raises IOError 117 | # Py33 raises FileNotFoundError 118 | except Exception as e: # Reraise as SSLError 119 | raise SSLError(e) 120 | if certfile: 121 | # FIXME: This block needs a test. 122 | context.load_cert_chain(certfile, keyfile) 123 | if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI 124 | return context.wrap_socket(sock, server_hostname=server_hostname) 125 | return context.wrap_socket(sock) 126 | 127 | else: # Python 3.1 and earlier 128 | def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, 129 | ca_certs=None, server_hostname=None, 130 | ssl_version=None): 131 | return wrap_socket(sock, keyfile=keyfile, certfile=certfile, 132 | ca_certs=ca_certs, cert_reqs=cert_reqs, 133 | ssl_version=ssl_version) 134 | -------------------------------------------------------------------------------- /requests/packages/urllib3/util/ssl_.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/util/ssl_.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/util/timeout.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/util/timeout.pyc -------------------------------------------------------------------------------- /requests/packages/urllib3/util/url.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | 3 | from ..exceptions import LocationParseError 4 | 5 | 6 | class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])): 7 | """ 8 | Datastructure for representing an HTTP URL. Used as a return value for 9 | :func:`parse_url`. 10 | """ 11 | slots = () 12 | 13 | def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None): 14 | return super(Url, cls).__new__(cls, scheme, auth, host, port, path, query, fragment) 15 | 16 | @property 17 | def hostname(self): 18 | """For backwards-compatibility with urlparse. We're nice like that.""" 19 | return self.host 20 | 21 | @property 22 | def request_uri(self): 23 | """Absolute path including the query string.""" 24 | uri = self.path or '/' 25 | 26 | if self.query is not None: 27 | uri += '?' + self.query 28 | 29 | return uri 30 | 31 | @property 32 | def netloc(self): 33 | """Network location including host and port""" 34 | if self.port: 35 | return '%s:%d' % (self.host, self.port) 36 | return self.host 37 | 38 | 39 | def split_first(s, delims): 40 | """ 41 | Given a string and an iterable of delimiters, split on the first found 42 | delimiter. Return two split parts and the matched delimiter. 43 | 44 | If not found, then the first part is the full input string. 45 | 46 | Example: :: 47 | 48 | >>> split_first('foo/bar?baz', '?/=') 49 | ('foo', 'bar?baz', '/') 50 | >>> split_first('foo/bar?baz', '123') 51 | ('foo/bar?baz', '', None) 52 | 53 | Scales linearly with number of delims. Not ideal for large number of delims. 54 | """ 55 | min_idx = None 56 | min_delim = None 57 | for d in delims: 58 | idx = s.find(d) 59 | if idx < 0: 60 | continue 61 | 62 | if min_idx is None or idx < min_idx: 63 | min_idx = idx 64 | min_delim = d 65 | 66 | if min_idx is None or min_idx < 0: 67 | return s, '', None 68 | 69 | return s[:min_idx], s[min_idx+1:], min_delim 70 | 71 | 72 | def parse_url(url): 73 | """ 74 | Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is 75 | performed to parse incomplete urls. Fields not provided will be None. 76 | 77 | Partly backwards-compatible with :mod:`urlparse`. 78 | 79 | Example: :: 80 | 81 | >>> parse_url('http://google.com/mail/') 82 | Url(scheme='http', host='google.com', port=None, path='/', ...) 83 | >>> parse_url('google.com:80') 84 | Url(scheme=None, host='google.com', port=80, path=None, ...) 85 | >>> parse_url('/foo?bar') 86 | Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) 87 | """ 88 | 89 | # While this code has overlap with stdlib's urlparse, it is much 90 | # simplified for our needs and less annoying. 91 | # Additionally, this implementations does silly things to be optimal 92 | # on CPython. 93 | 94 | scheme = None 95 | auth = None 96 | host = None 97 | port = None 98 | path = None 99 | fragment = None 100 | query = None 101 | 102 | # Scheme 103 | if '://' in url: 104 | scheme, url = url.split('://', 1) 105 | 106 | # Find the earliest Authority Terminator 107 | # (http://tools.ietf.org/html/rfc3986#section-3.2) 108 | url, path_, delim = split_first(url, ['/', '?', '#']) 109 | 110 | if delim: 111 | # Reassemble the path 112 | path = delim + path_ 113 | 114 | # Auth 115 | if '@' in url: 116 | # Last '@' denotes end of auth part 117 | auth, url = url.rsplit('@', 1) 118 | 119 | # IPv6 120 | if url and url[0] == '[': 121 | host, url = url.split(']', 1) 122 | host += ']' 123 | 124 | # Port 125 | if ':' in url: 126 | _host, port = url.split(':', 1) 127 | 128 | if not host: 129 | host = _host 130 | 131 | if port: 132 | # If given, ports must be integers. 133 | if not port.isdigit(): 134 | raise LocationParseError(url) 135 | port = int(port) 136 | else: 137 | # Blank ports are cool, too. (rfc3986#section-3.2.3) 138 | port = None 139 | 140 | elif not host and url: 141 | host = url 142 | 143 | if not path: 144 | return Url(scheme, auth, host, port, path, query, fragment) 145 | 146 | # Fragment 147 | if '#' in path: 148 | path, fragment = path.split('#', 1) 149 | 150 | # Query 151 | if '?' in path: 152 | path, query = path.split('?', 1) 153 | 154 | return Url(scheme, auth, host, port, path, query, fragment) 155 | 156 | 157 | def get_host(url): 158 | """ 159 | Deprecated. Use :func:`.parse_url` instead. 160 | """ 161 | p = parse_url(url) 162 | return p.scheme or 'http', p.hostname, p.port 163 | -------------------------------------------------------------------------------- /requests/packages/urllib3/util/url.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/packages/urllib3/util/url.pyc -------------------------------------------------------------------------------- /requests/sessions.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/sessions.pyc -------------------------------------------------------------------------------- /requests/status_codes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .structures import LookupDict 4 | 5 | _codes = { 6 | 7 | # Informational. 8 | 100: ('continue',), 9 | 101: ('switching_protocols',), 10 | 102: ('processing',), 11 | 103: ('checkpoint',), 12 | 122: ('uri_too_long', 'request_uri_too_long'), 13 | 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'), 14 | 201: ('created',), 15 | 202: ('accepted',), 16 | 203: ('non_authoritative_info', 'non_authoritative_information'), 17 | 204: ('no_content',), 18 | 205: ('reset_content', 'reset'), 19 | 206: ('partial_content', 'partial'), 20 | 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'), 21 | 208: ('already_reported',), 22 | 226: ('im_used',), 23 | 24 | # Redirection. 25 | 300: ('multiple_choices',), 26 | 301: ('moved_permanently', 'moved', '\\o-'), 27 | 302: ('found',), 28 | 303: ('see_other', 'other'), 29 | 304: ('not_modified',), 30 | 305: ('use_proxy',), 31 | 306: ('switch_proxy',), 32 | 307: ('temporary_redirect', 'temporary_moved', 'temporary'), 33 | 308: ('resume_incomplete', 'resume'), 34 | 35 | # Client Error. 36 | 400: ('bad_request', 'bad'), 37 | 401: ('unauthorized',), 38 | 402: ('payment_required', 'payment'), 39 | 403: ('forbidden',), 40 | 404: ('not_found', '-o-'), 41 | 405: ('method_not_allowed', 'not_allowed'), 42 | 406: ('not_acceptable',), 43 | 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'), 44 | 408: ('request_timeout', 'timeout'), 45 | 409: ('conflict',), 46 | 410: ('gone',), 47 | 411: ('length_required',), 48 | 412: ('precondition_failed', 'precondition'), 49 | 413: ('request_entity_too_large',), 50 | 414: ('request_uri_too_large',), 51 | 415: ('unsupported_media_type', 'unsupported_media', 'media_type'), 52 | 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'), 53 | 417: ('expectation_failed',), 54 | 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'), 55 | 422: ('unprocessable_entity', 'unprocessable'), 56 | 423: ('locked',), 57 | 424: ('failed_dependency', 'dependency'), 58 | 425: ('unordered_collection', 'unordered'), 59 | 426: ('upgrade_required', 'upgrade'), 60 | 428: ('precondition_required', 'precondition'), 61 | 429: ('too_many_requests', 'too_many'), 62 | 431: ('header_fields_too_large', 'fields_too_large'), 63 | 444: ('no_response', 'none'), 64 | 449: ('retry_with', 'retry'), 65 | 450: ('blocked_by_windows_parental_controls', 'parental_controls'), 66 | 451: ('unavailable_for_legal_reasons', 'legal_reasons'), 67 | 499: ('client_closed_request',), 68 | 69 | # Server Error. 70 | 500: ('internal_server_error', 'server_error', '/o\\', '✗'), 71 | 501: ('not_implemented',), 72 | 502: ('bad_gateway',), 73 | 503: ('service_unavailable', 'unavailable'), 74 | 504: ('gateway_timeout',), 75 | 505: ('http_version_not_supported', 'http_version'), 76 | 506: ('variant_also_negotiates',), 77 | 507: ('insufficient_storage',), 78 | 509: ('bandwidth_limit_exceeded', 'bandwidth'), 79 | 510: ('not_extended',), 80 | } 81 | 82 | codes = LookupDict(name='status_codes') 83 | 84 | for (code, titles) in list(_codes.items()): 85 | for title in titles: 86 | setattr(codes, title, code) 87 | if not title.startswith('\\'): 88 | setattr(codes, title.upper(), code) 89 | -------------------------------------------------------------------------------- /requests/status_codes.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/status_codes.pyc -------------------------------------------------------------------------------- /requests/structures.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.structures 5 | ~~~~~~~~~~~~~~~~~~~ 6 | 7 | Data structures that power Requests. 8 | 9 | """ 10 | 11 | import os 12 | import collections 13 | from itertools import islice 14 | 15 | 16 | class IteratorProxy(object): 17 | """docstring for IteratorProxy""" 18 | def __init__(self, i): 19 | self.i = i 20 | # self.i = chain.from_iterable(i) 21 | 22 | def __iter__(self): 23 | return self.i 24 | 25 | def __len__(self): 26 | if hasattr(self.i, '__len__'): 27 | return len(self.i) 28 | if hasattr(self.i, 'len'): 29 | return self.i.len 30 | if hasattr(self.i, 'fileno'): 31 | return os.fstat(self.i.fileno()).st_size 32 | 33 | def read(self, n): 34 | return "".join(islice(self.i, None, n)) 35 | 36 | 37 | class CaseInsensitiveDict(collections.MutableMapping): 38 | """ 39 | A case-insensitive ``dict``-like object. 40 | 41 | Implements all methods and operations of 42 | ``collections.MutableMapping`` as well as dict's ``copy``. Also 43 | provides ``lower_items``. 44 | 45 | All keys are expected to be strings. The structure remembers the 46 | case of the last key to be set, and ``iter(instance)``, 47 | ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` 48 | will contain case-sensitive keys. However, querying and contains 49 | testing is case insensitive: 50 | 51 | cid = CaseInsensitiveDict() 52 | cid['Accept'] = 'application/json' 53 | cid['aCCEPT'] == 'application/json' # True 54 | list(cid) == ['Accept'] # True 55 | 56 | For example, ``headers['content-encoding']`` will return the 57 | value of a ``'Content-Encoding'`` response header, regardless 58 | of how the header name was originally stored. 59 | 60 | If the constructor, ``.update``, or equality comparison 61 | operations are given keys that have equal ``.lower()``s, the 62 | behavior is undefined. 63 | 64 | """ 65 | def __init__(self, data=None, **kwargs): 66 | self._store = dict() 67 | if data is None: 68 | data = {} 69 | self.update(data, **kwargs) 70 | 71 | def __setitem__(self, key, value): 72 | # Use the lowercased key for lookups, but store the actual 73 | # key alongside the value. 74 | self._store[key.lower()] = (key, value) 75 | 76 | def __getitem__(self, key): 77 | return self._store[key.lower()][1] 78 | 79 | def __delitem__(self, key): 80 | del self._store[key.lower()] 81 | 82 | def __iter__(self): 83 | return (casedkey for casedkey, mappedvalue in self._store.values()) 84 | 85 | def __len__(self): 86 | return len(self._store) 87 | 88 | def lower_items(self): 89 | """Like iteritems(), but with all lowercase keys.""" 90 | return ( 91 | (lowerkey, keyval[1]) 92 | for (lowerkey, keyval) 93 | in self._store.items() 94 | ) 95 | 96 | def __eq__(self, other): 97 | if isinstance(other, collections.Mapping): 98 | other = CaseInsensitiveDict(other) 99 | else: 100 | return NotImplemented 101 | # Compare insensitively 102 | return dict(self.lower_items()) == dict(other.lower_items()) 103 | 104 | # Copy is required 105 | def copy(self): 106 | return CaseInsensitiveDict(self._store.values()) 107 | 108 | def __repr__(self): 109 | return str(dict(self.items())) 110 | 111 | class LookupDict(dict): 112 | """Dictionary lookup object.""" 113 | 114 | def __init__(self, name=None): 115 | self.name = name 116 | super(LookupDict, self).__init__() 117 | 118 | def __repr__(self): 119 | return '' % (self.name) 120 | 121 | def __getitem__(self, key): 122 | # We allow fall-through here, so values default to None 123 | 124 | return self.__dict__.get(key, None) 125 | 126 | def get(self, key, default=None): 127 | return self.__dict__.get(key, default) 128 | -------------------------------------------------------------------------------- /requests/structures.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/structures.pyc -------------------------------------------------------------------------------- /requests/utils.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/requests/utils.pyc -------------------------------------------------------------------------------- /routes.py: -------------------------------------------------------------------------------- 1 | from imports import * 2 | from handlers import * 3 | 4 | routes = [ 5 | (r'/',MainHandler), 6 | (r'/profile/.*',ProfileHandler), 7 | (r'/promote/.*',PromoteHandler), 8 | (r'/link/.*',RepoHandler), 9 | (r'/mypromotedrepos',MyPromotedRepos), 10 | (r'/redirecting/.*',GitHubView), 11 | (r'/edit/.*',RepoEditHandler), 12 | (r'/logout',LogoutHandler), 13 | (r'/auth_redirect',AuthRedirect), 14 | (r'/promote_verify',PromoteVerify), 15 | (r'/authorization',Authorization), 16 | (r'/halloffame',HallOfFame) 17 | ] 18 | -------------------------------------------------------------------------------- /static/css/reset.css: -------------------------------------------------------------------------------- 1 | /* http://meyerweb.com/eric/tools/css/reset/ 2 | v2.0 | 20110126 3 | License: none (public domain) 4 | */ 5 | 6 | html, body, div, span, applet, object, iframe, 7 | h1, h2, h3, h4, h5, h6, p, blockquote, pre, 8 | a, abbr, acronym, address, big, cite, code, 9 | del, dfn, em, img, ins, kbd, q, s, samp, 10 | small, strike, strong, sub, sup, tt, var, 11 | b, u, i, center, 12 | dl, dt, dd, ol, ul, li, 13 | fieldset, form, label, legend, 14 | table, caption, tbody, tfoot, thead, tr, th, td, 15 | article, aside, canvas, details, embed, 16 | figure, figcaption, footer, header, hgroup, 17 | menu, nav, output, ruby, section, summary, 18 | time, mark, audio, video { 19 | margin: 0; 20 | padding: 0; 21 | border: 0; 22 | font-size: 100%; 23 | font: inherit; 24 | vertical-align: baseline; 25 | } 26 | /* HTML5 display-role reset for older browsers */ 27 | article, aside, details, figcaption, figure, 28 | footer, header, hgroup, menu, nav, section, main { 29 | display: block; 30 | } 31 | body { 32 | line-height: 1; 33 | } 34 | ol, ul { 35 | list-style: none; 36 | } 37 | blockquote, q { 38 | quotes: none; 39 | } 40 | blockquote:before, blockquote:after, 41 | q:before, q:after { 42 | content: ''; 43 | content: none; 44 | } 45 | table { 46 | border-collapse: collapse; 47 | border-spacing: 0; 48 | } -------------------------------------------------------------------------------- /static/css/style.css: -------------------------------------------------------------------------------- 1 | /* ============================================================================= 2 | HTML5 CSS Reset Minified - Eric Meyer 3 | ========================================================================== */ 4 | 5 | 6 | 7 | 8 | /* ============================================================================= 9 | My CSS 10 | ========================================================================== */ 11 | 12 | /* ---- base ---- */ 13 | 14 | html,body{ 15 | width:100%; 16 | height:100%; 17 | } 18 | 19 | 20 | canvas{ 21 | display:block; 22 | vertical-align:bottom; 23 | } 24 | 25 | 26 | 27 | 28 | 29 | /* ---- particles.js container ---- */ 30 | 31 | #particles-js{ 32 | width: 100%; 33 | height: 100%; 34 | background-image: url('pattern.png'); 35 | background-size: cover; 36 | background-position: 50% 50%; 37 | background-repeat: no-repeat; 38 | } 39 | -------------------------------------------------------------------------------- /static/dist/README.md: -------------------------------------------------------------------------------- 1 | Place the extracted content from Semantic-UI here in this folder. 2 | -------------------------------------------------------------------------------- /static/images/Open-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/static/images/Open-logo.png -------------------------------------------------------------------------------- /static/images/cd-arrow.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /static/images/cd-nav-icons.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | 6 | 8 | 9 | 11 | 12 | 14 | 15 | 16 | 18 | -------------------------------------------------------------------------------- /static/images/cd-search.svg: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 9 | -------------------------------------------------------------------------------- /static/images/dpp.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/static/images/dpp.PNG -------------------------------------------------------------------------------- /static/images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/static/images/logo.png -------------------------------------------------------------------------------- /static/images/of.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/static/images/of.png -------------------------------------------------------------------------------- /static/images/oie_png.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/static/images/oie_png.png -------------------------------------------------------------------------------- /static/images/openflock-ss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/static/images/openflock-ss.png -------------------------------------------------------------------------------- /static/images/pattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/static/images/pattern.png -------------------------------------------------------------------------------- /static/images/safari.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waseem18/Openflock/68ebfb1010ef1853d7028647bb062c683efaaf60/static/images/safari.png -------------------------------------------------------------------------------- /static/js/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "particles.js", 3 | "main": "particles.js", 4 | "homepage": "https://github.com/VincentGarreau/particles.js", 5 | "authors": [ 6 | "Vincent Garreau " 7 | ], 8 | "description": "A lightweight JavaScript library for creating particles.", 9 | "keywords": [ 10 | "particle", 11 | "particles" 12 | ], 13 | "license": "MIT", 14 | "ignore": [ 15 | "**/.*", 16 | "node_modules", 17 | "bower_components", 18 | "test", 19 | "tests" 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /static/js/homepage.js: -------------------------------------------------------------------------------- 1 | $(document) 2 | .ready(function() { 3 | 4 | var 5 | changeSides = function() { 6 | $('.ui.shape') 7 | .eq(0) 8 | .shape('flip over') 9 | .end() 10 | .eq(1) 11 | .shape('flip over') 12 | .end() 13 | .eq(2) 14 | .shape('flip back') 15 | .end() 16 | .eq(3) 17 | .shape('flip back') 18 | .end() 19 | ; 20 | }, 21 | validationRules = { 22 | firstName: { 23 | identifier : 'email', 24 | rules: [ 25 | { 26 | type : 'empty', 27 | prompt : 'Please enter an e-mail' 28 | }, 29 | { 30 | type : 'email', 31 | prompt : 'Please enter a valid e-mail' 32 | } 33 | ] 34 | } 35 | } 36 | ; 37 | 38 | $('.ui.dropdown') 39 | .dropdown({ 40 | on: 'hover' 41 | }) 42 | ; 43 | 44 | $('.ui.form') 45 | .form(validationRules, { 46 | on: 'blur' 47 | }) 48 | ; 49 | 50 | $('.masthead .information') 51 | .transition('scale in', 1000) 52 | ; 53 | 54 | setInterval(changeSides, 3000); 55 | 56 | }) 57 | ; -------------------------------------------------------------------------------- /static/js/main.js: -------------------------------------------------------------------------------- 1 | jQuery(document).ready(function(){ 2 | //cache DOM elements 3 | var mainContent = $('.cd-main-content'), 4 | header = $('.cd-main-header'), 5 | sidebar = $('.cd-side-nav'), 6 | sidebarTrigger = $('.cd-nav-trigger'), 7 | topNavigation = $('.cd-top-nav'), 8 | searchForm = $('.cd-search'), 9 | accountInfo = $('.account'); 10 | 11 | //on resize, move search and top nav position according to window width 12 | var resizing = false; 13 | moveNavigation(); 14 | $(window).on('resize', function(){ 15 | if( !resizing ) { 16 | (!window.requestAnimationFrame) ? setTimeout(moveNavigation, 300) : window.requestAnimationFrame(moveNavigation); 17 | resizing = true; 18 | } 19 | }); 20 | 21 | //on window scrolling - fix sidebar nav 22 | var scrolling = false; 23 | checkScrollbarPosition(); 24 | $(window).on('scroll', function(){ 25 | if( !scrolling ) { 26 | (!window.requestAnimationFrame) ? setTimeout(checkScrollbarPosition, 300) : window.requestAnimationFrame(checkScrollbarPosition); 27 | scrolling = true; 28 | } 29 | }); 30 | 31 | //mobile only - open sidebar when user clicks the hamburger menu 32 | sidebarTrigger.on('click', function(event){ 33 | event.preventDefault(); 34 | $([sidebar, sidebarTrigger]).toggleClass('nav-is-visible'); 35 | }); 36 | 37 | //click on item and show submenu 38 | $('.has-children > a').on('click', function(event){ 39 | var mq = checkMQ(), 40 | selectedItem = $(this); 41 | if( mq == 'mobile' || mq == 'tablet' ) { 42 | event.preventDefault(); 43 | if( selectedItem.parent('li').hasClass('selected')) { 44 | selectedItem.parent('li').removeClass('selected'); 45 | } else { 46 | sidebar.find('.has-children.selected').removeClass('selected'); 47 | accountInfo.removeClass('selected'); 48 | selectedItem.parent('li').addClass('selected'); 49 | } 50 | } 51 | }); 52 | 53 | //click on account and show submenu - desktop version only 54 | accountInfo.children('a').on('click', function(event){ 55 | var mq = checkMQ(), 56 | selectedItem = $(this); 57 | if( mq == 'desktop') { 58 | event.preventDefault(); 59 | accountInfo.toggleClass('selected'); 60 | sidebar.find('.has-children.selected').removeClass('selected'); 61 | } 62 | }); 63 | 64 | $(document).on('click', function(event){ 65 | if( !$(event.target).is('.has-children a') ) { 66 | sidebar.find('.has-children.selected').removeClass('selected'); 67 | accountInfo.removeClass('selected'); 68 | } 69 | }); 70 | 71 | //on desktop - differentiate between a user trying to hover over a dropdown item vs trying to navigate into a submenu's contents 72 | sidebar.children('ul').menuAim({ 73 | activate: function(row) { 74 | $(row).addClass('hover'); 75 | }, 76 | deactivate: function(row) { 77 | $(row).removeClass('hover'); 78 | }, 79 | exitMenu: function() { 80 | sidebar.find('.hover').removeClass('hover'); 81 | return true; 82 | }, 83 | submenuSelector: ".has-children", 84 | }); 85 | 86 | function checkMQ() { 87 | //check if mobile or desktop device 88 | return window.getComputedStyle(document.querySelector('.cd-main-content'), '::before').getPropertyValue('content').replace(/'/g, "").replace(/"/g, ""); 89 | } 90 | 91 | function moveNavigation(){ 92 | var mq = checkMQ(); 93 | 94 | if ( mq == 'mobile' && topNavigation.parents('.cd-side-nav').length == 0 ) { 95 | detachElements(); 96 | topNavigation.appendTo(sidebar); 97 | searchForm.removeClass('is-hidden').prependTo(sidebar); 98 | } else if ( ( mq == 'tablet' || mq == 'desktop') && topNavigation.parents('.cd-side-nav').length > 0 ) { 99 | detachElements(); 100 | searchForm.insertAfter(header.find('.cd-logo')); 101 | topNavigation.appendTo(header.find('.cd-nav')); 102 | } 103 | checkSelected(mq); 104 | resizing = false; 105 | } 106 | 107 | function detachElements() { 108 | topNavigation.detach(); 109 | searchForm.detach(); 110 | } 111 | 112 | function checkSelected(mq) { 113 | //on desktop, remove selected class from items selected on mobile/tablet version 114 | if( mq == 'desktop' ) $('.has-children.selected').removeClass('selected'); 115 | } 116 | 117 | function checkScrollbarPosition() { 118 | var mq = checkMQ(); 119 | 120 | if( mq != 'mobile' ) { 121 | var sidebarHeight = sidebar.outerHeight(), 122 | windowHeight = $(window).height(), 123 | mainContentHeight = mainContent.outerHeight(), 124 | scrollTop = $(window).scrollTop(); 125 | 126 | ( ( scrollTop + windowHeight > sidebarHeight ) && ( mainContentHeight - sidebarHeight != 0 ) ) ? sidebar.addClass('is-fixed').css('bottom', 0) : sidebar.removeClass('is-fixed').attr('style', ''); 127 | } 128 | scrolling = false; 129 | } 130 | }); -------------------------------------------------------------------------------- /templates/HallOfFame.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | Hall Of Fame - Openflock 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | {% for ud in userdata %} 29 | Menu 30 | 31 | 52 | {% endfor %} 53 |
54 | 55 |
56 | 57 |
58 | 59 | 60 |
61 |
62 | 63 | 64 | 65 | 66 | 67 |
68 | 100 |
101 | 102 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /templates/promoted_repos.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | {% for ud in userdata %} 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | {{ud.fullname}} - Promoted repos - Openflock 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | Menu 26 | 27 | 47 |
48 | 49 |
50 | 51 | 52 |
53 | 54 | 55 |
56 |
57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 |
73 |
74 |
{{ud.fullname}}
75 | @{{ud.username}} 76 | 77 | 78 | {% if len_lang_list == 0 %} 79 |

{{ud.fullname}} is an Opensource newbie.

80 | {% else %} 81 |

{{ud.fullname}} is an Opensource enthusiast who likes to code in {% for i in lang_list %} {{i}} {% endfor %} 82 |

83 | {% endif %} 84 | 85 |
86 | 87 | Follow @{{ud.username}} 88 | Share 89 |
90 | 91 | {% for rd in repodata %} 92 |

{{rd.reponame}}

93 |

Edit

94 |
95 | 96 | 97 |

98 | {% if language %} 99 | {{rd.language}} | 100 | {% endif %} 101 | 102 | {% if rd.genre %} 103 | {{rd.genre}} 104 | | 105 | {% endif %} 106 | {{rd.simple_reason}} 107 |

108 | 109 | 110 |

{{rd.detailed_reason}}

111 |

{{rd.promoted_time.strftime('%b %d, %y')}} | Views: {{rd.views_of}}

112 | 113 |
114 | {% endfor %} 115 |
116 | {% if notpromoted %} 117 |

You haven't yet promoted any repositories!

118 |
119 |
120 |
121 | {% endif %} 122 |

Trying to promote a repository from an Organization?

123 |

Enter the URL of the repo here

124 |
125 |
126 | 127 | 128 |
129 |
130 | 131 | 132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 | 151 |
152 | 153 | 154 | 155 | 156 | 157 | {% endfor %} 158 | 159 | 160 | -------------------------------------------------------------------------------- /templates/repo_info.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | {% for rd in repodata %} 14 | {{rd.reponame}}| Openflock 15 | {% endfor %} 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | {% if username %} 27 | 28 | Menu 29 | 30 | 49 | {% endif %} 50 |
51 | 52 |
53 | 54 |
55 | 56 | 57 |
58 |
59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | {% for rd in repodata %} 73 |
74 |
75 | 76 |
{{rd.reponame}}
77 | 78 |

{{rd.description}}

79 |

{{rd.repo_html_url}}

80 | 81 | {% if rd.language %} 82 |

Language : {{rd.language}}

83 | {% endif %} 84 | 85 | Star 86 |    87 | 88 | Fork 89 |    90 | 91 | Watch 92 | {% if username == rd.promoting_user %} 93 |

Edit details

94 |
95 | 96 | {% endif %} 97 |

Views: {{rd.views_of}}

98 |
99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | {% if genre %} 121 | 122 | 123 | 124 | 125 | {% endif %} 126 | 127 | 128 | 129 | 130 | {% if difficulty %} 131 | 132 | 133 | 134 | 135 | {% endif %} 136 | 137 | 138 | 139 | 140 | 141 |
111 | Details 112 |
Reason to promote{{rd.simple_reason}}
Genre{{rd.genre}}
Detailed Reason{{rd.detailed_reason}}
Difficulty{{rd.is_beginner}}
Contact{{rd.contact_link}}
142 | 143 | 144 |
145 |
146 |
147 | 148 |
149 |
150 |
151 |
152 |
153 | 154 | 155 | 156 | 157 | 158 | {% endfor %} 159 | 160 | 161 | -------------------------------------------------------------------------------- /templates/userprofile.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | {% for ud in userdata %} 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | {{ud.fullname}} | Openflock 17 | 18 | 19 | 20 | 21 | 22 |
23 | 25 | 26 | {% if navfullname %} 27 | Menu 28 | 29 | 53 | {% endif %} 54 |
55 | 56 |
57 | 58 |
59 | 60 | 61 |
62 |
63 | 64 | 65 |
66 |
67 |
{{ud.fullname}}
68 | @{{ud.username}} 69 | {% if len_lang_list == 0 %} 70 |

{{ud.fullname}} is an Opensource newbie.

71 | {% else %} 72 |

{{ud.fullname}} is an Opensource enthusiast who likes to code in {% for i in lang_list %} {{i}} {% endfor %} 73 |

74 | {% endif %} 75 | 76 | 77 |
78 | 79 | Follow @{{ud.username}} 80 | {% if ud.fullname == navfullname %} 81 | Share 82 | 83 | {% else %} 84 | Share 85 | 86 | 87 | {% endif %} 88 |
89 | 90 | {% if noofrepos == 0 %} 91 |

You don't have any repositories on GitHub.

92 |

So...Why don't start contributing to the issue/project that inspires you from the promoted repositories/issues?!

{% endif %} 93 |
94 | 95 | {% for rd in repodata %} 96 |

{{rd.reponame}}

97 | 98 | {% if navfullname == ud.fullname %} 99 |

Promote

100 | {% endif %} 101 | 102 | {% if rd.language %} 103 |

{{rd.language}}

104 | {% endif %} 105 |

{{rd.description}}

106 |
107 | {% endfor %} 108 |
109 | 110 | 111 |

Trying to promote a repository from an Organization?

112 |

Enter the URL of the repo here

113 |
114 |
115 | 116 | 117 |
118 |
119 | 120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 | 139 |
140 | 141 | 142 | 143 | 144 | 145 | {% endfor %} 146 | 147 | 148 | 149 | --------------------------------------------------------------------------------