├── .gitignore ├── LICENSE ├── README.md ├── d3status ├── __init__.py ├── app.py ├── consts.py ├── cron │ ├── __init__.py │ └── d3_server_status.py ├── d3status_apns_dev.pem ├── db │ ├── __init__.py │ ├── status.py │ └── subscribers.py ├── exceptions.py ├── handler.py ├── handlers │ ├── __init__.py │ └── status.py ├── i18n │ ├── zh_CN.csv │ └── zh_TW.csv ├── libs │ ├── __init__.py │ ├── apnswrapper.py │ ├── importlib.py │ ├── loader.py │ ├── options.py │ └── utils.py ├── mail.py ├── settings.py ├── settings_local.py ├── tasks │ ├── __init__.py │ ├── apns_tasks.py │ ├── celeryconfig.py │ ├── email_tasks.py │ ├── status_tasks.py │ └── tasks.py ├── templates │ └── errors │ │ ├── 400.html │ │ ├── 400_debug.html │ │ ├── 404.html │ │ ├── 404_debug.html │ │ ├── 500.html │ │ ├── 500_debug.html │ │ └── 500_email.html └── urls.py └── schema.sql /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # D3Status 2 | 3 | Diablo3 server status notification APP, a RESTful API demo powered by Tornado. 4 | 5 | ## Requirement(Python packages) 6 | 7 | - Tornado 8 | - libxml, require libxslt1-dev(libxslt) and libxml2 9 | - pyquery 10 | - python-dateutil 11 | - celery 12 | - apns([https://github.com/simonwhitaker/PyAPNs][1]) 13 | 14 | 15 | [1]: https://github.com/simonwhitaker/PyAPNs 16 | -------------------------------------------------------------------------------- /d3status/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/felinx/d3status/98aa44a153a0d4e848752c09c374df716787aef8/d3status/__init__.py -------------------------------------------------------------------------------- /d3status/app.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | 10 | import os 11 | import platform 12 | import sys 13 | 14 | if platform.system() == "Linux": 15 | os.environ["PYTHON_EGG_CACHE"] = "/tmp/egg" 16 | _root = os.path.dirname(os.path.abspath(__file__)) 17 | # append tasks directory for celeryconfig.py 18 | sys.path.append(os.path.join(_root, "tasks")) 19 | # chdir to current directory 20 | # workaround for d3status-redis27 server which raise exception(celeryd use os.getcwd()) 21 | # when using supervisor to run app.py 22 | os.chdir(_root) 23 | 24 | from tornado import web 25 | from tornado.ioloop import IOLoop 26 | from tornado.httpserver import HTTPServer 27 | from tornado.options import options 28 | from tornado.database import Connection 29 | 30 | try: 31 | import d3status 32 | except ImportError: 33 | import sys 34 | sys.path.append(os.path.join(_root, "..")) 35 | 36 | from d3status.libs.options import parse_options 37 | 38 | 39 | class Application(web.Application): 40 | def __init__(self): 41 | from d3status.urls import handlers, ui_modules 42 | from d3status.db import Model 43 | 44 | settings = dict(debug=options.debug, 45 | template_path=os.path.join(os.path.dirname(__file__), 46 | "templates"), 47 | static_path=os.path.join(os.path.dirname(__file__), 48 | "static"), 49 | login_url=options.login_url, 50 | xsrf_cookies=options.xsrf_cookies, 51 | cookie_secret=options.cookie_secret, 52 | ui_modules=ui_modules, 53 | #autoescape=None, 54 | ) 55 | 56 | # d3status db connection 57 | self.db = Connection(host=options.mysql["host"] + ":" + 58 | options.mysql["port"], 59 | database=options.mysql["database"], 60 | user=options.mysql["user"], 61 | password=options.mysql["password"], 62 | ) 63 | 64 | Model.setup_dbs({"db": self.db}) 65 | 66 | super(Application, self).__init__(handlers, **settings) 67 | 68 | def reverse_api(self, request): 69 | """Returns a URL name for a request""" 70 | handlers = self._get_host_handlers(request) 71 | 72 | for spec in handlers: 73 | match = spec.regex.match(request.path) 74 | if match: 75 | return spec.name 76 | 77 | return None 78 | 79 | 80 | def main(): 81 | parse_options() 82 | 83 | http_server = HTTPServer(Application(), 84 | xheaders=True) 85 | http_server.bind(int(options.port), "127.0.0.1") # listen local only 86 | http_server.start(1) 87 | 88 | IOLoop.instance().start() 89 | 90 | if __name__ == '__main__': 91 | main() 92 | -------------------------------------------------------------------------------- /d3status/consts.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jul 1, 2012 7 | # 8 | 9 | CATEGORY_AMERICAS = "Americas" 10 | CATEGORY_EUROPE = "Europe" 11 | CATEGORY_ASIA = "Asia" 12 | CATEGORYS = (CATEGORY_AMERICAS, CATEGORY_EUROPE, CATEGORY_ASIA) 13 | 14 | SUBSCRIBE_STATUS_ON = "on" 15 | SUBSCRIBE_STATUS_OFF = "off" 16 | 17 | LOCALES = ("en", "zh_CN", "zh_TW") 18 | -------------------------------------------------------------------------------- /d3status/cron/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/felinx/d3status/98aa44a153a0d4e848752c09c374df716787aef8/d3status/cron/__init__.py -------------------------------------------------------------------------------- /d3status/cron/d3_server_status.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jul 2, 2012 7 | # 8 | 9 | import os 10 | import platform 11 | import sys 12 | import logging 13 | from pyquery import PyQuery as pq 14 | from lxml import etree 15 | 16 | from tornado.httpclient import HTTPRequest, HTTPClient 17 | from tornado.options import options 18 | 19 | _dir = os.path.dirname(os.path.abspath(__file__)) 20 | _root = os.path.join(_dir, "..") 21 | # append tasks directory for celeryconfig.py 22 | sys.path.append(os.path.join(_root, "tasks")) 23 | 24 | try: 25 | # tornado process 26 | import d3status 27 | except ImportError: 28 | # celeryd process runtime env 29 | if platform.system() == "Linux": 30 | os.environ["PYTHON_EGG_CACHE"] = "/tmp/egg" 31 | sys.path.append(os.path.join(_root, "..")) 32 | 33 | from tornado.options import options 34 | from tornado.database import Connection 35 | 36 | from d3status.libs.options import parse_options 37 | parse_options() 38 | 39 | from d3status.db import Model 40 | from d3status.db import load_model 41 | from d3status.mail import send_email 42 | from d3status.tasks import status_tasks 43 | 44 | # db connection 45 | db = Connection(host=options.mysql["host"] + ":" + 46 | options.mysql["port"], 47 | database=options.mysql["database"], 48 | user=options.mysql["user"], 49 | password=options.mysql["password"], 50 | ) 51 | 52 | Model.setup_dbs({"db": db}) 53 | 54 | 55 | def update_server_status(): 56 | url = options.d3_server_status_url 57 | req = HTTPRequest(url=url) 58 | 59 | client = HTTPClient() 60 | response = client.fetch(req) 61 | if response.code == 200: 62 | status = _parse_server_status(response.body) 63 | changed_status = load_model("status").update_status(status) 64 | if changed_status: 65 | status_tasks.status_notification_task.delay(changed_status) 66 | else: 67 | err = "GET_D3_SERVER_STAUTS_ERROR: %s\n%s" (response.code, response) 68 | logging.error(err) 69 | 70 | # send email 71 | subject = "[%s]Get D3 server status error" % options.sitename 72 | body = err 73 | if options.send_error_email: 74 | send_email(options.email_from, options.admins, subject, body) 75 | 76 | 77 | def _parse_server_status(body): 78 | status = {} 79 | 80 | q = pq(etree.fromstring(body)) 81 | boxes = q(".box") # category box 82 | for box in boxes: 83 | box_q = pq(etree.fromstring(etree.tostring(box))) 84 | category = box_q(".category")[0].text.strip() 85 | status[category] = {} 86 | servers = box_q(".server") 87 | for server in servers: 88 | server_q = pq(etree.fromstring(etree.tostring(server))) 89 | server_name = server_q(".server-name")[0].text.strip().replace(" ", "") 90 | if server_name: 91 | status_icon = server_q(".status-icon")[0] 92 | class_ = status_icon.get("class") 93 | if class_: 94 | st = 0 95 | if "up" in class_: 96 | st = 1 97 | status[category][server_name] = st 98 | 99 | return status 100 | 101 | 102 | if __name__ == "__main__": 103 | update_server_status() 104 | -------------------------------------------------------------------------------- /d3status/d3status_apns_dev.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIFdzCCBF+gAwIBAgIIDGJ7998UXlkwDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV 3 | BAYTAlVTMRMwEQYDVQQKDApBcHBsZSBJbmMuMSwwKgYDVQQLDCNBcHBsZSBXb3Js 4 | ZHdpZGUgRGV2ZWxvcGVyIFJlbGF0aW9uczFEMEIGA1UEAww7QXBwbGUgV29ybGR3 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1ATad9K9UjnpQzzEe2iuDK8IA2fxqQSRZ1hEU0YP1Ap1H3huhl1o6hU 55 | k6uE0OmOGn0nGNTZj44V1CtfuFjRfirDAMDGkso4qu4Bbv0nB/dv0I1cGeEJ3KWQ 56 | AIbu0oECgYEAtHFq9F+HwqfBcAhC8J48UGIDxWmvS/ZJeAPDKZoJMlZ2B++k883T 57 | e/b95T5cdenYkcBFFE0aouDicw20+3zEtx0DxT2vIqhQ/SMj2aoP1k8DGDVBxn+h 58 | GxMvIBE7wPHfdnmCaqXW56yM9t1aAbWPX/21XqDSKgrVQFhRkjLfAoQ= 59 | -----END RSA PRIVATE KEY----- 60 | -------------------------------------------------------------------------------- /d3status/db/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | from d3status.libs.loader import load 10 | 11 | load_model = load("d3status.db", "Model") 12 | 13 | 14 | class Model(object): 15 | _dbs = {} 16 | 17 | @classmethod 18 | def setup_dbs(cls, dbs): 19 | cls._dbs = dbs 20 | 21 | @property 22 | def dbs(self): 23 | return self.dbs 24 | 25 | # legacy support 26 | @property 27 | def db(self): 28 | return self._dbs.get("db", None) 29 | -------------------------------------------------------------------------------- /d3status/db/status.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | from d3status.db import Model 10 | 11 | 12 | class StatusModel(Model): 13 | def get_status(self): 14 | status = {"status": {"items": []}} 15 | items = status["status"]["items"] 16 | categorys = {} 17 | 18 | rows = self.db.query("select * from status") 19 | for row in rows: 20 | categorys.setdefault(row.category, {})[row.service] = row.status 21 | 22 | for category, services in categorys.iteritems(): 23 | items.append({"category": category, 24 | "services": services}) 25 | 26 | if rows: 27 | status["count"] = len(items) 28 | return status 29 | else: 30 | return {} 31 | 32 | def update_status(self, status): 33 | changed_status = {} 34 | 35 | old_status = self.get_status() 36 | old_status_ = {} 37 | if old_status: 38 | for item in old_status["status"]["items"]: 39 | old_status_[item["category"]] = item["services"] 40 | 41 | for category, services in status.iteritems(): 42 | for name, st in services.iteritems(): 43 | old_st = old_status_[category].get(name, None) 44 | if old_st is not None and old_st != st: 45 | changed_status.setdefault(category, {})[name] = st 46 | self._update_status(category, name, st) 47 | 48 | return changed_status 49 | 50 | def _update_status(self, category, server_name, status): 51 | row = self.db.get("select * from status where category=%s and service=%s", 52 | category, server_name) 53 | if not row: 54 | self.db.execute("insert into status (category, service, status) " 55 | "values (%s, %s, %s)", 56 | category, server_name, status) 57 | else: 58 | self.db.execute("update status set status=%s where id=%s", 59 | status, row.id) 60 | -------------------------------------------------------------------------------- /d3status/db/subscribers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | from d3status.db import Model 10 | from d3status import consts 11 | 12 | 13 | class SubscribersModel(Model): 14 | def subscribe(self, token, categorys, locale="en"): 15 | row = self.db.get("select * from subscribers where token=%s", token) 16 | if not row: 17 | sql = "insert into subscribers (token, categorys, status, locale) " \ 18 | "values (%s, %s, %s, %s)" 19 | self.db.execute(sql, token, categorys, consts.SUBSCRIBE_STATUS_ON, 20 | locale) 21 | else: 22 | sql = "update subscribers set categorys=%s, locale=%s where token=%s" 23 | self.db.execute(sql, categorys, locale, token) 24 | 25 | def unsubscribe(self, token): 26 | sql = "update subscribers set status=%s where token=%s" 27 | self.db.execute(sql, consts.SUBSCRIBE_STATUS_OFF, token) 28 | 29 | def get_subscribers(self, limit=200, offset=0): 30 | return self.db.query("select * from subscribers where status='on' " 31 | "limit %s offset %s", 32 | limit, offset) 33 | -------------------------------------------------------------------------------- /d3status/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | from tornado import escape 10 | from tornado.web import HTTPError 11 | 12 | 13 | class HTTPAPIError(HTTPError): 14 | """API error handling exception 15 | 16 | API server always returns formatted JSON to client even there is 17 | an internal server error. 18 | """ 19 | def __init__(self, status_code=400, error_detail="", error_type="", 20 | notification="", response="", log_message=None, *args): 21 | 22 | super(HTTPAPIError, self).__init__(int(status_code), log_message, *args) 23 | 24 | self.error_type = error_type if error_type else \ 25 | _error_types.get(self.status_code, "unknow_error") 26 | self.error_detail = error_detail 27 | self.notification = {"message": notification} if notification else {} 28 | self.response = response if response else {} 29 | 30 | def __str__(self): 31 | err = {"meta": {"code": self.status_code, "errorType": self.error_type}} 32 | self._set_err(err, ["notification", "response"]) 33 | 34 | if self.error_detail: 35 | err["meta"]["errorDetail"] = self.error_detail 36 | 37 | return escape.json_encode(err) 38 | 39 | def _set_err(self, err, names): 40 | for name in names: 41 | v = getattr(self, name) 42 | if v: 43 | err[name] = v 44 | 45 | 46 | _error_types = {400: "param_error", 47 | 401: "invalid_auth", 48 | 403: "not_authorized", 49 | 404: "endpoint_error", 50 | 405: "method_not_allowed", 51 | 500: "server_error"} 52 | -------------------------------------------------------------------------------- /d3status/handler.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | import traceback 10 | import logging 11 | 12 | from tornado import escape 13 | from tornado.options import options 14 | from tornado.web import RequestHandler as BaseRequestHandler, HTTPError 15 | from d3status import exceptions 16 | from d3status.tasks import email_tasks 17 | 18 | 19 | class BaseHandler(BaseRequestHandler): 20 | def get(self, *args, **kwargs): 21 | # enable GET request when enable delegate get to post 22 | if options.app_get_to_post: 23 | self.post(*args, **kwargs) 24 | else: 25 | raise exceptions.HTTPAPIError(405) 26 | 27 | def prepare(self): 28 | self.traffic_control() 29 | pass 30 | 31 | def traffic_control(self): 32 | # traffic control hooks for api call etc 33 | self.log_apicall() 34 | pass 35 | 36 | def log_apicall(self): 37 | pass 38 | 39 | 40 | class RequestHandler(BaseHandler): 41 | pass 42 | 43 | 44 | class APIHandler(BaseHandler): 45 | def get_current_user(self): 46 | pass 47 | 48 | def finish(self, chunk=None, notification=None): 49 | if chunk is None: 50 | chunk = {} 51 | 52 | if isinstance(chunk, dict): 53 | chunk = {"meta": {"code": 200}, "response": chunk} 54 | 55 | if notification: 56 | chunk["notification"] = {"message": notification} 57 | 58 | callback = escape.utf8(self.get_argument("callback", None)) 59 | if callback: 60 | self.set_header("Content-Type", "application/x-javascript") 61 | 62 | if isinstance(chunk, dict): 63 | chunk = escape.json_encode(chunk) 64 | 65 | self._write_buffer = [callback, "(", chunk, ")"] if chunk else [] 66 | super(APIHandler, self).finish() 67 | else: 68 | self.set_header("Content-Type", "application/json; charset=UTF-8") 69 | super(APIHandler, self).finish(chunk) 70 | 71 | def write_error(self, status_code, **kwargs): 72 | """Override to implement custom error pages.""" 73 | debug = self.settings.get("debug", False) 74 | try: 75 | exc_info = kwargs.pop('exc_info') 76 | e = exc_info[1] 77 | 78 | if isinstance(e, exceptions.HTTPAPIError): 79 | pass 80 | elif isinstance(e, HTTPError): 81 | e = exceptions.HTTPAPIError(e.status_code) 82 | else: 83 | e = exceptions.HTTPAPIError(500) 84 | 85 | exception = "".join([ln for ln in traceback.format_exception(*exc_info)]) 86 | 87 | if status_code == 500 and not debug: 88 | self._send_error_email(exception) 89 | 90 | if debug: 91 | e.response["exception"] = exception 92 | 93 | self.clear() 94 | self.set_status(200) # always return 200 OK for API errors 95 | self.set_header("Content-Type", "application/json; charset=UTF-8") 96 | self.finish(str(e)) 97 | except Exception: 98 | logging.error(traceback.format_exc()) 99 | return super(APIHandler, self).write_error(status_code, **kwargs) 100 | 101 | def _send_error_email(self, exception): 102 | try: 103 | # send email 104 | subject = "[%s]Internal Server Error" % options.sitename 105 | body = self.render_string("errors/500_email.html", 106 | exception=exception) 107 | if options.send_error_email: 108 | email_tasks.send_email_task.delay(options.email_from, 109 | options.admins, subject, body) 110 | except Exception: 111 | logging.error(traceback.format_exc()) 112 | 113 | 114 | class ErrorHandler(RequestHandler): 115 | """Default 404: Not Found handler.""" 116 | def prepare(self): 117 | super(ErrorHandler, self).prepare() 118 | raise HTTPError(404) 119 | 120 | 121 | class APIErrorHandler(APIHandler): 122 | """Default API 404: Not Found handler.""" 123 | def prepare(self): 124 | super(APIErrorHandler, self).prepare() 125 | raise exceptions.HTTPAPIError(404) 126 | -------------------------------------------------------------------------------- /d3status/handlers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/felinx/d3status/98aa44a153a0d4e848752c09c374df716787aef8/d3status/handlers/__init__.py -------------------------------------------------------------------------------- /d3status/handlers/status.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | from d3status.handler import APIHandler 10 | from d3status.db import load_model 11 | from d3status import consts 12 | from d3status.tasks import status_tasks 13 | 14 | 15 | class StatusIndexHandler(APIHandler): 16 | def get(self): 17 | self.finish(load_model('status').get_status()) 18 | 19 | 20 | class StatusSubscribeHandler(APIHandler): 21 | def post(self): 22 | token = self.get_argument("deviceToken", "") 23 | categorys = self.get_argument("categorys", "").split(",") 24 | categorys = [c for c in categorys if c in consts.CATEGORYS] 25 | categorys = ",".join(categorys) 26 | locale = self.get_argument("locale", "en") 27 | if locale not in consts.LOCALES: 28 | locale = "en" 29 | 30 | if token: 31 | load_model("subscribers").subscribe(token, categorys, locale) 32 | 33 | 34 | class StatusUnsubscribeHandler(APIHandler): 35 | def post(self): 36 | token = self.get_argument("deviceToken", "") 37 | if token: 38 | load_model("subscribers").unsubscribe(token) 39 | 40 | 41 | handlers = [(r"/status", StatusIndexHandler), 42 | (r"/status/subscribe", StatusSubscribeHandler), 43 | (r"/status/unsubscribe", StatusUnsubscribeHandler), 44 | ] 45 | -------------------------------------------------------------------------------- /d3status/i18n/zh_CN.csv: -------------------------------------------------------------------------------- 1 | "Americas", "美服" 2 | "Europe", "欧服" 3 | "Asia", "台服" 4 | "Diablo3 %s server status has changed to %s","暗黑破坏神%s%s" 5 | "Available", "恢复正常" 6 | "Unavailable", "现在维护" -------------------------------------------------------------------------------- /d3status/i18n/zh_TW.csv: -------------------------------------------------------------------------------- 1 | "Americas", "美服" 2 | "Europe", "歐服" 3 | "Asia", "台服" 4 | "Diablo3 %s server status has changed to %s","暗黑破壞神%s%s" 5 | "Available", "恢復正常" 6 | "Unavailable", "現在維護" -------------------------------------------------------------------------------- /d3status/libs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/felinx/d3status/98aa44a153a0d4e848752c09c374df716787aef8/d3status/libs/__init__.py -------------------------------------------------------------------------------- /d3status/libs/apnswrapper.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | import time 10 | import traceback 11 | import logging 12 | from apns import APNs, Payload 13 | 14 | _ignored_content_keys = ("message",) # maybe more keys later 15 | 16 | 17 | class APNsWrapper(APNs): 18 | def __init__(self, use_sandbox=False, cert_file=None, key_file=None): 19 | super(APNsWrapper, self).__init__(use_sandbox, cert_file, key_file) 20 | self._payloads = [] 21 | 22 | def append(self, token, notification, alert=None, badge=None, sound=None): 23 | if not alert: 24 | alert = notification.get("message", None) 25 | 26 | if alert and isinstance(alert, dict): 27 | alert = alert.get("message", None) 28 | 29 | for key in _ignored_content_keys: 30 | try: 31 | del notification[key] 32 | except KeyError: 33 | pass 34 | 35 | payload = Payload(alert, badge, sound, custom=notification) 36 | self._payloads.append((token, payload)) 37 | 38 | def flush(self): 39 | if self._payloads: 40 | for token, payload in self._payloads: 41 | try: 42 | self.gateway_server.write(self.gateway_server._get_notification(token, payload)) 43 | except: 44 | logging.error(traceback.format_exc()) 45 | # trigger reconnect 46 | self._gateway_connection = None 47 | 48 | self._payloads = [] 49 | -------------------------------------------------------------------------------- /d3status/libs/importlib.py: -------------------------------------------------------------------------------- 1 | # License for code in this file that was taken from Python 2.7. 2 | 3 | # PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 4 | # -------------------------------------------- 5 | # 6 | # 1. This LICENSE AGREEMENT is between the Python Software Foundation 7 | # ("PSF"), and the Individual or Organization ("Licensee") accessing and 8 | # otherwise using this software ("Python") in source or binary form and 9 | # its associated documentation. 10 | # 11 | # 2. Subject to the terms and conditions of this License Agreement, PSF 12 | # hereby grants Licensee a nonexclusive, royalty-free, world-wide 13 | # license to reproduce, analyze, test, perform and/or display publicly, 14 | # prepare derivative works, distribute, and otherwise use Python 15 | # alone or in any derivative version, provided, however, that PSF's 16 | # License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 17 | # 2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; 18 | # All Rights Reserved" are retained in Python alone or in any derivative 19 | # version prepared by Licensee. 20 | # 21 | # 3. In the event Licensee prepares a derivative work that is based on 22 | # or incorporates Python or any part thereof, and wants to make 23 | # the derivative work available to others as provided herein, then 24 | # Licensee hereby agrees to include in any such work a brief summary of 25 | # the changes made to Python. 26 | # 27 | # 4. PSF is making Python available to Licensee on an "AS IS" 28 | # basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR 29 | # IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND 30 | # DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS 31 | # FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT 32 | # INFRINGE ANY THIRD PARTY RIGHTS. 33 | # 34 | # 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 35 | # FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS 36 | # A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, 37 | # OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 38 | # 39 | # 6. This License Agreement will automatically terminate upon a material 40 | # breach of its terms and conditions. 41 | # 42 | # 7. Nothing in this License Agreement shall be deemed to create any 43 | # relationship of agency, partnership, or joint venture between PSF and 44 | # Licensee. This License Agreement does not grant permission to use PSF 45 | # trademarks or trade name in a trademark sense to endorse or promote 46 | # products or services of Licensee, or any third party. 47 | # 48 | # 8. By copying, installing or otherwise using Python, Licensee 49 | # agrees to be bound by the terms and conditions of this License 50 | # Agreement. 51 | import sys 52 | 53 | 54 | def _resolve_name(name, package, level): 55 | """Return the absolute name of the module to be imported.""" 56 | if not hasattr(package, 'rindex'): 57 | raise ValueError("'package' not set to a string") 58 | dot = len(package) 59 | for x in xrange(level, 1, -1): 60 | try: 61 | dot = package.rindex('.', 0, dot) 62 | except ValueError: 63 | raise ValueError("attempted relative import beyond top-level " 64 | "package") 65 | return "%s.%s" % (package[:dot], name) 66 | 67 | 68 | def import_module(name, package=None): 69 | """Import a module. 70 | 71 | The 'package' argument is required when performing a relative import. It 72 | specifies the package to use as the anchor point from which to resolve the 73 | relative import to an absolute import. 74 | 75 | """ 76 | if name.startswith('.'): 77 | if not package: 78 | raise TypeError("relative imports require the 'package' argument") 79 | level = 0 80 | for character in name: 81 | if character != '.': 82 | break 83 | level += 1 84 | name = _resolve_name(name[level:], package, level) 85 | __import__(name) 86 | return sys.modules[name] 87 | -------------------------------------------------------------------------------- /d3status/libs/loader.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | import importlib 10 | 11 | _module_instances = {} 12 | 13 | 14 | def load(root_module, suffix): 15 | def load_(name): 16 | name = name.lower() 17 | key = "%s.%s" % (root_module, name) 18 | if key not in _module_instances: 19 | try: 20 | module = importlib.import_module(".%s" % name, root_module) 21 | except ImportError: 22 | module = importlib.import_module(".%s" % name[:-1], root_module) 23 | 24 | # load("breeze.db", "users", "Model") will return UsersModel class obj 25 | cls = getattr(module, 26 | "%s%s%s%s" % (name[0].upper(), name[1:], 27 | suffix[0].upper(), suffix[1:])) 28 | _module_instances[key] = cls() 29 | 30 | return _module_instances[key] 31 | 32 | return load_ 33 | -------------------------------------------------------------------------------- /d3status/libs/options.py: -------------------------------------------------------------------------------- 1 | ## -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | import logging 10 | import os 11 | 12 | from tornado.options import parse_command_line, options, define 13 | 14 | 15 | def parse_config_file(path): 16 | """Rewrite tornado default parse_config_file. 17 | 18 | Parses and loads the Python config file at the given path. 19 | 20 | This version allow customize new options which are not defined before 21 | from a configuration file. 22 | """ 23 | config = {} 24 | execfile(path, config, config) 25 | for name in config: 26 | if name in options: 27 | options[name].set(config[name]) 28 | else: 29 | define(name, config[name]) 30 | 31 | 32 | def parse_options(): 33 | _root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") 34 | _settings = os.path.join(_root, "settings.py") 35 | _settings_local = os.path.join(_root, "settings_local.py") 36 | 37 | try: 38 | parse_config_file(_settings) 39 | logging.info("Using settings.py as default settings.") 40 | except Exception, e: 41 | logging.error("No any default settings, are you sure? Exception: %s" % e) 42 | 43 | try: 44 | parse_config_file(_settings_local) 45 | logging.info("Override some settings with local settings.") 46 | except Exception, e: 47 | logging.error("No local settings. Exception: %s" % e) 48 | 49 | parse_command_line() 50 | -------------------------------------------------------------------------------- /d3status/libs/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | import os 10 | import mimetypes 11 | 12 | 13 | def find_modules(modules_dir): 14 | try: 15 | return [f[:-3] for f in os.listdir(modules_dir) 16 | if not f.startswith('_') and f.endswith('.py')] 17 | except OSError: 18 | return [] 19 | -------------------------------------------------------------------------------- /d3status/mail.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | import re 10 | import logging 11 | import smtplib 12 | import time 13 | from datetime import datetime, timedelta 14 | from email import encoders 15 | from email.mime.multipart import MIMEMultipart 16 | from email.mime.base import MIMEBase 17 | from email.mime.text import MIMEText 18 | from email.utils import COMMASPACE 19 | from email.utils import formatdate 20 | 21 | from tornado.escape import utf8 22 | from tornado.options import options 23 | 24 | __all__ = ("send_email", "EmailAddress") 25 | 26 | # borrow email re pattern from django 27 | _email_re = re.compile( 28 | r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom 29 | r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string 30 | r')@(?:[A-Z0-9]+(?:-*[A-Z0-9]+)*\.)+[A-Z]{2,6}$', re.IGNORECASE) # domain 31 | 32 | 33 | def send_email(fr, to, subject, body, html=None, attachments=[]): 34 | """Send an email. 35 | 36 | If an HTML string is given, a mulitpart message will be generated with 37 | plain text and HTML parts. Attachments can be added by providing as a 38 | list of (filename, data) tuples. 39 | """ 40 | # convert EmailAddress to pure string 41 | if isinstance(fr, EmailAddress): 42 | fr = str(fr) 43 | else: 44 | fr = utf8(fr) 45 | to = [utf8(t) for t in to] 46 | 47 | if html: 48 | # Multipart HTML and plain text 49 | message = MIMEMultipart("alternative") 50 | message.attach(MIMEText(body, "plain")) 51 | message.attach(MIMEText(html, "html")) 52 | else: 53 | # Plain text 54 | message = MIMEText(body) 55 | if attachments: 56 | part = message 57 | message = MIMEMultipart("mixed") 58 | message.attach(part) 59 | for filename, data in attachments: 60 | part = MIMEBase("application", "octet-stream") 61 | part.set_payload(data) 62 | encoders.encode_base64(part) 63 | part.add_header("Content-Disposition", "attachment", 64 | filename=filename) 65 | message.attach(part) 66 | 67 | message["Date"] = formatdate(time.time()) 68 | message["From"] = fr 69 | message["To"] = COMMASPACE.join(to) 70 | message["Subject"] = utf8(subject) 71 | 72 | _get_session().send_mail(fr, to, utf8(message.as_string())) 73 | 74 | 75 | class EmailAddress(object): 76 | def __init__(self, addr, name=""): 77 | assert _email_re.match(addr), "Email address(%s) is invalid." % addr 78 | 79 | self.addr = addr 80 | if name: 81 | self.name = name 82 | else: 83 | self.name = addr.split("@")[0] 84 | 85 | def __str__(self): 86 | return '%s <%s>' % (utf8(self.name), utf8(self.addr)) 87 | 88 | 89 | class _SMTPSession(object): 90 | def __init__(self, host, user='', password='', duration=30, tls=False): 91 | self.host = host 92 | self.user = user 93 | self.password = password 94 | self.duration = duration 95 | self.tls = tls 96 | self.session = None 97 | self.deadline = datetime.now() 98 | self.renew() 99 | 100 | def send_mail(self, fr, to, message): 101 | if self.timeout: 102 | self.renew() 103 | 104 | try: 105 | self.session.sendmail(fr, to, message) 106 | except Exception, e: 107 | err = "Send email from %s to %s failed!\n Exception: %s!" \ 108 | % (fr, to, e) 109 | logging.error(err) 110 | self.renew() 111 | 112 | @property 113 | def timeout(self): 114 | if datetime.now() < self.deadline: 115 | return False 116 | else: 117 | return True 118 | 119 | def renew(self): 120 | try: 121 | if self.session: 122 | self.session.quit() 123 | except Exception: 124 | pass 125 | 126 | self.session = smtplib.SMTP(self.host) 127 | if self.user and self.password: 128 | if self.tls: 129 | self.session.starttls() 130 | 131 | self.session.login(self.user, self.password) 132 | 133 | self.deadline = datetime.now() + timedelta(seconds=self.duration * 60) 134 | 135 | 136 | def _get_session(): 137 | global _session 138 | if _session is None: 139 | _session = _SMTPSession(options.smtp['host'], 140 | options.smtp['user'], 141 | options.smtp['password'], 142 | options.smtp['duration'], 143 | options.smtp['tls']) 144 | 145 | return _session 146 | 147 | _session = None 148 | -------------------------------------------------------------------------------- /d3status/settings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | """Project settings""" 9 | 10 | import platform 11 | import os 12 | 13 | # can't use __file__ directly here because it's parsed by tornado.options 14 | import d3status 15 | root_dir = os.path.dirname(os.path.abspath(d3status.__file__)) 16 | 17 | if platform.node() == "FELINX": # FELINX is the hosting server name. 18 | debug = False 19 | else: 20 | debug = True 21 | 22 | loglevel = "INFO" # for celeryd 23 | port = 8888 24 | 25 | d3_server_status_url = "http://us.battle.net/d3/en/status" 26 | 27 | sitename = "D3 Status" 28 | domain = "api.feilong.me" 29 | home_url = "http://%s/d3" % domain 30 | login_url = "http://%s/login" % home_url 31 | app_url_prefix = "/d3/v1" 32 | email_from = "%s " % (sitename, domain) 33 | admins = ("Felinx ",) 34 | send_error_email = True 35 | cookie_secret = "d1d87395-8272-4749-b2f2-dcabd3903a1c" 36 | xsrf_cookies = False 37 | 38 | # Apple push notification settings 39 | apns_sandbox = debug 40 | apns_certificate = "d3status_apns_dev.pem" 41 | apns_certificate_key = None 42 | 43 | mysql = {"host": "localhost", 44 | "port": "3306", 45 | "database": "d3status", 46 | "user": "felinx", 47 | "password": "felinx" 48 | } 49 | 50 | smtp = {"host": "localhost", 51 | "user": "", 52 | "password": "", 53 | "duration": 30, 54 | "tls": False 55 | } 56 | -------------------------------------------------------------------------------- /d3status/settings_local.py: -------------------------------------------------------------------------------- 1 | debug = True 2 | apns_sandbox = True 3 | -------------------------------------------------------------------------------- /d3status/tasks/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/felinx/d3status/98aa44a153a0d4e848752c09c374df716787aef8/d3status/tasks/__init__.py -------------------------------------------------------------------------------- /d3status/tasks/apns_tasks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on May 30, 2012 7 | # 8 | 9 | import os 10 | 11 | from celery.task import task 12 | from tornado.options import options 13 | 14 | from d3status.libs.apnswrapper import APNsWrapper 15 | 16 | _root = os.path.join(os.path.dirname(__file__), "..") 17 | _apns = None 18 | 19 | 20 | @task 21 | def apns_push_task(tokens, notification, alert=None, badge=None, sound=None): 22 | apns_push(tokens, notification, alert, badge, sound) 23 | 24 | 25 | def apns_push(tokens, notification, alert=None, badge=None, sound=None): 26 | _setup_apns() 27 | if isinstance(tokens, basestring): 28 | tokens = [tokens, ] 29 | 30 | for token in tokens: 31 | _apns.append(token, notification, alert, badge, sound) 32 | 33 | _apns.flush() 34 | 35 | 36 | def _setup_apns(): 37 | global _apns 38 | 39 | if not _apns: 40 | cert_file = os.path.join(_root, options.apns_certificate) 41 | if not options.apns_certificate_key: 42 | key_file = None 43 | else: 44 | key_file = os.path.join(_root, options.apns_certificate_key) 45 | 46 | _apns = APNsWrapper(use_sandbox=options.apns_sandbox, 47 | cert_file=cert_file, 48 | key_file=key_file) 49 | -------------------------------------------------------------------------------- /d3status/tasks/celeryconfig.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | 8 | 9 | CELERY_IMPORTS = ("tasks", ) 10 | 11 | CELERY_RESULT_BACKEND = "redis" 12 | CELERY_REDIS_HOST = "localhost" 13 | CELERY_REDIS_PORT = 6379 14 | CELERY_REDIS_DB = 0 15 | 16 | BROKER_URL = "redis://%s:%s/%s" % (CELERY_REDIS_HOST, CELERY_REDIS_PORT, 17 | CELERY_REDIS_DB) 18 | -------------------------------------------------------------------------------- /d3status/tasks/email_tasks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | from celery.task import task 10 | from d3status.mail import send_email 11 | 12 | 13 | @task 14 | def send_email_task(fr, to, subject, body, html=None, attachments=[]): 15 | send_email(fr, to, subject, body, html, attachments) 16 | -------------------------------------------------------------------------------- /d3status/tasks/status_tasks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jul 2, 2012 7 | # 8 | 9 | import os 10 | import tornado.locale 11 | 12 | from celery.task import task 13 | from tornado.options import options 14 | from d3status.db import load_model 15 | from d3status.tasks import apns_tasks 16 | 17 | 18 | @task 19 | def status_notification_task(changed_status): 20 | status_notifciation(changed_status) 21 | 22 | 23 | def status_notifciation(changed_status): 24 | notifications = {} 25 | for category, services in changed_status.iteritems(): 26 | for name, st in services.iteritems(): 27 | # just push notification about game server now 28 | if name == "GameServer": 29 | notifications[category] = st 30 | 31 | for category, st in notifications.iteritems(): 32 | status = "Available" if st else "Unavailable" 33 | 34 | offset = 0 35 | limit = 200 36 | while True: 37 | subscribers = load_model("subscribers").get_subscribers(limit, offset) 38 | if not subscribers: 39 | break 40 | 41 | for subscribe in subscribers: 42 | if category in subscribe.categorys: 43 | alert = _trans_alert("Diablo3 %s server status has changed to %s", 44 | category, status, subscribe.locale) 45 | apns_tasks.apns_push_task.delay(subscribe.token, {}, 46 | alert=alert, badge=1, 47 | sound="default") 48 | offset += len(subscribers) 49 | 50 | 51 | def _trans(s, locale): 52 | locale = tornado.locale.get(locale) 53 | s = locale.translate(s).strip("\"") 54 | 55 | return s 56 | 57 | 58 | def _trans_alert(alert, category, status, locale): 59 | def _(s): 60 | return _trans(s, locale) 61 | 62 | return _(alert) % (_(category), _(status)) 63 | 64 | 65 | _i18n_dir = os.path.join(os.path.join(os.path.dirname(__file__), ".."), 'i18n') 66 | tornado.locale.load_translations(_i18n_dir) 67 | -------------------------------------------------------------------------------- /d3status/tasks/tasks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | """Celery tasks center 10 | 11 | Setup env for celery tasks and import them. 12 | """ 13 | 14 | import os 15 | import platform 16 | import sys 17 | 18 | _dir = os.path.dirname(os.path.abspath(__file__)) 19 | _root = os.path.join(_dir, "..") 20 | 21 | try: 22 | # tornado process 23 | import d3status 24 | except ImportError: 25 | # celeryd process runtime env 26 | if platform.system() == "Linux": 27 | os.environ["PYTHON_EGG_CACHE"] = "/tmp/egg" 28 | sys.path.append(os.path.join(_root, "..")) 29 | # append current directory for celeryconfig.py 30 | sys.path.append(_dir) 31 | 32 | from tornado.options import options 33 | from tornado.database import Connection 34 | 35 | from d3status.libs.options import parse_options 36 | parse_options() 37 | 38 | from d3status.db import Model 39 | 40 | # db connection 41 | db = Connection(host=options.mysql["host"] + ":" + 42 | options.mysql["port"], 43 | database=options.mysql["database"], 44 | user=options.mysql["user"], 45 | password=options.mysql["password"], 46 | ) 47 | 48 | Model.setup_dbs({"db": db}) 49 | 50 | 51 | from d3status.libs.importlib import import_module 52 | from d3status.libs.utils import find_modules 53 | 54 | 55 | def _load_tasks(): 56 | _current_module = sys.modules[__name__] 57 | for m in find_modules(os.path.dirname(__file__)): 58 | if m.endswith("_tasks"): # xxx_tasks.py 59 | try: 60 | mod = import_module("." + m, package="d3status.tasks") 61 | for func in dir(mod): 62 | if func.endswith("_task"): 63 | setattr(_current_module, func, getattr(mod, func)) 64 | except ImportError: 65 | pass 66 | 67 | _load_tasks() 68 | 69 | -------------------------------------------------------------------------------- /d3status/templates/errors/400.html: -------------------------------------------------------------------------------- 1 | {% extends ../base.html %} 2 | 3 | {% block body %} 4 | 400 Bad Request 5 | {% end %} 6 | -------------------------------------------------------------------------------- /d3status/templates/errors/400_debug.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 400 Bad Request 5 | 6 | 7 | 400 Bad Request 8 |

9 | URL:{{request.full_url()}} 10 |

11 | Exeception: 12 |
13 | {% raw str(exception).replace("\n", "
") %} 14 | 15 | 16 | -------------------------------------------------------------------------------- /d3status/templates/errors/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Page Not Found :( 6 | 28 | 29 | 30 |
31 |

Not found :(

32 |
-------------------------------------------------------------------------------- /d3status/templates/errors/404_debug.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 404 Page Not Find 5 | 6 | 7 | 404 Page Not Find 8 |

9 | URL:{{request.full_url()}} 10 | 11 | 12 | -------------------------------------------------------------------------------- /d3status/templates/errors/500.html: -------------------------------------------------------------------------------- 1 | {% extends ../base.html %} 2 | 3 | {% block body %} 4 | 500 Server Error 5 | {% end %} -------------------------------------------------------------------------------- /d3status/templates/errors/500_debug.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 500 Internal Server Error 5 | 6 | 7 | 500 Internal Server Error 8 |

9 | URL:{{request.full_url()}} 10 |

11 | Exeception: 12 |
13 | {% raw str(exception).replace("\n", "
") %} 14 | 15 | 16 | -------------------------------------------------------------------------------- /d3status/templates/errors/500_email.html: -------------------------------------------------------------------------------- 1 | 500 Internal Server Error 2 | 3 | URL: 4 | {{request.full_url()}} 5 | 6 | Exeception: 7 | {% raw str(exception) %} -------------------------------------------------------------------------------- /d3status/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (c) 2012 feilong.me. All rights reserved. 4 | # 5 | # @author: Felinx Lee 6 | # Created on Jun 30, 2012 7 | # 8 | 9 | try: 10 | import importlib 11 | except: 12 | from d3status.libs import importlib 13 | 14 | from tornado.options import options 15 | from tornado.web import url 16 | from d3status.handler import APIErrorHandler 17 | 18 | handlers = [] 19 | ui_modules = {} 20 | 21 | # the module names in handlers folder 22 | handler_names = ["status", ] 23 | 24 | 25 | def _generate_handler_patterns(root_module, handler_names, prefix=options.app_url_prefix): 26 | for name in handler_names: 27 | module = importlib.import_module(".%s" % name, root_module) 28 | module_hanlders = getattr(module, "handlers", None) 29 | if module_hanlders: 30 | _handlers = [] 31 | for handler in module_hanlders: 32 | try: 33 | patten = r"%s%s" % (prefix, handler[0]) 34 | if len(handler) == 2: 35 | _handlers.append((patten, 36 | handler[1])) 37 | elif len(handler) == 3: 38 | _handlers.append(url(patten, 39 | handler[1], 40 | name=handler[2]) 41 | ) 42 | else: 43 | pass 44 | except IndexError: 45 | pass 46 | 47 | handlers.extend(_handlers) 48 | 49 | _generate_handler_patterns("d3status.handlers", handler_names) 50 | 51 | # Override Tornado default ErrorHandler 52 | handlers.append((r".*", APIErrorHandler)) 53 | -------------------------------------------------------------------------------- /schema.sql: -------------------------------------------------------------------------------- 1 | 2 | create database if not exists `d3status`; 3 | 4 | USE `d3status`; 5 | 6 | DROP TABLE IF EXISTS `status`; 7 | CREATE TABLE `status` ( 8 | `id` int(11) NOT NULL AUTO_INCREMENT, 9 | `category` varchar(45) NOT NULL, 10 | `service` varchar(45) NOT NULL, 11 | `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1 - up, 0 -down', 12 | `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 13 | PRIMARY KEY (`id`) 14 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 15 | 16 | DROP TABLE IF EXISTS `subscribers`; 17 | CREATE TABLE `subscribers` ( 18 | `id` int(11) NOT NULL AUTO_INCREMENT, 19 | `token` varchar(100) NOT NULL, 20 | `categorys` varchar(45) NOT NULL COMMENT '''Americas,Europe,Asia''', 21 | `locale` enum('en','zh_CN','zh_TW') NOT NULL DEFAULT 'en', 22 | `status` enum('on','off') NOT NULL DEFAULT 'on', 23 | PRIMARY KEY (`id`), 24 | UNIQUE KEY `token_UNIQUE` (`token`) 25 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; --------------------------------------------------------------------------------