branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>smgrv123/RestAPI_Practice<file_sep>/mainRoutes/auth.js
const express = require("express");
const app = express();
const postAuth = require("../authRoutes/postSignUp");
const getAuth=require('../authRoutes/postLogIn')
app.use("/signup", postAuth);
app.use('/login',getAuth)
module.exports = app;
<file_sep>/PostRoutes/get.js
const express = require("express");
const router = express.Router();
const Post = require("../models/Posts");
router.get("/", async (req, res) => {
try {
// console.log(Post.find(), "working");
const posts = await Post.find();
res.json(posts);
} catch (error) {
console.log('not working');
res.json({ message: error });
}
});
router.get("/:postId", async (req, res) => {
try {
const particular = await Post.findById(req.params.postId);
res.json(particular);
} catch (err) {
res.json({ messagse: err });
}
});
module.exports = router;
<file_sep>/PostRoutes/update.js
const express = require("express");
const router = express.Router();
const Post = require("../models/Posts");
router.patch("/:id", async (req, res) => {
try {
const update = await Post.updateOne(
{ _id: req.params.id },
{ $set: { title: req.body.title } }
);
res.json(update);
} catch (error) {
res.json({ message: error });
}
});
module.exports = router;
<file_sep>/authRoutes/postLogIn.js
const express = require("express");
const router = express.Router();
const auth = require("../models/Auth");
const bcrypt = require("bcrypt");
router.post("/", async (req, res) => {
try {
await auth
.find()
.select("username")
.then((users) => {
users.forEach((docs) => {
if (docs.username === req.body.username) {
bcrypt.compare(
req.body.password,
docs.password,
function (err, result) {
if (!err) {
res.json({ result: result });
}
}
);
}
});
});
} catch (error) {
res.send({ message: error });
}
});
module.exports = router;
<file_sep>/authRoutes/postSignUp.js
const express = require("express");
const router = express.Router();
const auth = require("../models/Auth");
const bcrypt = require("bcrypt");
router.post("/", async (req, res) => {
try {
const Bpassword = await bcrypt.hash(req.body.password, 10);
const authPost = new auth({
username: req.body.username,
password: <PASSWORD>,
});
const sendData = await authPost.save();
res.json(sendData);
} catch (error) {
console.log(error);
res.sendStatus(503);
}
});
module.exports = router; | 44c36664a09ff7e206c85b8d47594f501a38bca0 | [
"JavaScript"
] | 5 | JavaScript | smgrv123/RestAPI_Practice | b4ec94f6104e7776b8538d57af9bf88ef1900a4e | 24bee6c0450a3ebcd444d5ce5f4a1bc1857377e5 |
refs/heads/master | <repo_name>khbuoyrupppiseth7/WebShop<file_sep>/savedirectsalling.php
<?php
include 'header.php';
$autoid = time();
$ProductID = get('txtProductID');
$ProductName = get('txtPrdName');
$ProductCategoryID = get('txtProductCategoryID');
$ProductCode = get('txtProductCode');
$QTY = get('txtQty');
$BuyPrice = get('txtbuyprice');
$SalePrice = get('txtsaleprice');
$sarchprd = get('sarchprd');
$txtDesc = get('txtDesc');
$txtOtherCost = get('txtOtherCost');
/*Create Invoice Customer Sale*/
$InsertToCustomerOrder=$db->query(" INSERT INTO tbl_customerorder (
CustomerOrderID,
BranchID,
InvoiceNo,
CustomerOrderDate,
UserID
)
VALUES
(
'".$autoid."',
'".$U_Brandid."',
'".$autoid."',
'".$date_now."',
'".$U_id."'
)");
$insertCustomerOrderdetail = $db->query("INSERT INTO `tbl_customerorderdetail`(
CustomerOrderDetailID,
BranchID,
CustomerOrderID,
ProductID,
Qty,
SalePrice,
BuyPrice,
perDicount,
AmtDiscount,
LastSalePrice,
Total,
Decription
)
VALUES
(
'".time().'2'."',
'".$U_Brandid."',
'".$autoid."',
'".$ProductID."',
'1',
'".$SalePrice."',
'".$BuyPrice."',
'0',
'0',
'0',
'',
'Powered by 7Technology'
)
");
$deductQty= $db->query("UPDATE tblproductsbranch SET Qty = Qty - 1 , OtherCost = ".$txtOtherCost.", Decription=N'".$txtDesc."' WHERE ProductID = '".$ProductID."' ");
if($InsertToCustomerOrder){
cRedirect('index.php');
}
?><file_sep>/savedirectOtherCost.php
<?php
include 'header.php';
$autoid = time();
$ProductID = get('txtProductID');
$txtOtherCost = get('txtOtherCost');
$txtDesc = get('txtDesc');
/*Create Invoice Customer Sale*/
$InsertToCustomerOrder=$db->query("UPDATE tblproductsbranch SET OtherCost = '".$txtOtherCost."', Decription=N'".$txtDesc."' WHERE ProductID = '".$ProductID."'");
if($InsertToCustomerOrder)
{
cRedirect('index.php');
}
?><file_sep>/WebShopV2/frmRule.php
<?php include 'header.php';?>
<?php
// Add new product to Produtct Tem
if(isset($_POST['btnSaveNew'])){
$cboPrd = $_POST['cboPrd'];
$txtmin = post('txtmin');
$txtmax = post('txtmax');
$txtdaymin = post('txtdaymin');
$txtdaymax = post('txtdaymax');
$txtatm = post('txtatm');
$txtDesc = post('txtDesc');
$insert=$db->query("INSERT INTO tblrule (RuleID, ProductID, Min, Max, DayMin, DayMax, Atm, Description)
VALUES (
'".time()."',
'".$cboPrd."',
'".$txtmin."',
'".$txtmax."',
'".$txtdaymin."',
'".$txtdaymax."',
'".$txtatm."',
'".$txtDesc."');
");
if($insert){
cRedirect('frmRule.php');
}
else{
echo mysql_error();
}
}
?>
<body class="skin-blue">
<!-- header logo: style can be found in header.less -->
<?php include 'nav.php';?>
<!-- Left side column. contains the logo and sidebar -->
<?php include 'menu.php';?>
<!-- Right side column. Contains the navbar and content of the page -->
<aside class="right-side">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<small><a ><i class="fa fa-dashboard"></i> Rule</a></small>
</h1>
<!--<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Branch</li>
</ol>-->
</section>
<!-- Main content -->
<div class="modal fade bs-example-modal-sm" tabindex="0" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Other Cost</h4>
</div>
<div class="modal-body">
<form enctype="multipart/form-data" action="updateRule.php" >
<input type="hidden" name="txtRuleID" id="txtRuleID">
<input type="hidden" name="txtProductID" id="txtProductID">
<div class="form-group">
<label>Products</label>
<input type="text" name="cboPrd" class="form-control currency" disabled id="txtPrdName" />
</div>
<div class="form-group">
<label>Min:</label>
<input type="text" name="txtmin" class="form-control currency" onkeypress="return isNumberKey(event)" required id="txtmin" />
</div>
<div class="form-group">
<label>Max:</label>
<input type="text" name="txtmax" onkeypress="return isNumberKey(event)" required class="form-control currency" id="txtmax" />
</div>
<div class="form-group">
<label>Day Mix:</label>
<input type="text" name="txtdaymin" onkeypress="return isNumberKey(event)" required class="form-control currency" id="txtdaymin" />
</div>
<div class="form-group">
<label>Day Max:</label>
<input type="text" name="txtdaymax" onkeypress="return isNumberKey(event)" required class="form-control currency" id="txtdaymax" />
</div>
<div class="form-group">
<label>ATM:</label>
<input type="text" name="txtatm" onkeypress="return isNumberKey(event)" required class="form-control currency" id="txtatm" />
</div>
<div class="form-group">
<label>Description: </label>
<textarea class="form-control" id="txtDesc" name="txtDesc" placeholder="Enter Descriptiion" rows="3"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save" />
</div>
</form>
</div>
</div>
</div>
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th colspan="9">
<div class="row">
<div class="col-md-3">
<button type="button" class="glyphicon glyphicon-plus btn btn-primary" data-toggle="modal" data-target="#NewUser"></button>
</div>
<form role="search">
<div class="col-md-3 pull-right">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" value="<?php echo $sarchprd; ?>" name="sarchprd" autofocus>
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</div>
</form>
</div>
</th>
</tr>
</thead>
<div id="edit-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body edit-content">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<thead>
<tr>
<th class="col-md-1">No</th>
<th class="col-md-1">Product Name</th>
<th class="col-md-1">Min</th>
<th class="col-md-1">DayMin</th>
<th class="col-md-1">Max</th>
<th class="col-md-1">DayMax</th>
<th class="col-md-1">ATM</th>
<th class="col-md-2">Description</th>
</tr>
</thead>
<tbody>
<!--<tr class="odd gradeX">
<td>Trident</td>
<td>Internet Explorer 4.0</td>
<td>Win 95+</td>
<td class="center">4</td>
<td class="center">4</td>
</tr>
<tr class="even gradeC">
<td>Trident</td>
<td>Internet Explorer 5.0</td>
<td>Win 95+</td>
<td class="center">5</td>
<td class="center">4</td>
</tr>-->
<?php
/*if($sarchprd == "")
{
$select=$db->query("SELECT ProductCategoryID, ProductCategoryName, Decription FROM `tblproductcategory`;");
}
else
{
$select=$db->query("SELECT ProductCategoryID, ProductCategoryName, Decription FROM `tblproductcategory`
WHERE ProductCategoryName LIKE N'%".$sarchprd."%'
");
}*/
$select=$db->query("SELECT tblRule.RuleID,
tblRule.ProductID,
tblproducts.ProductName,
tblRule.Min,
tblRule.Max,
tblRule.DayMin,
tblRule.DayMax,
tblRule.Atm,
tblRule.Description FROM `tblrule`
INNER JOIN tblproducts
ON tblrule.ProductID = tblproducts.ProductID
WHERE tblproducts.isStock = 0");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
$i = 1;
while($row=$db->fetch($select)){
$RuleID = $row->RuleID;
$ProductID = $row->ProductID;
$ProductName = $row->ProductName;
$Min = $row->Min;
$Max = $row->Max;
$DayMin = $row->DayMin;
$DayMax = $row->DayMax;
$Atm = $row->Atm;
$Description = $row->Description;
$x = $i++;
echo'<tr class="even">
<td>'.$i++.'</td>
<td>'.$ProductName.'</td>
<td>'.$Min.'</td>
<td>'.$DayMin.'</td>
<td>'.$Max.'</td>
<td>'.$DayMax.'</td>';
echo "<td><a onclick=\"myOtherCost('".$RuleID."','".$ProductID."','".$ProductName."','".$Min."','".$Max."','".$DayMin."','".$DayMax."','".$Atm."','".$Description."')\">".$Atm."</a></td>";
echo '<td class="center">'.$Description.'</td>
</tr>';
}
}
else
{
echo '<tr class="even">
<td colspan="8"><font size="+1" color="#CC0000"> No Branch Selected.</font></td>
</td>
</tr>';
}
?>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
<script type="text/javascript">
// '".$RuleID."','".$ProductID."','".$ProductName."','".$Min."','".$Max."','".$DayMin."','".$DayMax."','".$Atm."','".$Description."'
var cboPrd = document.getElementById("cboPrd");
var txtPrdName = document.getElementById("txtPrdName");
var txtmin = document.getElementById("txtmin");
var txtmax = document.getElementById("txtmax");
var txtdaymin = document.getElementById("txtdaymin");
var txtdaymax = document.getElementById("txtdaymax");
var txtatm = document.getElementById("txtatm");
var txtDesc = document.getElementById("txtDesc");
var txtRuleID = document.getElementById("txtRuleID");
var txtProductID = document.getElementById("txtProductID");
function myOtherCost(getRuleID,getProductID,getProductName,getMin,getMax,getDayMin,getDayMax,getAtm,getDescription)
{
$('.bs-example-modal-sm').modal('show');
txtRuleID.value = getRuleID;
txtProductID.value = getProductID;
txtPrdName.value = getProductName;
txtmin.value = getMin;
txtmax.value = getMax;
txtdaymin.value = getDayMin;
txtdaymax.value = getDayMax;
txtatm.value = getAtm;
txtDesc.value = getDescription;
}
</script>
<!-- New User -->
<div class="modal fade" id="NewUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="exampleModalLabel">New Category</h4>
</div>
<div class="modal-body">
<form role="form" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Choose Products</label>
<select class="form-control" name="cboPrd">
<?php
$select=$db->query("SELECT ProductID, ProductName FROM `tblproducts` WHERE isStock = 0");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$ProductID = $row->ProductID;
$ProductName = $row->ProductName;
echo'<option value='.$ProductID.'>'.$ProductName.'</option>';
}
}
?>
</select>
</div>
<div class="form-group">
<label>Min:</label>
<input type="number" name="txtmin" onkeypress="return isNumberKey(event)"value="0" min="0" step="0.01" required data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
<div class="form-group">
<label>Max:</label>
<input type="number" name="txtmax" onkeypress="return isNumberKey(event)"value="0" min="0" step="0.01" required data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
<div class="form-group">
<label>Day Mix:</label>
<input type="number" name="txtdaymin" onkeypress="return isNumberKey(event)"value="0" min="0" step="0.01" required data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
<div class="form-group">
<label>Day Max:</label>
<input type="number" name="txtdaymax" onkeypress="return isNumberKey(event)"value="0" min="0" step="0.01" required data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
<div class="form-group">
<label>ATM:</label>
<input type="number" name="txtatm" onkeypress="return isNumberKey(event)"value="0" min="0" step="0.01" required data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
<div class="form-group">
<label>Description:</label>
<textarea name="txtDesc" class="form-control" rows="3" ></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="btnSaveNew" class="btn btn-primary" value="Save" />
</div>
</form>
</div>
</div>
</div>
<!-- End New User -->
<!-- Modal -->
<!-- Check Out -->
<!-- End Check Out -->
</aside><!-- /.right-side -->
</div><!-- ./wrapper -->
<!-- add new calendar event modal -->
<?php include 'footer.php';?><file_sep>/header.php
<?php
session_start();
if(!$_SESSION['user']){
//if(!$_SESSION['user'] || $_SESSION['ComID'] != 1){
header('location:login.php');
}
include('connectionclass/connect.php');
include('connectionclass/function.php');
include('connectionclass/metencrypt.php');
$db=new MyConnection();
$db->connect();
mysql_query("SET NAMES 'UTF8'");
$U_id = $_SESSION['UserID'];
$U_Acc = $_SESSION['user'];
$U_Brandid = $_SESSION['BranchID'];
$U_Branchname = $_SESSION['BranchName'];
$ip=$_SERVER['REMOTE_ADDR'];
$branchid = get('branchid');
//$ip = '192.168.1.1';
$sarchprd = get('sarchprd');
$txtFrom = get('txtFrom');
$txtTo = get('txtTo');
$getProductID = get('ProductID');
$getBuydetailid = get('Buydetailid');
$getProductsName = get('ProductsName');
$getQty = get('Qty');
$getBranchID = get('BranchID');
$getBranchName = get('BranchName');
$getBranchDesc = get('BranchDesc');
$getBuyprice = get('buyprice');
$getothecost = get('othecost');
$getdesc = get('desc');
$getPrdBranchID = get('PrdBranchID');
$getProductName = get('PrdBranchName');
$getPrdBranchPrice = get('PrdBranchPrice');
$getSPrdBrandID = get('SPrdBrandID');
$getSPrdBrandname = get('SPrdBrandname');
$getPrdBranchCode = get('PrdBranchCode');
$getUserID = get('UserID');
// Call Date Location
date_default_timezone_set('Asia/Bangkok');
$date_now = date("Y-m-d H:i:s");
$date = date("Y-m-d");
$datetomorow = date("Y-m-d" ,date(strtotime("+1 day", strtotime($date))));
/*$db->disconnect();
$db->connect();*/
$cboPrdCate1 = get('cboPrdCate1');
$txtprdname1 = get('txtprdname1');
$txtcode1 = get('txtcode1');
$txtbuyprice1 = get('txtbuyprice1');
$txtsaleprice1 = get('txtsaleprice1');
$txtOtherCost = get('txtOtherCost');
$txtDesc = get('txtDesc');
$gettxtuser = get('txtuser');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $date_now; ?></title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<!--<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />-->
<!-- Ionicons -->
<link href="//code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" rel="stylesheet" type="text/css" />
<!-- Morris chart -->
<link href="css/morris/morris.css" rel="stylesheet" type="text/css" />
<!-- jvectormap -->
<link href="css/jvectormap/jquery-jvectormap-1.2.2.css" rel="stylesheet" type="text/css" />
<!-- Date Picker -->
<link href="css/datepicker/datepicker3.css" rel="stylesheet" type="text/css" />
<!-- Daterange picker -->
<link href="css/daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css" />
<!-- bootstrap wysihtml5 - text editor -->
<link href="css/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css" rel="stylesheet" type="text/css" />
<!-- Theme style -->
<link href="css/AdminLTE.css" rel="stylesheet" type="text/css" />
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="css/BeatPicker.min.css"/>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/BeatPicker.min.js"></script>
<script type="text/javascript">
function checkInput(ob) {
var invalidChars = /[^0-9]/gi
if(invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars,"");
}
}
<!--Ex: <input type="text" onKeyUp="checkInput(this)"/>-->
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
<!--Ex: <INPUT onkeypress="return isNumberKey(event)" type="text">-->
</script>
<script type="text/javascript">
function goBack() {
window.history.back()
}
</script>
<script src="js/shorttable.js"></script>
<link rel="stylesheet" type="text/css" href="./jquery.datetimepicker.css"/>
</head><file_sep>/frmAfterSaling.php
<?php include 'header.php';?>
<?php
// Add new product to Produtct Tem
if(isset($_POST['btnAddNewPrd'])){
$txtQty = post('txtQty');
$txtOtherCost = post('txtOtherCost');
$txtDesc = post('txtDesc');
$insert=$db->query("UPDATE tbl_customerorderdetail SET Qty = ".$txtQty.", OtherCost= N'".$txtOtherCost."'
, Decription= N'".$txtDesc."'
WHERE CustomerOrderDetailID = '".$getBuydetailid."'");
$UpdateStockNewBranch=$db->query("UPDATE tblproductsbranch SET Qty = ( Qty + ".$getQty." ) - ".$txtQty.", OtherCost= ".$txtOtherCost."
WHERE ProductID = '".$getProductID."' AND BranchID = '".$U_Brandid."';");
$UpdateStockOldBranch=$db->query("UPDATE tblproductsbranch SET Qty = ( Qty - ".$getQty." ) + ".$txtQty.", OtherCost= ".$txtOtherCost."
WHERE FromBranchID = '".$U_Brandid."' AND FromPrdID = '".$getProductID."' AND BranchID ='".$branchid."';");
if($insert){
cRedirect('invoicesaling.php');
}
}
?>
<body class="skin-blue">
<!-- header logo: style can be found in header.less -->
<?php include 'nav.php';?>
<!-- Left side column. contains the logo and sidebar -->
<?php include 'menu.php';?>
<!-- Right side column. Contains the navbar and content of the page -->
<aside class="right-side">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<small>Control panel <?php echo $getBuydetailid; ?></small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section>
<!-- Main content -->
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Name</th>
<th>QTY</th>
<th>Other Price</th>
<th>Description</th>
<th class="">Action</th>
</tr>
</thead>
<tbody>
<form role="form" method="post">
<?php
echo'<tr class="even">
<td>'.$getProductsName.'</td>
<td><input name="txtQty" value="'.$getQty.'" onKeyUp="checkInput(this)" class="form-control" placeholder="Enter text" /></td>
<td><input name="txtOtherCost" value="'.$getothecost.'" class="form-control" onkeypress="return isNumberKey(event)" placeholder="Enter text" /></td>
<td><input name="txtDesc" value="'.$getdesc.'" class="form-control" placeholder="Enter text" /></td>
<td class="center">
<input type="submit" name="btnAddNewPrd" class="btn btn-primary" value="Save" />
</td>
</tr>';
?>
</form>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
</aside><!-- /.right-side -->
</div><!-- ./wrapper -->
<!-- add new calendar event modal -->
<?php include 'footer.php';?><file_sep>/WebShopV2/index.php
<?php include 'header.php';?>
<?php
// Add new product to Produtct Tem
if(isset($_POST['btnAddNewPrd'])){
$txtprdname = $_POST['txtprdname'];
$txtcode = post('txtcode');
$txtqty = post('txtqty');
$ProductCategoryID = post('cboPrdCate');
$txtbuyprice = post('txtbuyprice');
$txtsaleprice = post('txtsaleprice');
$cboBranch = post('cboBranch');
$isStock = (isset($_POST['ckisStock'])) ? 1 : 0;
// Check if Products Dupplicate.
$CheckPrd = $db->query("SELECT `tblproductsbranch`.BranchID, `tblproductsbranch`.ProductID, tblproducts.ProductName
FROM `tblproductsbranch`
INNER JOIN tblproducts
ON tblproductsbranch.ProductID = tblproducts.ProductID
WHERE BranchID = '".$U_Brandid."' AND ProductName = '".$txtprdname."'
");
$rowCheckPrd=$db->dbCountRows($CheckPrd);
if($rowCheckPrd>0){
$row=$db->fetch($CheckPrd);
$ProductID = $row->ProductID;
$ProductName = $row->ProductName;
$insert=$db->query("INSERT INTO tblprdtem (
IP
, ProductID
, ProductName
, ProductCategoryID
, ProductCode
, QTY
, BuyPrice
, SalePrice
,BranchID
,isStock
)
VALUES(
'".$ip."',
'".$ProductID."',
N'".$ProductName."',
N'".sql_quote($ProductCategoryID)."',
N'".sql_quote($txtcode)."',
N'".sql_quote($txtqty)."',
N'".sql_quote($txtbuyprice)."',
N'".sql_quote($txtsaleprice)."',
'".$U_Brandid."',
'".$isStock."'
);
");
}
else
{
$insert=$db->query("INSERT INTO tblprdtem (
IP
, ProductID
, ProductName
, ProductCategoryID
, ProductCode
, QTY
, BuyPrice
, SalePrice
, PrdCopied
,BranchID
,isStock
)
VALUES(
'".$ip."',
'".time()."',
N'".sql_quote($txtprdname)."',
N'".sql_quote($ProductCategoryID)."',
N'".sql_quote($txtcode)."',
N'".sql_quote($txtqty)."',
N'".sql_quote($txtbuyprice)."',
N'".sql_quote($txtsaleprice)."',
'1',
'".$U_Brandid."',
'".$isStock."'
);
");
}
/*
$insert=$db->query("INSERT INTO tblprdtem (
IP
, ProductID
, ProductName
, ProductCategoryID
, ProductCode
, QTY
, BuyPrice
, SalePrice
, PrdCopied,
BranchID
)
VALUES(
'".$ip."',
'".time()."',
N'".sql_quote($txtprdname)."',
N'".sql_quote($ProductCategoryID)."',
N'".sql_quote($txtcode)."',
N'".sql_quote($txtqty)."',
N'".sql_quote($txtbuyprice)."',
N'".sql_quote($txtsaleprice)."',
'1',
'".$cboBranch."'
);
");*/
/*if($insert){
cRedirect('index.php');
}*/
$error = "Error Internet Connection!";
}
if(isset($_POST['btnCheckout'])){
$cboBranch = post('cboBranch');
$buyid = time();
$InsertToTableBuy= $db->query("INSERT INTO tblproducts_buy (BuyID, BuyDate, UserID, Decription)
VALUES('".$buyid."','".$date_now."','".$U_id."','');");
$InsertToTableBuyDetail = $db->query("SELECT ProductID, QTY, BuyPrice, BranchID, SalePrice FROM tblprdtem ");
$rowselect=$db->dbCountRows($InsertToTableBuyDetail);
if($rowselect>0){
$x = 1;
while($row=$db->fetch($InsertToTableBuyDetail)){
$ProductID = $row->ProductID;
$QTY = $row->QTY;
$BuyPrice = $row->BuyPrice;
$BranchID = $row->BranchID;
$SalePrice = $row->SalePrice;
$sfrombranch = $db->query("SELECT ProductID, BranchID FROM `tblproductsbranch` WHERE ProductID = '".$ProductID."' AND BranchID = '".$BranchID."'");
$cfrombranch=$db->dbCountRows($sfrombranch);
if($cfrombranch>0){
$row=$db->fetch($sfrombranch);
/*Update Qty of ProductsBranch if products already Exit*/
$updateprdqty = $db->query("UPDATE `tblproductsbranch` SET
BuyPrice = (SELECT BuyPrice FROM tblprdtem WHERE ProductID = '".$ProductID."' ) ,
SalePrice = (SELECT SalePrice FROM tblprdtem WHERE ProductID = '".$ProductID."' ) ,
Qty = Qty + (SELECT Qty FROM tblprdtem WHERE ProductID = '".$ProductID."' )
WHERE ProductID = '".$ProductID."'
");
/*Insert to tblproducts_buydetail*/
$newinsert = $db->query("INSERT INTO tblproducts_buydetail
( BuyDetailID,
BuyID,
UserID,
ProductID,
Qty,
BuyPrice,
Decription )
VALUES
(
'".time().$x++ ."',
'".$buyid."',
'".$U_id."',
'".$ProductID."',
'".$QTY."',
'".$BuyPrice."',
''
)");
}
else
{
$insertfor_old_prd=$db->query("INSERT INTO tblproductsbranch (ProductID, BranchID, BuyPrice, OtherCost, SalePrice, Qty)
VALUES (".$ProductID.", ".$U_Brandid.", BuyPrice,'".$BuyPrice."', ".$SalePrice.", ".$QTY.")");
/*Insert to tblproducts_buydetail*/
$newinsert = $db->query("INSERT INTO tblproducts_buydetail
( BuyDetailID,
BuyID,
UserID,
ProductID,
Qty,
BuyPrice,
Decription )
VALUES
(
'".time().$x++ ."',
'".$buyid."',
'".$U_id."',
'".$ProductID."',
'".$QTY."',
'".$BuyPrice."',
''
)");
}
}
}
/*Move from tableprdtem to products*/
$copy=$db->query("INSERT INTO tblproducts (ProductID, ProductName, ProductCategoryID, ProductCode,QTY, BuyPrice, SalePrice, isStock)
SELECT ProductID, ProductName, ProductCategoryID, ProductCode, QTY, BuyPrice, SalePrice, isStock
FROM tblprdtem WHERE tblprdtem.PrdCopied = '1' ");
/*Move from tableprdtem to productsBranch*/
$copy1=$db->query("INSERT INTO tblproductsbranch (ProductID, BranchID, BuyPrice, OtherCost, SalePrice, Qty, QtyInstock, TotalBuyPrice, isStock)
SELECT ProductID, ".$U_Brandid.", BuyPrice,'0', SalePrice, Qty, '0', Qty, isStock
FROM tblprdtem WHERE tblprdtem.PrdCopied = '1' ");
if($copy){
$delete=$db->query("DELETE FROM `tblprdtem` WHERE IP = '".$ip."'");
$delete=$db->query("DELETE FROM `tblproductsbranch` WHERE BuyPrice IS NULL");
//cRedirect('index.php');
}
}
?>
<body class="skin-blue">
<!-- header logo: style can be found in header.less -->
<?php include 'nav.php';?>
<!-- Left side column. contains the logo and sidebar -->
<?php include 'menu.php';?>
<!-- Right side column. Contains the navbar and content of the page -->
<aside class="right-side">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<small><i class="fa fa-dashboard"></i> Panel Buying ( Buy to Branch " <a ><?php echo $U_Branchname; ?> </a>")</small>
</h1>
<!--<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>-->
</section>
<!-- Main content -->
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th colspan="7">
<div class="row">
<div class="col-md-3">
<button type="button" class="glyphicon glyphicon-plus btn btn-primary" data-toggle="modal" data-target="#NewUser"></button>
</div>
<div class="col-md-6 pull-center" >
<button type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-shopping-cart" aria-hidden="true">
<?php
$select=$db->query("SELECT COUNT(ProductID) AS TotalOrder FROM `tblprdtem` WHERE IP = '".$ip."';");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$TotalOrder = $row->TotalOrder;
echo'QTY Products: ' . $TotalOrder;
}
}
?>
</span>
</button>
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
Total All Cart
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<form method="post" enctype="multipart/form-data">
<?php
$select=$db->query("SELECT ProductID , ProductName, QTY FROM `tblprdtem` WHERE IP = '".$ip."' Order by ProductName;");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$ProductID = $row->ProductID;
$ProductName = $row->ProductName;
$QTY = $row->QTY;
echo'<li role="presentation"><a role="menuitem" tabindex="-1"
href="frmBuyPrd-Editeachone.php?ProductID='.$ProductID.'">'.$ProductName.' ( '.$QTY.' ) </a> </li>';
}
echo '</ul>';
//echo '<button type="button" class="glyphicon glyphicon-random btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-sm"> CheckOut</button>';
echo '<button type="submit" name="btnCheckout" class="glyphicon glyphicon-random btn btn-primary" > Save</button>';
echo '</form>';
}
else
{
echo '</ul>';
echo '<button type="button" class="glyphicon glyphicon-random btn btn-default"> Save</button>';
}
?>
</div>
<!-- Check Out Form -->
<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<form method="post" enctype="multipart/form-data">
<!--<div class="form-group">
<label>Choose Branch</label>
<select class="form-control" name="cboBranch">
<?php
/*$select=$db->query("SELECT BranchID, BranchName FROM `tblbranch`;");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$BranchID = $row->BranchID;
$BranchName = $row->BranchName;
echo'<option value='.$BranchID.'>'.$BranchName.'</option>';
}
}*/
?>
</select>
</div>-->
<div class="checkbox">
<label>
<input type="checkbox" checked> Check here to follow us.
</label>
<input type="submit" name="btnCheckout" cclass="glyphicon glyphicon-random btn btn-primary" value="Checkout" />
</div>
</form>
</div>
</div>
</div>
<!-- Check Out Form -->
<form role="search">
<div class="col-md-3 pull-right">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" value="<?php echo $sarchprd; ?>" name="sarchprd" autofocus>
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</div>
</form>
</div>
</th>
</tr>
</thead>
<thead>
<tr>
<th>Category <?php echo $sarchprd ?></th>
<th>Name </th>
<th>Code</th>
<th>BuyPrice</th>
<th>SalePrice</th>
<th>Order Action</th>
</tr>
</thead>
<tbody>
<!--<tr class="odd gradeX">
<td>Trident</td>
<td>Internet Explorer 4.0</td>
<td>Win 95+</td>
<td class="center">4</td>
<td class="center">4</td>
</tr>
<tr class="even gradeC">
<td>Trident</td>
<td>Internet Explorer 5.0</td>
<td>Win 95+</td>
<td class="center">5</td>
<td class="center">4</td>
</tr>-->
<?php
$select=$db->query("CALL spSearchPrdBuy('".$sarchprd."')");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
$i = 1;
while($row=$db->fetch($select)){
$ProductID = $row->ProductID;
$ProductCategoryID = $row->ProductCategoryID;
$ProductName = $row->ProductName;
$ProductCategoryName = $row->ProductCategoryName;
$ProductCode = $row->ProductCode;
$Qty = $row->Qty;
$BuyPrice = $row->BuyPrice;
$SalePrice = $row->SalePrice;
$x = $i++;
echo'<tr class="even">
<td>'.$ProductCategoryName.'</td>
<td>'.$ProductName.'</td>
<td>'.$ProductCode.'</td>
<td class="center"> $'.$BuyPrice.'</td>
<td class="center"> $'.$SalePrice.'</td>
<td class="center">
<a href="clickBuyPrd.php?ProductID='.$ProductID.'
&ProductName='.$ProductName.'
&ProductCategoryID='.$ProductCategoryID.'
&ProductCode='.$ProductCode.'
&QTY= 1
&BuyPrice='.$BuyPrice.'
&SalePrice='.$SalePrice.'
&sarchprd='.$sarchprd.'
">
<button type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
</button></a>
</td>
</tr>';
}
}
else
{
echo '<tr class="even">
<td colspan="8"><font size="+1" color="#CC0000"> No Products Selected.</font></td>
</td>
</tr>';
}
$db->disconnect();
$db->connect();
?>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
<!-- New User -->
<div class="modal fade" id="NewUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="exampleModalLabel">New Product</h4>
</div>
<div class="modal-body">
<form role="form" method="post">
<div class="form-group">
<label>Choose Category</label>
<select class="form-control" name="cboPrdCate">
<?php
$select=$db->query("SELECT ProductCategoryID, ProductCategoryName FROM `tblproductcategory`;");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$ProductCategoryID = $row->ProductCategoryID;
$ProductCategoryName = $row->ProductCategoryName;
echo'<option value='.$ProductCategoryID.'>'.$ProductCategoryName.'</option>';
}
}
?>
</select>
</div>
<div class="form-group">
<label>Product Name: </label>
<input name="txtprdname" class="form-control" placeholder="Enter text" required autofocus />
</div>
<div class="form-group">
<label>Products Code:</label>
<input name="txtcode" class="form-control" placeholder="Enter text" />
</div>
<div class="form-group">
<label>Products QTY:</label>
<input name="txtqty" onKeyUp="checkInput(this)" class="form-control" value="1" placeholder="Enter text" required />
</div>
<div class="form-group">
<label>Buy Price:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="number" name="txtbuyprice" onkeypress="return isNumberKey(event)"value="0" min="0" step="0.01" required data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
</div>
<div class="form-group">
<label>Sale Price:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="number" value="0" name="txtsaleprice" onKeyPress="return isNumberKey(event)" min="0" required step="0.01" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
</div>
<div class="form-group">
<label>
<input type="checkbox" name="ckisStock" checked> isStock
</label>
</div>
<!--<div class="form-group">
<label>User Limit </label>
<label class="radio-inline">
<input type="radio" name="rdstatus" id="optionsRadiosInline1" value="1" checked>Active
</label>
<label class="radio-inline">
<input type="radio" name="rdstatus" id="optionsRadiosInline2" value="0">Suspend
</label>
</div>
-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="btnAddNewPrd" class="btn btn-primary" value="Save" />
</div>
</form>
</div>
</div>
</div>
<!-- End New User -->
<!-- Check Out -->
<!-- End Check Out -->
</aside><!-- /.right-side -->
</div><!-- ./wrapper -->
<!-- add new calendar event modal -->
<?php include 'footer.php';?><file_sep>/invoicebuying.php
<?php include 'header.php';?>
<?php
// Add new product to Produtct Tem
if(isset($_POST['btnSearch'])){
$txtprdname = $_POST['txtprdname'];
$txtcode = post('txtcode');
$txtqty = post('txtqty');
$ProductCategoryID = post('cboPrdCate');
$txtbuyprice = post('txtbuyprice');
$txtsaleprice = post('txtsaleprice');
$cboBranch = post('cboBranch');
$insert=$db->query("INSERT INTO tblprdtem (
IP
, ProductID
, ProductName
, ProductCategoryID
, ProductCode
, QTY
, BuyPrice
, SalePrice
, PrdCopied)
VALUES(
'".$ip."',
'".time()."',
N'".sql_quote($txtprdname)."',
N'".sql_quote($ProductCategoryID)."',
N'".sql_quote($txtcode)."',
N'".sql_quote($txtqty)."',
N'".sql_quote($txtbuyprice)."',
N'".sql_quote($txtsaleprice)."',
'1'
);
");
if($insert){
cRedirect('index.php');
}
$error = "Error Internet Connection!";
}
?>
<body class="skin-blue">
<!-- header logo: style can be found in header.less -->
<?php include 'nav.php';?>
<!-- Left side column. contains the logo and sidebar -->
<?php include 'menu.php';?>
<!-- Right side column. Contains the navbar and content of the page -->
<aside class="right-side">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<div class="row">
<form class="form-inline">
<div class="col-md-6 pull-right">
<div class="form-group">
<input type="text" class="form-control some_class" <?php
if ($txtFrom == "")
{
echo 'value="'.$date_now.'"';
}
else
{
echo 'value="'.$txtFrom.'"';
}
?> name="txtFrom" id="some_class_1"/>
</div>
<div class="form-group">
<input type="text" class="form-control some_class" <?php
if ($txtFrom == "")
{
echo 'value="'.$date_now.'"';
}
else
{
echo 'value="'.$txtTo.'"';
}
?> name="txtTo" id="some_class_1"/>
</div>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search Products" value="<?php echo $sarchprd; ?>" name="sarchprd" autofocus>
<div class="input-group-btn">
<button name="btnSearch" value="true" class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</h1>
<!--<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>-->
</section>
<!-- Main content -->
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover sortable" id="dataTables-example">
<thead>
<tr>
<th class="col-md-2 text-center">Date</th>
<th class="text-center">Name</th>
<th class="text-center">Code</th>
<th class="col-md-2 text-center">Branch</th>
<th class="col-md-1 text-center">QTY</th>
<th class="col-md-1 text-center">Price</th>
<th class="col-md-1 text-center">Other Price</th>
<th class="text-center">Order</th>
</tr>
</thead>
<tbody>
<!--<tr class="odd gradeX">
<td>Trident</td>
<td>Internet Explorer 4.0</td>
<td>Win 95+</td>
<td class="center">4</td>
<td class="center">4</td>
</tr>
<tr class="even gradeC">
<td>Trident</td>
<td>Internet Explorer 5.0</td>
<td>Win 95+</td>
<td class="center">5</td>
<td class="center">4</td>
</tr>-->
<?php
if($sarchprd != "")
{
$select=$db->query("SELECT
tblproducts_buydetail.BuyDetailID,
tblproducts_buydetail.ProductID,
tblproducts.ProductName,
tblproducts.ProductCode,
tblbranch.BranchName,
tblproducts_buydetail.Qty,
tblproducts_buydetail.OtherCost,
tblproducts_buydetail.BuyPrice,
DATE_FORMAT(tblproducts_buy.BuyDate,'%d %b %Y %h:%m:%s') as BuyingDate,
TIMESTAMPDIFF(MINUTE,tblproducts_buy.BuyDate,NOW()) AS CalcMin,
tblbranch.BranchName
FROM `tblproducts_buy`
INNER JOIN tblproducts_buydetail
ON tblproducts_buy.BuyID = tblproducts_buydetail.BuyID
INNER JOIN tblproducts
ON tblproducts.ProductID = tblproducts_buydetail.ProductID
INNER JOIN tblproductsbranch
ON tblproducts_buydetail.ProductID = tblproductsbranch.ProductID
INNER JOIN tblbranch
ON tblproductsbranch.BranchID = tblbranch.BranchID
WHERE ( tblproducts.ProductName LIKE '%".$sarchprd."%'
OR tblproducts.ProductCode LIKE '%".$sarchprd."%' )
AND ( tblproducts_buy.BuyDate BETWEEN '".$txtFrom."' AND '".$txtTo."')
And tblproducts_buy.UserID = '".$U_id."'
ORDER By tblproducts_buy.BuyDate DESC
;
");
}
else
{
$select=$db->query("SELECT
tblproducts_buydetail.BuyDetailID,
tblproducts_buydetail.ProductID,
tblproducts.ProductName,
tblproducts.ProductCode,
tblbranch.BranchName,
tblproducts_buydetail.Qty,
tblproducts_buydetail.OtherCost,
tblproducts_buydetail.BuyPrice,
DATE_FORMAT(tblproducts_buy.BuyDate,'%d %b %Y %h:%m:%s') as BuyingDate,
TIMESTAMPDIFF(MINUTE,tblproducts_buy.BuyDate,NOW()) AS CalcMin,
tblbranch.BranchName
FROM `tblproducts_buy`
INNER JOIN tblproducts_buydetail
ON tblproducts_buy.BuyID = tblproducts_buydetail.BuyID
INNER JOIN tblproducts
ON tblproducts.ProductID = tblproducts_buydetail.ProductID
INNER JOIN tblproductsbranch
ON tblproducts_buydetail.ProductID = tblproductsbranch.ProductID
INNER JOIN tblbranch
ON tblproductsbranch.BranchID = tblbranch.BranchID
WHERE ( tblproducts.ProductName LIKE '%%'
OR tblproducts.ProductCode LIKE '%%' )
AND ( tblproducts_buy.BuyDate BETWEEN '".$txtFrom."' AND '".$txtTo."')
And tblproducts_buy.UserID = '".$U_id."'
AND tblbranch.BranchID = '".$U_Brandid."'
ORDER By tblproducts_buy.BuyDate DESC
;");
}
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
$i = 1;
while($row=$db->fetch($select)){
$BuyDetailID = $row->BuyDetailID;
$ProductID = $row->ProductID;
$ProductName = $row->ProductName;
$BranchName = $row->BranchName;
$Qty = $row->Qty;
$OtherCost = $row->OtherCost;
$BuyPrice = $row->BuyPrice;
$CalcMin = $row->CalcMin;
$ProductCode = $row->ProductCode;
$BuyingDate = date("F d, Y H:i:s",strtotime($row->BuyingDate));
//$BuyingDate = $row->BuyingDate;
if($CalcMin <= 120)
echo'<tr class="even">
<td class="col-md-2">'.$BuyingDate.'</td>
<td>'.$ProductName.'</td>
<td>'.$ProductCode.'</td>
<td class="col-md-1 text-left">'.$BranchName.'</td>
<td class="col-md-1 text-center">'.$Qty.'</td>
<td class="col-md-1 text-right">$ '.$BuyPrice.'</td>
<td class="col-md-1 text-right">$ '.$OtherCost.'</td>
<td class="col-md-1 text-center"><a href="frmAfterBuying.php?Buydetailid='.$BuyDetailID.'&ProductID='.$ProductID.'&ProductsName='.$ProductName.'&Qty='.$Qty.'&buyprice='.$BuyPrice.'&othecost='.$OtherCost.'"><button class="btn btn-default" type="submit" ><i class="glyphicon glyphicon glyphicon-pencil"></i></button> </a></td>
</tr>';
else
{
echo'<tr class="even">
<td class="col-md-2">'.$BuyingDate.'</td>
<td>'.$ProductName.'</td>
<td>'.$ProductCode.'</td>
<td class="col-md-1 text-left">'.$BranchName.'</td>
<td class="col-md-1 text-center">'.$Qty.'</td>
<td class="col-md-1 text-right">$ '.$BuyPrice.'</td>
<td class="col-md-1 text-right">$ '.$OtherCost.'</td>
<td class="col-md-1 text-center"></td>
</tr>';
}
}
}
else
{
echo '<tr class="even">
<td colspan="8"><font size="+1" color="#CC0000"> No Products Selected.</font></td>
</td>
</tr>';
}
?>
</tbody >
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
<!-- New User -->
<div class="modal fade" id="NewUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="exampleModalLabel">New Product</h4>
</div>
<div class="modal-body">
<form role="form" method="post">
<!--<div class="form-group">
<label>Choose Branch</label>
<select class="form-control" name="cboBranch">
<?php
/* $select=$db->query("SELECT BranchID, BranchName FROM `tblbranch`;");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$BranchID = $row->BranchID;
$BranchName = $row->BranchName;
echo'<option value='.$BranchID.'>'.$BranchName.'</option>';
}
}*/
?>
</select>
</div>-->
<div class="form-group">
<label>Choose Category</label>
<select class="form-control" name="cboPrdCate">
<?php
$select=$db->query("SELECT ProductCategoryID, ProductCategoryName FROM `tblproductcategory`;");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$ProductCategoryID = $row->ProductCategoryID;
$ProductCategoryName = $row->ProductCategoryName;
echo'<option value='.$ProductCategoryID.'>'.$ProductCategoryName.'</option>';
}
}
?>
</select>
</div>
<div class="form-group">
<label>Product Name: </label>
<input name="txtprdname" class="form-control" placeholder="Enter text" required />
</div>
<div class="form-group">
<label>Products Code:</label>
<input name="txtcode" class="form-control" placeholder="Enter text" />
</div>
<div class="form-group">
<label>Products QTY:</label>
<input name="txtqty" class="form-control" placeholder="Enter text" />
</div>
<div class="form-group">
<label>Buy Price:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="number" name="txtbuyprice" value="1" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
</div>
<div class="form-group">
<label>Sale Price:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="number" value="1" name="txtsaleprice" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
</div>
<!--<div class="form-group">
<label>User Limit </label>
<label class="radio-inline">
<input type="radio" name="rdstatus" id="optionsRadiosInline1" value="1" checked>Active
</label>
<label class="radio-inline">
<input type="radio" name="rdstatus" id="optionsRadiosInline2" value="0">Suspend
</label>
</div>
-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="btnAddNewPrd" class="btn btn-primary" value="Save" />
</div>
</form>
</div>
</div>
</div>
<!-- End New User -->
<!-- Check Out -->
<!-- End Check Out -->
</aside><!-- /.right-side -->
</div><!-- ./wrapper -->
<!-- add new calendar event modal -->
<?php include 'footer.php';?><file_sep>/invoicesalingofuser.php
<?php include 'header.php';?>
<?php
// Add new product to Produtct Tem
if(isset($_POST['btnAddNewPrd'])){
$txtprdname = $_POST['txtprdname'];
$txtcode = post('txtcode');
$txtqty = post('txtqty');
$ProductCategoryID = post('cboPrdCate');
$txtbuyprice = post('txtbuyprice');
$txtsaleprice = post('txtsaleprice');
$cboBranch = post('cboBranch');
$insert=$db->query("INSERT INTO tblprdtem (
IP
, ProductID
, ProductName
, ProductCategoryID
, ProductCode
, QTY
, BuyPrice
, SalePrice
, PrdCopied)
VALUES(
'".$ip."',
'".time()."',
N'".sql_quote($txtprdname)."',
N'".sql_quote($ProductCategoryID)."',
N'".sql_quote($txtcode)."',
N'".sql_quote($txtqty)."',
N'".sql_quote($txtbuyprice)."',
N'".sql_quote($txtsaleprice)."',
'1'
);
");
if($insert){
cRedirect('index.php');
}
$error = "Error Internet Connection!";
}
if(isset($_POST['btnCheckout'])){
$cboBranch = post('cboBranch');
/*Move from tableprdtem to products*/
$copy=$db->query("INSERT INTO tblproducts (ProductID, ProductName, ProductCategoryID, ProductCode,QTY, BuyPrice, SalePrice)
SELECT ProductID, ProductName, ProductCategoryID, ProductCode, QTY, BuyPrice, SalePrice
FROM tblprdtem WHERE tblprdtem.PrdCopied = '1' ");
/*Move from tableprdtem to productsBranch*/
$copy=$db->query("INSERT INTO tblproductsbranch (ProductID, BranchID, BuyPrice, OtherCost, SalePrice, Qty, QtyInstock, TotalBuyPrice)
SELECT ProductID, '".$cboBranch."', BuyPrice,'0', SalePrice, Qty, '0', BuyPrice * Qty
FROM tblprdtem WHERE tblprdtem.PrdCopied = '1' ");
$buyid = time();
$InsertToTableBuy= $db->query("INSERT INTO tblproducts_buy (BuyID, BuyDate, UserID, Decription)
VALUES('".$buyid."',Now(),'".$U_id."','');");
$InsertToTableBuyDetail = $db->query("SELECT ProductID, QTY, BuyPrice, SalePrice FROM tblprdtem ");
$rowselect=$db->dbCountRows($InsertToTableBuyDetail);
if($rowselect>0){
while($row=$db->fetch($InsertToTableBuyDetail)){
$ProductID = $row->ProductID;
$QTY = $row->QTY;
$BuyPrice = $row->BuyPrice;
/*Insert to tblproducts_buydetail*/
$newinsert = $db->query("INSERT INTO tblproducts_buydetail
( BuyDetailID,
BuyID,
UserID,
ProductID,
Qty,
BuyPrice,
Decription )
VALUES
(
'".time()."',
'".$buyid."',
'".$U_id."',
'".$ProductID."',
'".$QTY."',
'".$BuyPrice."',
'Hello, World.'
)");
/*Update Qty of Products*/
$updateproductsqty = $db->query("UPDATE tblproducts
SET Qty = Qty + (SELECT Qty FROM tblprdtem WHERE ProductID = '".$ProductID."' )
WHERE ProductID = '".$ProductID."'
");
/*Update Qty of ProductsBranch*/
$updateproductsqty = $db->query("UPDATE `tblproductsbranch`SET
BuyPrice = (SELECT BuyPrice FROM tblprdtem WHERE ProductID = '".$ProductID."' ) ,
OtherCost = '0',
SalePrice = (SELECT SalePrice FROM tblprdtem WHERE ProductID = '".$ProductID."' ) ,
Qty = Qty + (SELECT Qty FROM tblprdtem WHERE ProductID = '".$ProductID."' ) ,
QtyInstock = (SELECT Qty FROM tblproducts WHERE ProductID = '".$ProductID."' ) ,
TotalBuyPrice = TotalBuyPrice + (SELECT Qty * BuyPrice FROM tblprdtem WHERE ProductID = '".$ProductID."' )
WHERE ProductID = '".$ProductID."'
");
}
}
if($copy){
$delete=$db->query("DELETE FROM `tblprdtem` WHERE IP = '".$ip."'");
cRedirect('index.php');
}
}
?>
<body class="skin-blue">
<!-- header logo: style can be found in header.less -->
<?php include 'nav.php';?>
<!-- Left side column. contains the logo and sidebar -->
<?php include 'menu.php';?>
<!-- Right side column. Contains the navbar and content of the page -->
<aside class="right-side">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<div class="row">
<form class="form-inline">
<div class="col-md-3 pull-left">
<div class="form-group">
<select class="form-control" name="UserID" >
<?php
if($U_id == 1)
{
$select=$db->query("SELECT UserID, BranchID, UserName FROM tblusers ORDER BY UserName");
}
else
{
$select=$db->query("SELECT UserID, BranchID, UserName FROM tblusers WHERE UserID != 1 ORDER BY UserName");
}
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$UserID = $row->UserID;
$UserName = $row->UserName;
if($getUserID == $UserID)
{
echo'<option value='.$UserID.' selected>'.$UserName.'</option>';
}
else
{
echo'<option value='.$UserID.'>'.$UserName.'</option>';
}
}
}
?>
</select>
</div>
</div>
<div class="col-md-7 pull-right">
<div class="form-group">
<input type="text" class="form-control some_class" <?php
if ($txtFrom == "")
{
echo 'value="'.$date_now.'"';
}
else
{
echo 'value="'.$txtFrom.'"';
}
?> name="txtFrom" id="some_class_1"/>
</div>
<div class="form-group">
<input type="text" class="form-control some_class" <?php
if ($txtFrom == "")
{
echo 'value="'.$date_now.'"';
}
else
{
echo 'value="'.$txtTo.'"';
}
?> name="txtTo" id="some_class_1"/>
</div>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search Products" value="<?php echo $sarchprd; ?>" name="sarchprd" autofocus>
<div class="input-group-btn">
<button name="btnSearch" value="true" class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</h1>
</section>
<!-- Main content -->
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover sortable" id="dataTables-example">
<?php
if($_SESSION['Level']=='1'){
echo ' <thead>
<tr>
<th class="col-md-2 text-center">Date</th>
<th class="text-center">Name</th>
<th class="text-center">Sale to Branch</th>
<th class="col-md-1 text-center">QTY</th>
<th class="col-md-1 text-center">Sale Price</th>
<th class="col-md-1 text-center">Buy Price</th>
<th class="col-md-1 text-center">Total Salling</th>
<th class="col-md-1 text-center">Total Buying</th>
<th class="col-md-1 text-center">Other Price</th>
<th class="col-md-1 text-center">Description</th>
<th class="col-md-1 text-center">INCOME</th>
</tr>
</thead>
<tbody>';
$select=$db->query("SELECT tbl_customerorder.CustomerOrderID,
tbl_customerorderdetail.CustomerOrderDetailID,
tbl_customerorder.InvoiceNo,
tbl_customerorder.CustomerOrderDate,
tblproducts.ProductID,
tbl_customerorderdetail.BranchID,
tblproducts.ProductName,
COALESCE((tbl_customerorderdetail.OtherCost),0) AS OtherCost,
COALESCE((tbl_customerorderdetail.BuyPrice),0) AS BuyPrice,
COALESCE((tbl_customerorderdetail.SalePrice),0) AS SalePrice,
COALESCE((tbl_customerorderdetail.Qty),0) AS Qty,
COALESCE((tbl_customerorderdetail.BuyPrice),0) * COALESCE((tbl_customerorderdetail.Qty),0) AS Total_Buying,
COALESCE((tbl_customerorderdetail.SalePrice),0) * COALESCE((tbl_customerorderdetail.Qty),0) AS Total_Salling,
DATE_FORMAT( tbl_customerorder.CustomerOrderDate,'%d %b %Y %h:%m:%s') as SaleDate,
TIMESTAMPDIFF(MINUTE,tbl_customerorder.CustomerOrderDate,NOW()) AS CalcMin,
tbl_customerorder.UserID,
tbl_customerorder.SelltoOtherBranch,
tblbranch.BranchName,
tbl_customerorderdetail.Decription
FROM tbl_customerorder
INNER JOIN tbl_customerorderdetail
ON tbl_customerorder.CustomerOrderID = tbl_customerorderdetail.CustomerOrderID
INNER JOIN tblproducts
ON tbl_customerorderdetail.ProductID = tblproducts.ProductID
LEFT JOIN tblbranch
ON tblbranch.BranchID = tbl_customerorder.SelltoOtherBranch
WHERE (tblproducts.ProductName LIKE '%".$sarchprd."%' OR tblproducts.ProductCode LIKE '%".$sarchprd."%' )
AND (tbl_customerorder.CustomerOrderDate BETWEEN '".$txtFrom." AND '".$txtTo.")
AND tbl_customerorder.UserID = '".$getUserID."'
ORDER BY tbl_customerorder.CustomerOrderDate DESC");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
$i = 1;
while($row=$db->fetch($select)){
$CustomerOrderDetailID = $row->CustomerOrderDetailID;
$InvoiceNo = $row->InvoiceNo;
$CustomerOrderDate = $row->CustomerOrderDate;
$ProductID = $row->ProductID;
$ProductName = $row->ProductName;
$Qty = $row->Qty;
$BuyPrice = round($row->BuyPrice,2);
$SalePrice = round($row->SalePrice,2);
$SaleDate = $row->SaleDate;
$CalcMin = $row->CalcMin;
$OtherCost = round($row->OtherCost,2);
$BranchName = $row->BranchName;
$Total_Buying = round($row->Total_Buying,2);
$Total_Salling = round($row->Total_Salling,2);
$Income = round($Total_Salling - ($Total_Buying + $OtherCost),2) ;
$BranchID = $row->BranchID;
$Decription = $row->Decription;
if($CalcMin <=120){
echo'<tr class="even">
<td>'.$SaleDate.'</td>
<td>'.$ProductName.'</td>
<td>'.$BranchName.'</td>
<td class="text-center">'.$Qty.'</td>
<td class="text-right">$ '.$SalePrice.'</td>
<td class="text-right">$ '.$BuyPrice.'</td>
<td class="text-right">$ '.$Total_Salling.'</td>
<td class="text-right">$ '.$Total_Buying.'</td>
<td class="text-right">$ '.$OtherCost.'</td>
<td class="text-right"> '.$Decription.'</td>
<td class="text-right"> $ <a href="frmAfterSaling.php?Buydetailid='.$CustomerOrderDetailID.'&ProductID='.$ProductID.'&branchid='.$BranchID.'&ProductsName='.$ProductName.'&Qty='.$Qty.'&othecost='.$OtherCost.'&desc='.$Decription.'">'.$Income.' </a></td>
</tr>';
}
else
{
echo'<tr class="even">
<td>'.$SaleDate.'</td>
<td>'.$ProductName.'</td>
<td>'.$BranchName.'</td>
<td class="text-center">'.$Qty.'</td>
<td class="text-right">$ '.$SalePrice.'</td>
<td class="text-right">$ '.$BuyPrice.'</td>
<td class="text-right">$ '.$Total_Salling.'</td>
<td class="text-right">$ '.$Total_Buying.'</td>
<td class="text-right">$ '.$OtherCost.'</td>
<td class="text-right"> '.$Decription.'</td>
<td class="text-right">$ '.$Income.'</td>
</tr>';
}
}
$select1=$db->query("SELECT
COALESCE((tbl_customerorderdetail.OtherCost),0) AS OtherCost,
COALESCE((tbl_customerorderdetail.BuyPrice),0) AS BuyPrice,
COALESCE((tbl_customerorderdetail.SalePrice),0) AS SalePrice,
COALESCE((tbl_customerorderdetail.Qty),0) AS QTY
FROM tbl_customerorder
INNER JOIN tbl_customerorderdetail
ON tbl_customerorder.CustomerOrderID = tbl_customerorderdetail.CustomerOrderID
INNER JOIN tblproducts
ON tbl_customerorderdetail.ProductID = tblproducts.ProductID
LEFT JOIN tblbranch
ON tblbranch.BranchID = tbl_customerorder.SelltoOtherBranch
WHERE (tblproducts.ProductName LIKE '%".$sarchprd."%' OR tblproducts.ProductCode LIKE '%".$sarchprd."%' )
AND (tbl_customerorder.CustomerOrderDate BETWEEN '".$txtFrom."' AND '".$txtTo."')
AND tbl_customerorder.UserID = '".$getUserID."'
ORDER BY tbl_customerorder.CustomerOrderDate DESC");
$rowselect1=$db->dbCountRows($select1);
if($rowselect1>0){
$i = 1;
$TotalIncome = 0;
while($row=$db->fetch($select1)){
$OtherCost = $row->OtherCost;
$BuyPrice = $row->BuyPrice;
$SalePrice = $row->SalePrice;
$QTY = $row->QTY;
$TotalIncome += ($SalePrice * $QTY) - (($BuyPrice*$QTY)+ $OtherCost);
}
echo '<tr class="odd gradeX">
<td colspan="10" class="text-right">Total</td>
<td class="text-right"> $ '.round($TotalIncome,2).'</td>
</tr>';
}
}
else
{
echo '<tr class="even">
<td colspan="11"><font size="+1" color="#CC0000"> No Products Selected.</font></td>
</td>
</tr>';
}
echo ' </tbody>';
}
else
{
echo ' <thead>
<tr>
<th class="col-md-2 text-center">Date</th>
<th class="text-center">Name</th>
<th class="text-center">Sale to Branch</th>
<th class="col-md-1 text-center">QTY</th>
<th class="col-md-1 text-center">Sale Price</th>
<th class="col-md-1 text-center">Other Price</th>
<th class="col-md-1 text-center">Total Salling</th>
</tr>
</thead>
<tbody>';
$select=$db->query("SELECT tbl_customerorder.CustomerOrderID,
tbl_customerorderdetail.CustomerOrderDetailID,
tbl_customerorder.InvoiceNo,
tbl_customerorder.CustomerOrderDate,
tblproducts.ProductID,
tblproducts.ProductName,
COALESCE((tbl_customerorderdetail.OtherCost),0) AS OtherCost,
COALESCE((tbl_customerorderdetail.BuyPrice),0) AS BuyPrice,
COALESCE((tbl_customerorderdetail.SalePrice),0) AS SalePrice,
COALESCE((tbl_customerorderdetail.Qty),0) AS Qty,
COALESCE((tbl_customerorderdetail.BuyPrice),0) * COALESCE((tbl_customerorderdetail.Qty),0) AS Total_Buying,
COALESCE((tbl_customerorderdetail.SalePrice),0) * COALESCE((tbl_customerorderdetail.Qty),0) AS Total_Salling,
DATE_FORMAT( tbl_customerorder.CustomerOrderDate,'%d %b %Y %h:%m:%s') as SaleDate,
TIMESTAMPDIFF(MINUTE,tbl_customerorder.CustomerOrderDate,NOW()) AS CalcMin,
tbl_customerorder.UserID,
tbl_customerorder.SelltoOtherBranch,
tblbranch.BranchName
FROM tbl_customerorder
INNER JOIN tbl_customerorderdetail
ON tbl_customerorder.CustomerOrderID = tbl_customerorderdetail.CustomerOrderID
INNER JOIN tblproducts
ON tbl_customerorderdetail.ProductID = tblproducts.ProductID
LEFT JOIN tblbranch
ON tblbranch.BranchID = tbl_customerorder.SelltoOtherBranch
WHERE (tblproducts.ProductName LIKE '%".$sarchprd."%' OR tblproducts.ProductCode LIKE '%".$sarchprd."%' )
AND (tbl_customerorder.CustomerOrderDate BETWEEN '".$txtFrom." 01:01:01' AND '".$txtTo." 23:59:59')
AND tbl_customerorder.UserID = '".$getUserID."'
ORDER BY tbl_customerorder.CustomerOrderDate DESC");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
$i = 1;
while($row=$db->fetch($select)){
$CustomerOrderDetailID = $row->CustomerOrderDetailID;
$InvoiceNo = $row->InvoiceNo;
$CustomerOrderDate = $row->CustomerOrderDate;
$ProductID = $row->ProductID;
$ProductName = $row->ProductName;
$Qty = $row->Qty;
$BuyPrice = $row->BuyPrice;
$SalePrice = $row->SalePrice;
$SaleDate = $row->SaleDate;
$CalcMin = $row->CalcMin;
$OtherCost = $row->OtherCost;
$BranchName = $row->BranchName;
$Total_Buying = $row->Total_Buying;
$Total_Salling = $row->Total_Salling;
$Income = $Total_Salling - ($Total_Buying + $OtherCost) ;
if($CalcMin <=120){
echo'<tr class="even">
<td>'.$SaleDate.'</td>
<td>'.$ProductName.'</td>
<td>'.$BranchName.'</td>
<td class="text-center">'.$Qty.'</td>
<td class="text-right">$ '.$SalePrice.'</td>
<td class="text-right">$ '.$OtherCost.'</td>
<td class="text-right">$ '.$Total_Salling.'</td>
</tr>';
}
else
{
echo'<tr class="even">
<td>'.$SaleDate.'</td>
<td>'.$ProductName.'</td>
<td>'.$BranchName.'</td>
<td class="text-center">'.$Qty.'</td>
<td class="text-right">$ '.$SalePrice.'</td>
<td class="text-right">$ '.$OtherCost.'</td>
<td class="text-right">$ '.$Total_Salling.'</td>
</tr>';
}
}
$select1=$db->query("SELECT
COALESCE((tbl_customerorderdetail.OtherCost),0) AS OtherCost,
COALESCE((tbl_customerorderdetail.BuyPrice),0) AS BuyPrice,
COALESCE((tbl_customerorderdetail.SalePrice),0) AS SalePrice,
COALESCE((tbl_customerorderdetail.Qty),0) AS QTY
FROM tbl_customerorder
INNER JOIN tbl_customerorderdetail
ON tbl_customerorder.CustomerOrderID = tbl_customerorderdetail.CustomerOrderID
INNER JOIN tblproducts
ON tbl_customerorderdetail.ProductID = tblproducts.ProductID
LEFT JOIN tblbranch
ON tblbranch.BranchID = tbl_customerorder.SelltoOtherBranch
WHERE (tblproducts.ProductName LIKE '%".$sarchprd."%' OR tblproducts.ProductCode LIKE '%".$sarchprd."%' )
AND (tbl_customerorder.CustomerOrderDate BETWEEN '".$txtFrom." 01:01:01' AND '".$txtTo." 23:59:59')
AND tbl_customerorder.UserID = '".$getUserID."'
ORDER BY tbl_customerorder.CustomerOrderDate DESC");
$rowselect1=$db->dbCountRows($select1);
if($rowselect1>0){
$i = 1;
$TotalIncome = 0;
while($row=$db->fetch($select1)){
$OtherCost = $row->OtherCost;
$BuyPrice = $row->BuyPrice;
$SalePrice = $row->SalePrice;
$QTY = $row->QTY;
$TotalIncome += ($SalePrice * $QTY);
}
echo '<tr class="odd gradeX">
<td colspan="7" class="text-right">Total</td>
<td class="text-right"> $ '.$TotalIncome.'</td>
</tr>';
}
}
else
{
echo '<tr class="even">
<td colspan="11"><font size="+1" color="#CC0000"> No Products Selected.</font></td>
</td>
</tr>';
}
echo ' </tbody>';
}
?>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
<!-- New User -->
<div class="modal fade" id="NewUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="exampleModalLabel">New Product</h4>
</div>
<div class="modal-body">
<form role="form" method="post">
<!--<div class="form-group">
<label>Choose Branch</label>
<select class="form-control" name="cboBranch">
<?php
/* $select=$db->query("SELECT BranchID, BranchName FROM `tblbranch`;");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$BranchID = $row->BranchID;
$BranchName = $row->BranchName;
echo'<option value='.$BranchID.'>'.$BranchName.'</option>';
}
}*/
?>
</select>
</div>-->
<div class="form-group">
<label>Choose Category</label>
<select class="form-control" name="cboPrdCate">
<?php
$select=$db->query("SELECT ProductCategoryID, ProductCategoryName FROM `tblproductcategory`;");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$ProductCategoryID = $row->ProductCategoryID;
$ProductCategoryName = $row->ProductCategoryName;
echo'<option value='.$ProductCategoryID.'>'.$ProductCategoryName.'</option>';
}
}
?>
</select>
</div>
<div class="form-group">
<label>Product Name: </label>
<input name="txtprdname" class="form-control" placeholder="Enter text" required />
</div>
<div class="form-group">
<label>Products Code:</label>
<input name="txtcode" class="form-control" placeholder="Enter text" />
</div>
<div class="form-group">
<label>Products QTY:</label>
<input name="txtqty" class="form-control" placeholder="Enter text" />
</div>
<div class="form-group">
<label>Buy Price:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="number" name="txtbuyprice" value="1" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
</div>
<div class="form-group">
<label>Sale Price:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="number" value="1" name="txtsaleprice" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
</div>
<!--<div class="form-group">
<label>User Limit </label>
<label class="radio-inline">
<input type="radio" name="rdstatus" id="optionsRadiosInline1" value="1" checked>Active
</label>
<label class="radio-inline">
<input type="radio" name="rdstatus" id="optionsRadiosInline2" value="0">Suspend
</label>
</div>
-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="btnAddNewPrd" class="btn btn-primary" value="Save" />
</div>
</form>
</div>
</div>
</div>
<!-- End New User -->
<!-- Check Out -->
<!-- End Check Out -->
</aside><!-- /.right-side -->
</div><!-- ./wrapper -->
<!-- add new calendar event modal -->
<?php include 'footer.php';?><file_sep>/WebShopV2/db/7stockweb V.2- 2015-06-11.sql
/*
Navicat MySQL Data Transfer
Source Server : MySQL
Source Server Version : 50536
Source Host : localhost:3306
Source Database : 7webstock
Target Server Type : MYSQL
Target Server Version : 50536
File Encoding : 65001
Date: 2015-06-11 10:07:49
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `tblbranch`
-- ----------------------------
DROP TABLE IF EXISTS `tblbranch`;
CREATE TABLE `tblbranch` (
`BranchID` text,
`BranchName` text,
`Decription` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tblbranch
-- ----------------------------
INSERT INTO `tblbranch` VALUES ('123', 'A', 'Branch A');
INSERT INTO `tblbranch` VALUES ('1234', 'B', 'This is B');
INSERT INTO `tblbranch` VALUES ('1429329904', 'C', 'Branch C');
INSERT INTO `tblbranch` VALUES ('1429759395', 'D', 'This is Branch D');
INSERT INTO `tblbranch` VALUES ('0', 'All Branch', null);
INSERT INTO `tblbranch` VALUES ('1430901802', 'E', '');
INSERT INTO `tblbranch` VALUES ('1430903952', 'F', '');
-- ----------------------------
-- Table structure for `tblprdsaletem`
-- ----------------------------
DROP TABLE IF EXISTS `tblprdsaletem`;
CREATE TABLE `tblprdsaletem` (
`IP` text,
`ProductID` text,
`ProductName` text,
`BranchID` text,
`ProductCategoryID` text,
`ProductCode` text,
`QTY` int(11) DEFAULT NULL,
`BuyPrice` float DEFAULT NULL,
`SalePrice` float DEFAULT NULL,
`PrdCopied` int(11) DEFAULT NULL,
`UpdateTem` int(11) DEFAULT NULL,
`isStock` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tblprdsaletem
-- ----------------------------
-- ----------------------------
-- Table structure for `tblprdtem`
-- ----------------------------
DROP TABLE IF EXISTS `tblprdtem`;
CREATE TABLE `tblprdtem` (
`IP` text,
`ProductID` text,
`ProductName` text,
`ProductCategoryID` text,
`ProductCode` text,
`QTY` int(11) DEFAULT NULL,
`BuyPrice` float DEFAULT NULL,
`SalePrice` float DEFAULT NULL,
`PrdCopied` int(11) DEFAULT NULL,
`UpdateTem` int(11) DEFAULT NULL,
`BranchID` int(11) DEFAULT NULL,
`isStock` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tblprdtem
-- ----------------------------
-- ----------------------------
-- Table structure for `tblproductcategory`
-- ----------------------------
DROP TABLE IF EXISTS `tblproductcategory`;
CREATE TABLE `tblproductcategory` (
`ProductCategoryID` text,
`ProductCategoryName` text,
`Decription` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tblproductcategory
-- ----------------------------
INSERT INTO `tblproductcategory` VALUES ('1', 'Apple', '');
INSERT INTO `tblproductcategory` VALUES ('2', 'Samsung', null);
INSERT INTO `tblproductcategory` VALUES ('3', 'Nokia', null);
INSERT INTO `tblproductcategory` VALUES ('1429330149', 'LG999', '');
INSERT INTO `tblproductcategory` VALUES ('1429775770', 'Book Store', 'Engish book');
INSERT INTO `tblproductcategory` VALUES ('1430899717', 'Car', '');
INSERT INTO `tblproductcategory` VALUES ('1432021651', 'Service', '123');
INSERT INTO `tblproductcategory` VALUES ('1432372512', '7Technology', 'ssssssssss');
-- ----------------------------
-- Table structure for `tblproducts`
-- ----------------------------
DROP TABLE IF EXISTS `tblproducts`;
CREATE TABLE `tblproducts` (
`ProductID` text,
`ProductName` text,
`ProductCategoryID` text,
`ProductCode` text,
`Qty` int(11) DEFAULT NULL,
`BuyPrice` float DEFAULT NULL,
`SalePrice` float DEFAULT NULL,
`Decription` text,
`isStock` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tblproducts
-- ----------------------------
INSERT INTO `tblproducts` VALUES ('1433841824', 'Book1', '2', 'b1', '1', '5', '7', null, '0');
INSERT INTO `tblproducts` VALUES ('1433842238', 'Setup new windows', '1432021651', 'win7', '1', '0', '7', null, '0');
-- ----------------------------
-- Table structure for `tblproductsbranch`
-- ----------------------------
DROP TABLE IF EXISTS `tblproductsbranch`;
CREATE TABLE `tblproductsbranch` (
`ProductID` text,
`BranchID` text,
`BuyPrice` float DEFAULT NULL,
`OtherCost` float DEFAULT NULL,
`SalePrice` float DEFAULT NULL,
`Qty` float DEFAULT NULL,
`QtyInstock` float DEFAULT NULL,
`TotalBuyPrice` float DEFAULT NULL,
`Decription` text,
`FromBranchID` text,
`FromPrdID` text,
`isStock` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tblproductsbranch
-- ----------------------------
INSERT INTO `tblproductsbranch` VALUES ('1433841824', '123', '5', '0', '7', '1', '0', '1', null, null, null, '0');
INSERT INTO `tblproductsbranch` VALUES ('1433842238', '123', '0', '0', '7', '1', '0', '1', null, null, null, '0');
-- ----------------------------
-- Table structure for `tblproducts_buy`
-- ----------------------------
DROP TABLE IF EXISTS `tblproducts_buy`;
CREATE TABLE `tblproducts_buy` (
`BuyID` text,
`BuyDate` datetime DEFAULT NULL,
`UserID` text,
`Decription` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tblproducts_buy
-- ----------------------------
INSERT INTO `tblproducts_buy` VALUES ('1433841827', '2015-06-09 16:23:47', '1', '');
INSERT INTO `tblproducts_buy` VALUES ('1433842241', '2015-06-09 16:30:41', '1', '');
-- ----------------------------
-- Table structure for `tblproducts_buydetail`
-- ----------------------------
DROP TABLE IF EXISTS `tblproducts_buydetail`;
CREATE TABLE `tblproducts_buydetail` (
`BuyDetailID` text,
`BuyID` text,
`UserID` text,
`ProductID` text,
`Qty` float DEFAULT NULL,
`BuyPrice` float DEFAULT NULL,
`OtherCost` float DEFAULT NULL,
`Decription` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tblproducts_buydetail
-- ----------------------------
INSERT INTO `tblproducts_buydetail` VALUES ('14338418271', '1433841827', '1', '1433841824', '1', '5', null, '');
INSERT INTO `tblproducts_buydetail` VALUES ('14338422411', '1433842241', '1', '1433842238', '1', '0', null, '');
-- ----------------------------
-- Table structure for `tblrule`
-- ----------------------------
DROP TABLE IF EXISTS `tblrule`;
CREATE TABLE `tblrule` (
`RuleID` text,
`ProductID` text,
`Min` float DEFAULT NULL,
`Max` float DEFAULT NULL,
`DayMin` float DEFAULT NULL,
`DayMax` float DEFAULT NULL,
`Atm` float DEFAULT NULL,
`Description` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tblrule
-- ----------------------------
INSERT INTO `tblrule` VALUES ('1433984910', '1433841824', '10', '20', '30', '40', '50', 'Description 20');
INSERT INTO `tblrule` VALUES ('1433986200', '1433842238', '50', '50', '10', '50', '23456800', 'Welcome');
INSERT INTO `tblrule` VALUES ('1433991981', '1433842238', '2', '4', '3', '5', '5555', 'wwww');
-- ----------------------------
-- Table structure for `tbltest`
-- ----------------------------
DROP TABLE IF EXISTS `tbltest`;
CREATE TABLE `tbltest` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbltest
-- ----------------------------
INSERT INTO `tbltest` VALUES ('1', '1');
INSERT INTO `tbltest` VALUES ('2', '123');
INSERT INTO `tbltest` VALUES ('3', '123');
INSERT INTO `tbltest` VALUES ('4', '123');
-- ----------------------------
-- Table structure for `tblusers`
-- ----------------------------
DROP TABLE IF EXISTS `tblusers`;
CREATE TABLE `tblusers` (
`UserID` text,
`BranchID` text,
`UserName` text,
`Password` text,
`Level` int(11) DEFAULT NULL,
`Decription` text,
`Status` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tblusers
-- ----------------------------
INSERT INTO `tblusers` VALUES ('1', '123', 'admin', 'a09sNXhtNExpZ1MwZkJSY0wwVGxiQT09', '1', '', '1');
INSERT INTO `tblusers` VALUES ('1431662725', '123', 'a', 'T3JITG9YU1FtWHB5cUJuN0tOUU1BUT09', '1', '', '1');
INSERT INTO `tblusers` VALUES ('1431662756', '123', 'aa', 'T3JITG9YU1FtWHB5cUJuN0tOUU1BUT09', '2', '', '1');
-- ----------------------------
-- Table structure for `tbl_app_setting`
-- ----------------------------
DROP TABLE IF EXISTS `tbl_app_setting`;
CREATE TABLE `tbl_app_setting` (
`ID` text,
`Name` text,
`Value` int(11) DEFAULT NULL,
`Description` text,
`IsEdit` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbl_app_setting
-- ----------------------------
INSERT INTO `tbl_app_setting` VALUES ('12345', 'Android', '1', 'Hello Android.', '127');
-- ----------------------------
-- Table structure for `tbl_customerorder`
-- ----------------------------
DROP TABLE IF EXISTS `tbl_customerorder`;
CREATE TABLE `tbl_customerorder` (
`CustomerOrderID` text,
`BranchID` text,
`ToBranchID` text,
`InvoiceNo` text,
`CustomerOrderDate` datetime DEFAULT NULL,
`Total` float DEFAULT NULL,
`perDicount` float DEFAULT NULL,
`AmtDiscount` float DEFAULT NULL,
`GTotal` float DEFAULT NULL,
`Recieve` float DEFAULT NULL,
`Return` float DEFAULT NULL,
`Decription` text,
`UserID` text,
`SelltoOtherBranch` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbl_customerorder
-- ----------------------------
-- ----------------------------
-- Table structure for `tbl_customerorderdetail`
-- ----------------------------
DROP TABLE IF EXISTS `tbl_customerorderdetail`;
CREATE TABLE `tbl_customerorderdetail` (
`CustomerOrderDetailID` text,
`BranchID` text,
`ToBranchID` text,
`CustomerOrderID` text,
`ProductID` text,
`Qty` float DEFAULT NULL,
`OtherCost` float DEFAULT NULL,
`BuyPrice` float DEFAULT NULL,
`SalePrice` float DEFAULT NULL,
`perDicount` float DEFAULT NULL,
`AmtDiscount` float DEFAULT NULL,
`LastSalePrice` float DEFAULT NULL,
`Total` float DEFAULT NULL,
`Decription` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbl_customerorderdetail
-- ----------------------------
-- ----------------------------
-- Table structure for `tbl_service_type`
-- ----------------------------
DROP TABLE IF EXISTS `tbl_service_type`;
CREATE TABLE `tbl_service_type` (
`Service_Type_ID` text,
`BranchID` text,
`Service_Type_Name` text,
`Service_Type_Desciption` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbl_service_type
-- ----------------------------
-- ----------------------------
-- Procedure structure for `spCompanyInsert`
-- ----------------------------
DROP PROCEDURE IF EXISTS `spCompanyInsert`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `spCompanyInsert`(
IN
_ComID NVARCHAR(500),
_ComName NVARCHAR(500),
_ComDate DATE,
_ComProfile NVARCHAR(500),
_ComMobile INT,
_ComEmail NVARCHAR(500),
_ComAddress NVARCHAR(500),
_ComZipCode INT,
_LastUpdate DATE,
_UserID NVARCHAR(500),
_PrdCategID NVARCHAR(500),
_ComStatus INT
)
BEGIN
INSERT INTO tblcompany(
ComID,
ComName,
ComDate,
ComProfile,
ComMobileNumber,
ComEmail,
ComAddress,
ComZipCode,
LastUpdate,
UserID,
PrdCategID,
ComStatus
)
VALUES (
_ComID,
_ComName,
_ComDate,
_ComProfile,
_ComMobile,
_ComEmail,
_ComAddress,
_ComZipCode,
_LastUpdate,
_UserID,
_PrdCategID,
_ComStatus
);
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `spSearchPrdBuy`
-- ----------------------------
DROP PROCEDURE IF EXISTS `spSearchPrdBuy`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `spSearchPrdBuy`(IN _SearchPrdBuy NVARCHAR(500))
BEGIN
IF(_SearchPrdBuy = "") THEN
SELECT
`tblproducts`.ProductID,
`tblproducts`.ProductName,
`tblproducts`.ProductCategoryID,
tblproductcategory.ProductCategoryName,
`tblproducts`.ProductCode,
`tblproducts`.Qty,
`tblproducts`.BuyPrice,
`tblproducts`.SalePrice,
tblproductsbranch.OtherCost,
tblproductsbranch.Decription
FROM `tblproducts`
INNER JOIN tblproductcategory
ON tblproducts.ProductCategoryID = tblproductcategory.ProductCategoryID
INNER JOIN tblproductsbranch
ON tblproductsbranch.ProductID = tblproducts.ProductID
WHERE tblproductsbranch.Qty >0
LIMIT 7;
ELSE
SELECT
`tblproducts`.ProductID,
`tblproducts`.ProductName,
`tblproducts`.ProductCategoryID,
tblproductcategory.ProductCategoryName,
`tblproducts`.ProductCode,
`tblproducts`.Qty,
`tblproducts`.BuyPrice,
`tblproducts`.SalePrice,
tblproductsbranch.OtherCost,
tblproductsbranch.Decription
FROM `tblproducts`
INNER JOIN tblproductcategory
ON tblproducts.ProductCategoryID = tblproductcategory.ProductCategoryID
INNER JOIN tblproductsbranch
ON tblproductsbranch.ProductID = tblproducts.ProductID
WHERE
tblproducts.ProductName LIKE CONCAT(N'%' , _SearchPrdBuy , '%')
OR tblproducts.ProductCode LIKE CONCAT(N'%' , _SearchPrdBuy , '%')
AND tblproductsbranch.Qty >0;
END IF;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `spSearchPrdBuyHistory`
-- ----------------------------
DROP PROCEDURE IF EXISTS `spSearchPrdBuyHistory`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `spSearchPrdBuyHistory`(IN _SearchPrdSale NVARCHAR(500), IN _SearchPrdBranch NVARCHAR(500))
BEGIN
IF(_SearchPrdSale ) is NULL THEN
SELECT
`tblproducts`.ProductID,
`tblproducts`.ProductName,
`tblproducts`.ProductCategoryID,
tblproductcategory.ProductCategoryName,
`tblproducts`.ProductCode,
`tblproducts`.Qty,
`tblproducts`.BuyPrice,
`tblproducts`.SalePrice
FROM `tblproducts`
INNER JOIN tblproductcategory
ON tblproducts.ProductCategoryID = tblproductcategory.ProductCategoryID
INNER JOIN tblproductsbranch
ON tblproducts.ProductID = tblproductsbranch.ProductID ;
ELSE
SELECT
`tblproducts`.ProductID,
`tblproducts`.ProductName,
`tblproducts`.ProductCategoryID,
tblproductcategory.ProductCategoryName,
`tblproducts`.ProductCode,
`tblproducts`.Qty,
`tblproducts`.BuyPrice,
`tblproducts`.SalePrice
FROM `tblproducts`
INNER JOIN tblproductcategory
ON tblproducts.ProductCategoryID = tblproductcategory.ProductCategoryID
INNER JOIN tblproductsbranch
ON tblproducts.ProductID = tblproductsbranch.ProductID
WHERE ( `tblproducts`.ProductName LIKE CONCAT(N'%' , _SearchPrdSale , '%')
OR `tblproducts`.ProductCode LIKE CONCAT(N'%' , _SearchPrdSale , '%'))
and tblproductsbranch.BranchID = '123' ;
END IF;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `spSearchPrdSale`
-- ----------------------------
DROP PROCEDURE IF EXISTS `spSearchPrdSale`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `spSearchPrdSale`(IN _SearchPrdSale NVARCHAR(500), IN _SearchPrdBranch NVARCHAR(500))
BEGIN
IF(_SearchPrdSale ) is NULL THEN
SELECT
`tblproducts`.ProductID,
`tblproducts`.ProductName,
`tblproducts`.ProductCategoryID,
tblproductcategory.ProductCategoryName,
`tblproducts`.ProductCode,
`tblproducts`.Qty,
`tblproducts`.BuyPrice,
`tblproducts`.SalePrice
FROM `tblproducts`
INNER JOIN tblproductcategory
ON tblproducts.ProductCategoryID = tblproductcategory.ProductCategoryID
INNER JOIN tblproductsbranch
ON tblproducts.ProductID = tblproductsbranch.ProductID ;
ELSE
SELECT
`tblproducts`.ProductID,
`tblproducts`.ProductName,
`tblproducts`.ProductCategoryID,
tblproductcategory.ProductCategoryName,
`tblproducts`.ProductCode,
`tblproducts`.Qty,
`tblproducts`.BuyPrice,
`tblproducts`.SalePrice
FROM `tblproducts`
INNER JOIN tblproductcategory
ON tblproducts.ProductCategoryID = tblproductcategory.ProductCategoryID
INNER JOIN tblproductsbranch
ON tblproducts.ProductID = tblproductsbranch.ProductID
WHERE ( `tblproducts`.ProductName LIKE CONCAT(N'%' , _SearchPrdSale , '%')
OR `tblproducts`.ProductCode LIKE CONCAT(N'%' , _SearchPrdSale , '%'))
and tblproductsbranch.BranchID = '123' ;
END IF;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `spTestingSellingQty`
-- ----------------------------
DROP PROCEDURE IF EXISTS `spTestingSellingQty`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `spTestingSellingQty`(
IN _SearchPrdBuy NVARCHAR(500) )
BEGIN
SELECT
`tblproducts`.ProductID,
`tblproducts`.ProductName,
`tblproducts`.ProductCode,
`tblproducts`.ProductCategoryID,
tblproductcategory.ProductCategoryName,
tblproductsbranch.Qty,
tblproductsbranch.BuyPrice,
tblproductsbranch.SalePrice
FROM `tblproducts`
INNER JOIN tblproductcategory
ON tblproducts.ProductCategoryID = tblproductcategory.ProductCategoryID
INNER JOIN tblproductsbranch
ON tblproducts.ProductID = tblproductsbranch.ProductID;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `spUserAccClearData`
-- ----------------------------
DROP PROCEDURE IF EXISTS `spUserAccClearData`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `spUserAccClearData`(_UserName NVARCHAR(500),
_UserPwd NVARCHAR(500))
BEGIN
SELECT tblusers.UserID,
tblusers.BranchID,
tblusers.UserName,
tblusers.`Password` AS UserPassword,
tblusers.`Level` AS UserLever,
tblusers.`Status` AS UserStatus,
tblbranch.BranchName
FROM tblusers INNER JOIN tblbranch
ON tblusers.BranchID = tblbranch.BranchID
WHERE tblusers.UserName = _UserName
AND tblusers.`Password` = <PASSWORD>
AND tblusers.`STATUS` = 1
AND tblusers.UserID = 1;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `spUserAccSelete`
-- ----------------------------
DROP PROCEDURE IF EXISTS `spUserAccSelete`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `spUserAccSelete`(_UserName NVARCHAR(500),
_UserPwd NVARCHAR(500))
BEGIN
SELECT tblusers.UserID,
tblusers.BranchID,
tblusers.UserName,
tblusers.`Password` AS UserPassword,
tblusers.`Level` AS UserLever,
tblusers.`Status` AS UserStatus,
tblbranch.BranchName
FROM tblusers INNER JOIN tblbranch
ON tblusers.BranchID = tblbranch.BranchID
WHERE tblusers.UserName = _UserName
AND tblusers.`Password` = <PASSWORD>
AND tblusers.`STATUS` = 1;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_Branch_Delete`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_Branch_Delete`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Branch_Delete`(IN _BranchID NVARCHAR(50))
BEGIN
DELETE From tblbranch
WHERE BranchID=_BranchID;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_Branch_Select`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_Branch_Select`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Branch_Select`(IN _Search NVARCHAR(50))
BEGIN
IF (_Search="") THEN
SELECT
BranchID,
BranchName,
Decription
From tblbranch
WHERE BranchID != 0;
ELSE
SELECT
BranchID,
BranchName,
Decription
From tblbranch
WHERE (BranchName Like CONCAT('%' , _Search , '%') OR Decription Like CONCAT('%' , _Search , '%') )
AND BranchID != 0;
END IF;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_Branch_Update`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_Branch_Update`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Branch_Update`(IN _BranchID NVARCHAR(50),_BranchName NVARCHAR(100),_Decription NVARCHAR(250))
BEGIN
UPDATE tblbranch SET
BranchName=_BranchName,
Decription=_Decription
WHERE BranchID=_BranchID;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_Category_Delete`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_Category_Delete`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Category_Delete`(IN _ProductCategoryID NVARCHAR(50))
BEGIN
DELETE From tblproductcategory
WHERE ProductCategoryID=_ProductCategoryID;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_Category_Select`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_Category_Select`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Category_Select`(IN _Search NVARCHAR(200))
BEGIN
IF (_Search="") THEN
SELECT
ProductCategoryID,
ProductCategoryName,
Decription
From tblproductcategory;
ELSE
SELECT
ProductCategoryID,
ProductCategoryName,
Decription
From tblproductcategory
WHERE (ProductCategoryName Like CONCAT('%' , _Search , '%') OR Decription Like CONCAT('%' , _Search , '%') );
END IF;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_Category_Update`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_Category_Update`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Category_Update`(IN _ProductCategoryID NVARCHAR(50),_ProductCategoryName NVARCHAR(100),_Decription NVARCHAR(250))
BEGIN
UPDATE tblproductcategory SET
ProductCategoryName=_ProductCategoryName,
Decription=_Decription
WHERE ProductCategoryID=_ProductCategoryID;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_Insert_Branch`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_Insert_Branch`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Insert_Branch`(IN
_BranchID NVARCHAR(50),
_BranchName NVARCHAR(100),
_Decription NVARCHAR(500))
BEGIN
INSERT INTO tblbranch(
BranchID,
BranchName,
Decription
)
VALUES (
_BranchID,
_BranchName,
_Decription
);
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_Insert_Category`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_Insert_Category`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Insert_Category`(IN _ProductCategoryID NVARCHAR(50),_ProductCategoryName NVARCHAR(100),_Decription NVARCHAR(250))
BEGIN
INSERT INTO tblproductcategory(
ProductCategoryID,
ProductCategoryName,
Decription
)
VALUES (
_ProductCategoryID,
_ProductCategoryName,
_Decription
);
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_Insert_UserAccount`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_Insert_UserAccount`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Insert_UserAccount`(IN _UserID NVARCHAR(100),_BranchID NVARCHAR(50),_UserName NVARCHAR(100),_Password NVARCHAR(100), _Level int,_Decription NVARCHAR(500),_Status int)
BEGIN
INSERT INTO tblusers(
UserID,
BranchID,
UserName,
Password,
Level,
Decription,
Status
)
VALUES (
_UserID,
_BranchID,
_UserName,
_Password,
_Level,
_Decription,
_Status
);
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_UserAccount_Delete`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_UserAccount_Delete`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_UserAccount_Delete`(IN _UserID NVARCHAR(100))
BEGIN
DELETE From tblusers
WHERE UserID=_UserID;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_UserAccount_Select`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_UserAccount_Select`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_UserAccount_Select`(IN _Search NVARCHAR(100))
BEGIN
IF (_Search="") THEN
SELECT
UserID,
BranchID,
UserName,
Password,
Level,
Decription,
Status
From tblusers;
ELSE
SELECT
UserID,
BranchID,
UserName,
Password,
Level,
Decription,
Status
From tblusers
WHERE (UserName Like CONCAT('%' , _Search , '%') OR Decription Like CONCAT('%' , _Search , '%') );
END IF;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_UserAccount_Select_By_ID`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_UserAccount_Select_By_ID`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_UserAccount_Select_By_ID`(IN _BranchID NVARCHAR(100))
BEGIN
SELECT
UserID,
BranchID,
UserName,
Password,
Level,
Decription,
Status
From tblusers
WHERE BranchID=_BranchID;
END
;;
DELIMITER ;
-- ----------------------------
-- Procedure structure for `sp_UserAccount_Update`
-- ----------------------------
DROP PROCEDURE IF EXISTS `sp_UserAccount_Update`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_UserAccount_Update`(IN _UserID NVARCHAR(100),_BranchID NVARCHAR(50),_UserName NVARCHAR(100), _Level int,_Decription NVARCHAR(500),_Status int)
BEGIN
UPDATE tblusers SET
BranchID =_BranchID,
UserName=_UserName,
Level=_Level,
Decription=_Decription,
Status=_Status
WHERE UserID=_UserID;
END
;;
DELIMITER ;
-- ----------------------------
-- Function structure for `IncomeLevel`
-- ----------------------------
DROP FUNCTION IF EXISTS `IncomeLevel`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `IncomeLevel`( monthly_value INT ) RETURNS varchar(20) CHARSET utf8
BEGIN
DECLARE income_level varchar(20);
IF monthly_value <= 4000 THEN
SET income_level = 'Low Income';
ELSEIF monthly_value > 4000 AND monthly_value <= 7000 THEN
SET income_level = 'Avg Income';
ELSE
SET income_level = 'High Income';
END IF;
RETURN income_level;
END
;;
DELIMITER ;
-- ----------------------------
-- Function structure for `PageCount`
-- ----------------------------
DROP FUNCTION IF EXISTS `PageCount`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `PageCount`( value INT ) RETURNS varchar(10) CHARSET utf8
DETERMINISTIC
BEGIN
DECLARE level varchar(20);
IF value < 500 THEN
SET level = 'Low';
ELSEIF value >= 500 AND value <= 4000 THEN
SET level = 'Medium';
ELSE
SET level = 'High';
END IF;
RETURN level;
END
;;
DELIMITER ;
<file_sep>/savedirectfrombuying.php
<?php
include 'header.php';
$buyid = time();
$PrdID = time().'2';
$BuyDetailID = time().'3';
/*$InsertTotblBuy= $db->query("INSERT INTO tblproducts_buy (BuyID, BuyDate, UserID, Decription)
VALUES('".$buyid."','".$date_now."','".$U_id."','');");
$inserTotblBuyDetail = $db->query("INSERT INTO tblproducts_buydetail
( BuyDetailID,
BuyID,
UserID,
ProductID,
Qty,
BuyPrice,
Decription )
VALUES
(
'".time().'1'."',
'".$buyid."',
'".$U_id."',
'".time().'2'."',
1,
'".$txtbuyprice1."',
''
)");*/
$insertTotblProducts=$db->query("INSERT INTO tblproducts(ProductID, ProductName, ProductCategoryID, ProductCode, Qty, BuyPrice, SalePrice, Decription)
VALUES( '".$PrdID."', '".$txtprdname1."','".$cboPrdCate1."','".$txtcode1."',1,".$txtbuyprice1.",".$txtsaleprice1.",'Desc');");
$inserttobuyBranch=$db->query("INSERT INTO tblproductsbranch (ProductID, BranchID, BuyPrice, OtherCost, SalePrice, Qty)
VALUES ('".$PrdID."', '".$U_Brandid."',".$txtbuyprice1.",0 , ".$txtsaleprice1.", 1)");
$InsertTotblBuy= $db->query("INSERT INTO tblproducts_buy (BuyID, BuyDate, UserID, Decription)
VALUES('".$buyid."','".$date_now."','".$U_id."','');");
$inserTotblBuyDetail = $db->query("INSERT INTO tblproducts_buydetail
( BuyDetailID,
BuyID,
UserID,
ProductID,
Qty,
BuyPrice,
Decription )
VALUES
(
'".$BuyDetailID."',
'".$buyid."',
'".$U_id."',
'".$PrdID."',
1,
'".$txtbuyprice1."',
''
)");
if($inserTotblBuyDetail){
cRedirect('frmSalePrd.php');
}
?><file_sep>/saveOtherCose.php
<?php
include 'header.php';
$txtCustomerOrderDetailID = get('txtCustomerOrderDetailID');
$txtsaleprice = get('txtsaleprice');
$txtDesc = get('txtDesc');
/*Create Invoice Customer Sale*/
$InsertToCustomerOrder=$db->query(" UPDATE tblproductsbranch SET
OtherCost='".$txtsaleprice."',
Decription='".$txtDesc."'
WHERE ProductID = '".$txtCustomerOrderDetailID."'");
//UPDATE tblproductsbranch SET OtherCost = '".$txtOtherCost."', Decription=N'".$txtDesc."' WHERE ProductID = '".$ProductID."'
if($InsertToCustomerOrder){
cRedirect('Report_Saling.php');
}
?><file_sep>/frmAfterBuying.php
<?php include 'header.php';?>
<?php
// Add new product to Produtct Tem
if(isset($_POST['btnAddNewPrd'])){
$txtQty = post('txtQty');
$txtPrice = post('txtPrice');
$txtotherCost = post('txtotherCost');
$insert=$db->query("UPDATE `tblproducts_buydetail` SET
Qty = '".$txtQty."',
BuyPrice = '".$txtPrice."',
OtherCost = '".$txtotherCost."'
WHERE BuyDetailID = '".$getBuydetailid."' ");
// Update Products Set Increase
$Updatestock1=$db->query("UPDATE tblproductsbranch SET Qty = ( Qty - ".$getQty." ) + ".$txtQty." , BuyPrice = ".$txtPrice.", OtherCost= ".$txtotherCost."
WHERE ProductID = '".$getProductID."';");
if($insert){
cRedirect('invoicebuying.php');
}
/*if($txtQty<$getQty)
{
$insert=$db->query("UPDATE tblproducts_buydetail SET Qty = ".$txtQty." , BuyPrice = ".$txtPrice." , OtherCost = ".$txtotherCost."
WHERE BuyDetailID = '".$getBuydetailid."'; ");
// Update Products Set Increase
$Updatestock1=$db->query("UPDATE tblproductsbranch SET Qty = ( Qty - ".$getQty." ) + ".$txtQty." , BuyPrice = ".$txtPrice.", OtherCost= ".$txtotherCost."
WHERE ProductID = '".$getBuydetailid."';");
if($insert){
cRedirect('invoicebuying.php');
}
}
else if($txtQty>$getQty)
{
$insert=$db->query("UPDATE tblproducts_buydetail SET Qty = ".$txtQty." , BuyPrice = ".$txtPrice." , OtherCost = ".$txtotherCost."
WHERE BuyDetailID = '".$getBuydetailid."' ");
$Updatestock=$db->query("UPDATE tblproductsbranch SET Qty = ( Qty - ".$getQty." ) + ".$txtQty." , BuyPrice = ".$txtPrice.", OtherCost= ".$txtotherCost."
WHERE ProductID = '".$getProductID."';");
if($insert){
cRedirect('invoicebuying.php');
}
}
else
{
$insert=$db->query("UPDATE tblproducts_buydetail SET BuyPrice = ".$txtPrice.", OtherCost= ".$txtotherCost."
WHERE BuyDetailID = '".$getBuydetailid."' ");
$Updatestock=$db->query("UPDATE tblproductsbranch SET BuyPrice = ".$txtPrice.", OtherCost= ".$txtotherCost."
WHERE ProductID = '".$getProductID."';");
cRedirect('invoicebuying.php');
}
$error = "Error Internet Connection!";*/
}
?>
<body class="skin-blue">
<!-- header logo: style can be found in header.less -->
<?php include 'nav.php';?>
<!-- Left side column. contains the logo and sidebar -->
<?php include 'menu.php';?>
<!-- Right side column. Contains the navbar and content of the page -->
<aside class="right-side">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<small>Control panel</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section>
<!-- Main content -->
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Name</th>
<th>QTY</th>
<th>Price</th>
<th>Other Price</th>
<th class="">Action</th>
</tr>
</thead>
<tbody>
<form role="form" method="post" enctype="multipart/form-data">
<?php
echo'<tr class="even">
<td>'.$getProductsName.'</td>
<td><input name="txtQty" value="'.$getQty.'" onKeyUp="checkInput(this)" class="form-control" placeholder="Enter text" /></td>
<td><input name="txtPrice" value="'.$getBuyprice.'" onkeypress="return isNumberKey(event)" class="form-control" placeholder="Enter text" /></td>
<td><input name="txtotherCost" value="'.$getothecost.'" onkeypress="return isNumberKey(event)" class="form-control" placeholder="Enter text" /></td>
<td class="center">
<input type="submit" name="btnAddNewPrd" class="btn btn-primary" value="Save" />
</td>
</tr>';
?>
</form>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
<!-- New User -->
<div class="modal fade" id="NewUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="exampleModalLabel">New message</h4>
</div>
<div class="modal-body">
<form role="form" method="post">
<!--<div class="form-group">
<label>Choose Branch</label>
<select class="form-control" name="cboBranch">
<?php
/* $select=$db->query("SELECT BranchID, BranchName FROM `tblbranch`;");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$BranchID = $row->BranchID;
$BranchName = $row->BranchName;
echo'<option value='.$BranchID.'>'.$BranchName.'</option>';
}
}*/
?>
</select>
</div>-->
<div class="form-group">
<label>Choose Category</label>
<select class="form-control" name="cboPrdCate">
<?php
$select=$db->query("SELECT ProductCategoryID, ProductCategoryName FROM `tblproductcategory`;");
$rowselect=$db->dbCountRows($select);
if($rowselect>0){
while($row=$db->fetch($select)){
$ProductCategoryID = $row->ProductCategoryID;
$ProductCategoryName = $row->ProductCategoryName;
echo'<option value='.$ProductCategoryID.'>'.$ProductCategoryName.'</option>';
}
}
?>
</select>
</div>
<div class="form-group">
<label>Product Name: </label>
<input name="txtprdname" class="form-control" placeholder="Enter text" required />
</div>
<div class="form-group">
<label>Products Code:</label>
<input name="txtcode" class="form-control" placeholder="Enter text" />
</div>
<div class="form-group">
<label>Products QTY:</label>
<input name="txtqty" class="form-control" placeholder="Enter text" />
</div>
<div class="form-group">
<label>Buy Price:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="number" name="txtbuyprice" value="1" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
</div>
<div class="form-group">
<label>Sale Price:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="number" value="1" name="txtsaleprice" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
</div>
</div>
<!--<div class="form-group">
<label>User Limit </label>
<label class="radio-inline">
<input type="radio" name="rdstatus" id="optionsRadiosInline1" value="1" checked>Active
</label>
<label class="radio-inline">
<input type="radio" name="rdstatus" id="optionsRadiosInline2" value="0">Suspend
</label>
</div>
-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="btnUpdate" class="btn btn-primary" value="Save" />
</div>
</form>
</div>
</div>
</div>
<!-- End New User -->
</aside><!-- /.right-side -->
</div><!-- ./wrapper -->
<!-- add new calendar event modal -->
<?php include 'footer.php';?><file_sep>/WebShopV2/updateRule.php
<?php
include 'header.php';
$autoid = time();
$txtRuleID = get('txtRuleID');
$txtProductID = get('txtProductID');
$cboPrd = get('cboPrd');
$txtmin = get('txtmin');
$txtmax = get('txtmax');
$txtdaymin = get('txtdaymin');
$txtdaymax = get('txtdaymax');
$txtatm = get('txtatm');
$txtDesc = get('txtDesc');
$updateRule=$db->query("UPDATE tblrule SET Min=".$txtmin.", Max=".$txtmax.", DayMin=".$txtdaymin.", DayMax=".$txtdaymax.", Atm=".$txtatm.", Description=N'".$txtDesc."'
WHERE RuleID = '".$txtRuleID."'");
if($updateRule)
{
echo "<script type='text/javascript'>alert('Update Successful!')</script>";
cRedirect('frmRule.php');
}
else
{
echo "<script type='text/javascript'>alert('Error!')</script>";
}
/*if($cboPrd == 0)
{
$updateRule=$db->query("UPDATE tblrule SET Min=".$txtmin.", Max=".$txtmax.", DayMin=".$txtdaymin.", DayMax=".$txtdaymax.", Atm=".$txtatm.", Description=N'".$txtDesc."'
WHERE RuleID = '".$txtRuleID."'");
if($updateRule)
{
echo "<script type='text/javascript'>alert('Update Successful!')</script>";
cRedirect('frmRule.php');
}
else
{
echo "<script type='text/javascript'>alert('Error!')</script>";
}
}
else
{
$updateRule=$db->query("UPDATE tblrule SET Min=".$txtmin.", Max=".$txtmax.", DayMin=".$txtdaymin.", DayMax=".$txtdaymax.", Atm=".$txtatm.", Description=N'".$txtDesc."'
WHERE RuleID = '".$txtRuleID."'");
if($updateRule)
{
echo "<script type='text/javascript'>alert('Update Successful!')</script>";
cRedirect('frmRule.php');
}
else
{
echo "<script type='text/javascript'>alert('Error!')</script>";
}
}*/
/*Create Invoice Customer Sale*/
?><file_sep>/menu.php
<aside class="left-side sidebar-offcanvas">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<img src="img/avatar3.png" class="img-circle" alt="User Image" />
</div>
<div class="pull-left info">
<p>Hello, <?php echo $U_Acc; ?></p>
<a href="#"><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- search form -->
<form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search..."/>
<span class="input-group-btn">
<button type='submit' name='search' id='search-btn' class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
<!-- /.search form -->
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
<?php
if($_SESSION['Level']=='1'){
echo '<li >
<a href="index.php">
<span>Buy & Sale Products</span>
</a>
</li>';
/*echo '<li class="treeview">
<a >
2. <span>Sale Products</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="frmSalePrd.php">2.1 Sale Products </a></li>
<li><a href="invoicesaling.php">2.2 Report Salling</a></li>
<li><a href="invoicesalingofuser.php">2.2 Report User Salling</a></li>
</ul>
</li>';*/
echo'<li class="treeview">
<a > <span>Setting</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="frmbranch.php">Branch</a></li>
<li><a href="frmCategory.php">Category</a></li>
</ul>
</li>';
echo '<li class="treeview">
<a href="userAccount.php">
<span>User Account</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="userAccount.php">User Account </a></li>
<li><a href="UserChangePassword.php">Change Password</a></li>
<li><a href="logout.php">Logout</a></li>
</ul>
</li>';
}
else
{
echo '<li>
<a href="index.php">
<span>Buy Products</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
</li>';
echo '<li class="treeview">
<a href="userAccount.php">
<span>User Account</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="UserChangePassword.php">Change Password</a></li>
<li><a href="logout.php">Logout</a></li>
</ul>
</li>';
}
?>
</ul>
</section>
<!-- /.sidebar -->
</aside> | 9316eff7017297fabdc05201f7d81f0a22cfce85 | [
"SQL",
"PHP"
] | 14 | PHP | khbuoyrupppiseth7/WebShop | 6e9fbb3758faf5ae3ba8aecd34eb0aae2cda850f | 5f7c56d273b9f38f84172ce629f075cd1b25a4ad |
refs/heads/master | <file_sep>const sponsorQry = $(() => {
if ($(window).width() < 768) {
// console.log($('.card.smOnMob').length);
let $card;
$('.card.smOnMob').each((index) => {
$card = $(`.card.smOnMob`);
console.log($card)
$card[index].onclick = () => {
$('.lgCards').addClass('displayed');
setTimeout(() => $(`.lgCards .card:nth-of-type(${index + 1})`).addClass('displayed'), 200);
$(`.lgCards .card .escElement img`).on('click', () => {
$(`.lgCards .card:nth-of-type(${index + 1})`).removeClass('displayed');
setTimeout(() => $('.lgCards').removeClass('displayed'), 500);
$(`.card .escElement:nth-of-type(${index + 1}) img`).off('click');
});
};
});
} else {
for (let index = 0; index < $('.sponsorContain .card').length; index++)
if ($('.lgCards').hasClass('displayed')) {
console.log('hasClass');
$(`.lgCards .card:nth-of-type(${index})`).removeClass('displayed');
$(`.lgCards`).removeClass('displayed');
};
};
});
export default sponsorQry;<file_sep>const sponsorQry = $(() => {
if ($(window).width() < 768) {
const $card1 = $('.sponsorContain .card:nth-of-type(1)'),
$card2 = $('.sponsorContain .card:nth-of-type(2)'),
$card3 = $('.sponsorContain .card:nth-of-type(3)'),
$card4 = $('.sponsorContain .card:nth-of-type(4)'),
$card5 = $('.sponsorContain .card:nth-of-type(5)'),
$card6 = $('.sponsorContain .card:nth-of-type(6)');
const $contain = $('.lgCards');
const $lgCard1 = $('.lgCards .card:nth-of-type(1)'),
$lgCard2 = $('.lgCards .card:nth-of-type(2)'),
$lgCard3 = $('.lgCards .card:nth-of-type(3)'),
$lgCard4 = $('.lgCards .card:nth-of-type(4)'),
$lgCard5 = $('.lgCards .card:nth-of-type(5)'),
$lgCard6 = $('.lgCards .card:nth-of-type(6)');
const $esc1 = $('.card .escElement:nth-of-type(1) img'),
$esc2 = $('.card .escElement:nth-of-type(2) img'),
$esc3 = $('.card .escElement:nth-of-type(3) img'),
$esc4 = $('.card .escElement:nth-of-type(4) img'),
$esc5 = $('.card .escElement:nth-of-type(5) img'),
$esc6 = $('.card .escElement:nth-of-type(6) img');
const $card1Handler = function() {
$contain.addClass('displayed');
setTimeout(() => $lgCard1.addClass('displayed'), 200);
$esc1.on('click', $esc1Handler);
$card2.off('click');
$card3.off('click');
$card4.off('click');
$card5.off('click');
$card6.off('click');
},
$card2Handler = function() {
$contain.addClass('displayed');
setTimeout(() => $lgCard2.addClass('displayed'), 200);
$esc2.on('click', $esc2Handler);
$card1.off('click');
$card3.off('click');
$card4.off('click');
$card5.off('click');
$card6.off('click');
},
$card3Handler = function() {
$contain.addClass('displayed');
setTimeout(() => $lgCard3.addClass('displayed'), 200);
$esc3.on('click', $esc3Handler);
$card1.off('click');
$card2.off('click');
$card4.off('click');
$card5.off('click');
$card6.off('click');
},
$card4Handler = function() {
$contain.addClass('displayed');
setTimeout(() => $lgCard4.addClass('displayed'), 200);
$esc4.on('click', $esc4Handler);
$card1.off('click');
$card2.off('click');
$card3.off('click');
$card5.off('click');
$card6.off('click');
},
$card5Handler = function() {
$contain.addClass('displayed');
setTimeout(() => $lgCard5.addClass('displayed'), 200);
$esc5.on('click', $esc5Handler);
$card1.off('click');
$card2.off('click');
$card3.off('click');
$card4.off('click');
$card6.off('click');
},
$card6Handler = function() {
$contain.addClass('displayed');
setTimeout(() => $lgCard6.addClass('displayed'), 200);
$esc6.on('click', $esc6Handler);
$card1.off('click');
$card2.off('click');
$card3.off('click');
$card4.off('click');
$card5.off('click');
};
const $esc1Handler = function () {
$lgCard1.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
$card2.on('click', $card2Handler);
$card3.on('click', $card3Handler);
$card4.on('click', $card4Handler);
$card5.on('click', $card5Handler);
$card6.on('click', $card6Handler);
$esc1.off('click');
},
$esc2Handler = function () {
$lgCard2.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
$card1.on('click', $card1Handler);
$card3.on('click', $card3Handler);
$card4.on('click', $card4Handler);
$card5.on('click', $card5Handler);
$card6.on('click', $card6Handler);
$esc2.off('click');
},
$esc3Handler = function () {
$lgCard3.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
$card1.on('click', $card1Handler);
$card2.on('click', $card2Handler);
$card4.on('click', $card4Handler);
$card5.on('click', $card5Handler);
$card6.on('click', $card6Handler);
$esc3.off('click');
},
$esc4Handler = function () {
$lgCard4.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
$card1.on('click', $card1Handler);
$card2.on('click', $card2Handler);
$card3.on('click', $card3Handler);
$card5.on('click', $card5Handler);
$card6.on('click', $card6Handler);
$esc4.off('click');
},
$esc5Handler = function () {
$lgCard5.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
$card1.on('click', $card1Handler);
$card2.on('click', $card2Handler);
$card3.on('click', $card3Handler);
$card4.on('click', $card4Handler);
$card6.on('click', $card6Handler);
$esc6.off('click');
},
$esc6Handler = function () {
$lgCard6.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
$card1.on('click', $card1Handler);
$card2.on('click', $card2Handler);
$card3.on('click', $card3Handler);
$card4.on('click', $card4Handler);
$card5.on('click', $card5Handler);
$esc6.off('click');
};
$card1.on('click', $card1Handler);
$card2.on('click', $card2Handler);
$card3.on('click', $card3Handler);
$card4.on('click', $card4Handler);
$card5.on('click', $card5Handler);
$card6.on('click', $card6Handler);
} else {
/* $lgCard1.removeClass('displayed');
$lgCard2.removeClass('displayed');
$lgCard3.removeClass('displayed');
$lgCard4.removeClass('displayed');
$lgCard5.removeClass('displayed');
$lgCard6.removeClass('displayed');
$contain.removeClass('displayed'); */
};
});
export default sponsorQry;
/* $card2.on('click', () => {
$contain.addClass('displayed');
setTimeout(() => $lgCard2.addClass('displayed'), 200);
});
$esc2.on('click', () => {
$lgCard2.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
});
$card3.on('click', () => {
$contain.addClass('displayed');
setTimeout(() => $lgCard3.addClass('displayed'), 200);
});
$esc3.on('click', () => {
$lgCard3.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
});
$card4.on('click', () => {
$contain.addClass('displayed');
setTimeout(() => $lgCard4.addClass('displayed'), 200);
});
$esc4.on('click', () => {
$lgCard4.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
});
$card5.on('click', () => {
$contain.addClass('displayed');
setTimeout(() => $lgCard5.addClass('displayed'), 200);
});
$esc5.on('click', () => {
$lgCard5.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
});
$card6.on('click', () => {
$contain.addClass('displayed');
setTimeout(() => $lgCard6.addClass('displayed'), 200);
});
$esc6.on('click', () => {
$lgCard6.removeClass('displayed');
setTimeout(() => $contain.removeClass('displayed'), 500);
}); */<file_sep>export default class TriviaClass {
constructor(_quest, _ansA, _ansB, _ansC, _ansD, _correct) {
this.question = _quest;
this.answers = {
a: _ansA,
b: _ansB,
c: _ansC,
d: _ansD
};
this.correctAnswer = _correct
}
}
<file_sep>
// timer
import timer from './modules/index/timer.js';
timer();
// trivia quiz
import { triviaQuestions } from '/modules/trivia/triviaQuestions.js'
import quiz from './modules/trivia/trivia.js';
quiz()
// frame module
import {
frame
} from './modules/frame.js';
// scroll effect module
import scroll from './modules/index/scrollEffect.js';<file_sep>export const frame = window.onload = $(() => {
const $lCorner = document.querySelector('.topLeftCorner');
const $rCorner = document.querySelector('.topRightCorner');
/* --------------------------------- mobile --------------------------------- */
/* ---------------------------- mobile variables ---------------------------- */
const $mobNavUl = $('.mobNavUL');
const $mobNavLi = document.querySelectorAll('.mobNavLI');
const $drop = $('.dropDownMenu');
const $hamburger = document.querySelector('.ham');
const vh = $(window).height() / 100;
const vw = $(window).width() / 100;
const tWdXxs = vw - 60;
/* -------------------------------- functions ------------------------------- */
//mbile ham class toggle
const hamClassToggle = () => {
$hamburger.classList.toggle('hamShown');
$hamburger.classList.toggle('hamCollapsed');
};
$hamburger.addEventListener('click', () => {
$hamburger.classList.toggle('hamShown');
$hamburger.classList.toggle('hamCollapsed');
});
$drop.on('click', () => {
$hamburger.classList.toggle('hamShown');
$hamburger.classList.toggle('hamCollapsed');
});
// corner class toggler
const trnsfmCorners = () => {
$lCorner.classList.toggle('notCollapsed');
$lCorner.classList.toggle('isCollapsed');
$rCorner.classList.toggle('notCollapsed');
$rCorner.classList.toggle('isCollapsed');
};
/* ------------------------ general event listenters ------------------------ */
// menu EventListeners
$hamburger.addEventListener('hover', trnsfmCorners);
$hamburger.addEventListener('click', trnsfmCorners);
$hamburger.addEventListener('focus', trnsfmCorners);
$drop.on('hover', trnsfmCorners);
$drop.on('click', trnsfmCorners);
$drop.on('focus', trnsfmCorners);
$mobNavLi.forEach((event) => {
event.addEventListener('hover', trnsfmCorners);
event.addEventListener('click', trnsfmCorners);
event.addEventListener('focus', trnsfmCorners);
event.addEventListener('hover', hamClassToggle);
event.addEventListener('click', hamClassToggle);
event.addEventListener('focus', hamClassToggle);
});
});<file_sep>// import TriviaClass from './triviaClass.js';
export class TriviaClass {
constructor(_quest, _ansA, _ansB, _ansC, _ansD, _correct) {
this.question = _quest;
this.answers = {
a: _ansA,
b: _ansB,
c: _ansC,
d: _ansD
};
this.correctAnswer = _correct
}
}
export const triviaQuestions = [
new TriviaClass("When was the first Mardi Gras ?",
"Feb. 24, 1857",
"Nov. 3, 1957",
"Mar. 15, 1875",
"Feb. 26, 1668",
"A"),
new TriviaClass("What the Mardi Gras colors stand for?",
"Purple for wine, green - nature, and gold for wealth",
"Purple for HackerU, green - Haifa, and gold for shiny things",
" Purple for justice, green - faith, and gold for power",
"Purple for fairness, green - envy, and yellow for intimidation",
"C"),
new TriviaClass("What is Twelfth Night?",
"It's the official ending of Mardi Gras",
"It's on January 6th and is the official start of Mardi Gras",
"It's always between February 18th and March 8th",
"It's the birthday of St. Mardi Gras of course!",
"B"),
new TriviaClass('Since when have "throws" been around?',
"Since the 1970s",
"Since the 1760s",
"Since the 1930s",
"Since the 1870s",
"D"),
new TriviaClass("Who first broadcast Mardi Gras LIVE on the Internet?",
"MardiGrasNewOrleans.com",
"NBC News",
"i24news.com",
"NatGeo Travel",
"A"),
new TriviaClass("How much does it cost to go to Mardi Gras?",
"60 Mardi Gras beads",
"5 USD for an adult",
"50 USD for an adult",
"It's free!",
"D"),
new TriviaClass("When is <NAME>?",
"Could be any Sunday between March 23 and April 25",
"Could be any Tuesday between March 14 and April 16",
"Always 47 days before Easter",
"Answers A and C are both correct",
"D"),
new TriviaClass("What is Fat Tuesday?",
"The day when food is free all over New Orleans",
"It symbolizes the hunger in which the first colonists of the city were in",
"It's the English meaning for 'Mardi Gras'",
"A fasting day to help the people of the city stay healthy",
"C"),
new TriviaClass("What is Lundi Gras?",
"The event where the king is chosen",
"The closing event of the holiday",
"A series of Shrove Monday events at Woldenberg Park",
"St. Mardi Gras' day of baptism of course!",
"C"),
new TriviaClass("When was New Orleans established?",
"1718",
"1892",
"1755",
"1649",
"A"),
]<file_sep>const renderQuestions = (_app, _arr, _data) => {
_app.innerHTML = `
<div id="quizCard" class="mx-auto border rounded col-12 col-sm-6 col-lg-5 col-xl-4 bg-light">
<form id="triviaForm" method="post" class="mt-3 "></form>
</div>
<div class="escRow">
<div id="esc" class="escElement"><img src="./css/Images/vectorObjects/EscBtn.png" alt="Escape Button"></div>
</div>`
const quizCard = document.querySelector('#quizCard');
const theForm = document.querySelector('#triviaForm');
_data.forEach((_quest, _index, _ar) => {
theForm.innerHTML += `
<div id="Q${_index + 1}" class="form-group border-bottom pb-4">
<h4 class="mb-3">${_index + 1}. ${_quest.question} </h4>
<ul class="answers list-group list-unstyled mt-2">
<li class="list-group-item">
<label for="Q${_index + 1}A"
class="mb-0 ml-2"><input type="radio" name="Q${_index + 1}" id="Q${_index + 1}A" value="A"> A : ${_quest.answers.a}</label>
</li>
<li class="list-group-item">
<label for="Q${_index + 1}B"
class="mb-0 ml-2"><input type="radio" name="Q${_index + 1}" id="Q${_index + 1}B" value="B"> B : ${_quest.answers.b}</label>
</li>
<li class="list-group-item">
<label for="Q${_index + 1}C"
class="mb-0 ml-2"><input type="radio" name="Q${_index + 1}" id="Q${_index + 1}C" value="C"> C : ${_quest.answers.c}</label>
</li>
<li class="list-group-item">
<label for="Q${_index + 1}D"
class="mb-0 ml-2"><input type="radio" name="Q${_index + 1}" id="Q${_index + 1}D" value="D"> D : ${_quest.answers.d}</label>
</li>
</ul>
</div>`;
_arr.push(document.querySelector(`#Q${_index + 1}${_quest.correctAnswer}`))
});
quizCard.innerHTML += `<div class= "my-2 text-center">
<button id="submit" class="btn btn-success">Submit Quiz!</button>
</div>`;
}
export default renderQuestions;<file_sep>class Handlers {
constructor(_starter) {
this.activateQuiz = (_app) => {
_starter.onclick = () => _app.classList.replace('inactive', 'active');
}
this.quitQuiz = (_app) => {
_starter.onclick = () => _app.classList.replace('active', 'inactive');
}
// this.backBtnHndlr = () => {
// document.querySelector('#back').onclick = () => {
// }
// }
}
};
export default Handlers;
<file_sep>export const gallery = window.onload = $(() => {
/* const vh = $(window).height() / 100;
const vw = $(window).width() / 100; */
const $img1 = $('.slide1 img');
const $img2 = $('.slide2 img');
const $img3 = $('.slide3 img');
const $img4 = $('.slide4 img');
const $img5 = $('.slide5 img');
if ($(window).width() >= 992) {
$img1.attr('src', './css/Images/gallery/AyaSalmanCorner(3).jpg')
$img2.attr('src', './css/Images/gallery/Mathieu-ChezeNecklace(3).jpg')
$img3.attr('src', './css/Images/gallery/philipstrongPhone(3).jpg')
$img4.attr('src', './css/Images/gallery/pexelsHelenaJankovičováKováčová(3).jpg')
$img5.attr('src', './css/Images/gallery/ThomasParkUmbrella(3).jpg')
} else if ($(window).width() >= 768) {
$img1.attr('src', './css/Images/gallery/AyaSalmanCorner(2).jpg')
$img2.attr('src', './css/Images/gallery/Mathieu-ChezeNecklace(2).jpg')
$img3.attr('src', './css/Images/gallery/philipstrongPhone(2).jpg')
$img4.attr('src', './css/Images/gallery/pexelsHelenaJankovičováKováčová(2).jpg')
$img5.attr('src', './css/Images/gallery/ThomasParkUmbrella(2).jpg')
} else {
$img1.attr('src', './css/Images/gallery/AyaSalmanCorner(1).jpg')
$img2.attr('src', './css/Images/gallery/Mathieu-ChezeNecklace(1).jpg')
$img3.attr('src', './css/Images/gallery/philipstrongPhone(1).jpg')
$img4.attr('src', './css/Images/gallery/pexelsHelenaJankovičováKováčová(1).jpg')
$img5.attr('src', './css/Images/gallery/ThomasParkUmbrella(1).jpg')
};
});<file_sep>export default window.onload = function printTime() {
const now = new Date();
const nowYear = now.getFullYear();
const nowMonth = now.getMonth() + 1;
const nowDate = now.getDate();
const endTime = (date, month) => {
let endYear;
if (nowMonth >= month && nowDate >= date) {
endYear = nowYear + 1;
} else {
endYear = nowYear;
}
return new Date(`${month}/${date}/${endYear}`);
}
const elapsed = {
ms() {
return endTime(1, 3).getTime() - now.getTime();
},
secs() {
return Math.floor((this.ms() / 60000 - Math.floor(this.ms() / 60000)) * 60);
},
mins() {
return Math.floor((this.ms() / 3600000 - Math.floor(this.ms() / 3600000)) * 60);
},
hs() {
return Math.floor((this.ms() / 86400000 - Math.floor(this.ms() / 86400000)) * 24);
},
days() {
return Math.floor(this.ms() / 86400000);
}
};
let secs;
let mins;
let hs;
let days;
if (elapsed.secs() < 10) {
secs = `0${elapsed.secs()}`
} else {
secs = elapsed.secs()
};
if (elapsed.mins() < 10) {
mins = `0${elapsed.mins()}`
} else {
mins = elapsed.mins()
};
if (elapsed.hs() < 10) {
hs = `0${elapsed.hs()}`
} else {
hs = elapsed.hs()
};
if (elapsed.days() < 10) {
days = `00${elapsed.days()}`
} else if (elapsed.days() < 100) {
days = `0${elapsed.days()}`
} else {
days = elapsed.days()
};
document.querySelector('.days .value').innerHTML = `<span>${days}</span>`;
document.querySelector('.hours .value').innerHTML = `<span>${hs}</span>`;
document.querySelector('.mins .value').innerHTML = `<span>${mins}</span>`;
document.querySelector('.secs .value').innerHTML = `<span>${secs}</span>`;
let inter = setTimeout(printTime, 1000);
};<file_sep>export default window.onload = $(() => {
let $imgs = $(`.galleryPicsSm .galItem`);
$imgs.each((index) => {
$imgs[index].onclick = () => {
$('.galleryPicsLg').addClass('displayed');
setTimeout(() => $(`.galItemLg.galItem${index + 1}`).addClass('displayed'), 200);
if ($('.topRightCorner')[0].classList.contains('notScrolled')) {
$('.topRightCorner')[0].classList.replace('notScrolled', 'isScrolled');
$('.topLeftCorner')[0].classList.replace('notScrolled', 'isScrolled');
};
$(`.galleryPicsLg .galItemLg .escElement img`).on('click', () => {
$(`.galItemLg.galItem${index + 1}`).removeClass('displayed');
if ($('.topRightCorner')[0].classList.contains('isScrolled')) {
$('.topRightCorner')[0].classList.replace('isScrolled', 'notScrolled');
$('.topLeftCorner')[0].classList.replace('isScrolled', 'notScrolled');
}
setTimeout(() => $('.galleryPicsLg').removeClass('displayed'), 500);
$(`.galItemLg .escElement:nth-of-type(${index + 1}) img`).off('click');
});
};
});
});
// export default gallery;
/* if ($('.topRightCorner')[0].classList.contains('notScrolled')) {
$('.topRightCorner')[0].classList.replace('notScrolled', 'isScrolled');
$('.topLeftCorner')[0].classList.replace('notScrolled', 'isScrolled');
}; */
/* if ($('.topRightCorner')[0].classList.contains('isScrolled')) {
$('.topRightCorner')[0].classList.replace('isScrolled', 'notScrolled');
$('.topLeftCorner')[0].classList.replace('isScrolled', 'notScrolled');
}; */<file_sep>import { triviaQuestions } from './triviaQuestions.js';
export default window.onload = async () => {
body.innerHTML += `<div id="quiz" class="inactive"></div>`;
const quizApp = document.querySelector('#quiz');
const activate = document.querySelector("#triviaActivate");
let crtAns = [];
let currentRank = 100;
renderQuestions(quizApp, crtAns, triviaQuestions, currentRank);
activateQuiz(quizApp, activate);
}
const renderQuestions = (_app, _arr, _data, _num) => {
_app.innerHTML = `
<div id="quizCard" class="mx-auto border rounded col-12 col-sm-6 col-lg-5 col-xl-4 bg-light">
<form id="triviaForm" method="post" class="mt-3 "></form>
</div>
<div class="escRow">
<div id="esc" class="escElement"><img src="./css/Images/vectorObjects/EscBtn.png" alt="Escape Button"></div>
</div>`;
const quizCard = document.querySelector('#quizCard');
const quizForm = document.querySelector('#triviaForm');
_data.forEach((_quest, _index, _ar) => {
quizForm.innerHTML += `
<div id="Q${_index + 1}" class="form-group border-bottom pb-4">
<h4 class="mb-3">${_index + 1}. ${_quest.question} </h4>
<ul class="answers list-group list-unstyled mt-2">
<li class="list-group-item">
<label for="Q${_index + 1}A"
class="mb-0 ml-2"><input type="radio" name="Q${_index + 1}" id="Q${_index + 1}A" value="A"> A : ${_quest.answers.a}</label>
</li>
<li class="list-group-item">
<label for="Q${_index + 1}B"
class="mb-0 ml-2"><input type="radio" name="Q${_index + 1}" id="Q${_index + 1}B" value="B"> B : ${_quest.answers.b}</label>
</li>
<li class="list-group-item">
<label for="Q${_index + 1}C"
class="mb-0 ml-2"><input type="radio" name="Q${_index + 1}" id="Q${_index + 1}C" value="C"> C : ${_quest.answers.c}</label>
</li>
<li class="list-group-item">
<label for="Q${_index + 1}D"
class="mb-0 ml-2"><input type="radio" name="Q${_index + 1}" id="Q${_index + 1}D" value="D"> D : ${_quest.answers.d}</label>
</li>
</ul>
</div>`;
_arr.push(document.querySelector(`#Q${_index + 1}${_quest.correctAnswer}`));
});
quizCard.innerHTML += `<div class= "my-2 text-center">
<button id="submit" class="btn btn-success">Submit Quiz!</button>
</div>`;
const esc = document.querySelector("#quiz #esc");
esc.addEventListener("click", () => {
_app.classList.replace('active', 'inactive');
_app.innerHTML = '';
renderQuestions(_app, _arr, _data);
})
const subQuiz = document.querySelector('#submit');
showResult(subQuiz, _app, _data, _num, _arr);
};
const showResult = (_btn, _app, _data, _num, _arr) => {
_btn.onclick = () => {
const answerContainers = _app.querySelectorAll('.answers');
_data.forEach((_quest, _index) => {
const answerContainer = answerContainers[_index];
const selector = `input[name="Q${_index + 1}"]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
if (userAnswer !== _quest.correctAnswer) {
_num -= 10;
}
})
result.ranker(_num);
renderResult(quizCard, result, _num,);
let back = document.querySelector('#back')
backBtnHandler(_app, back, _arr, _data)
}
_num = 100;
};
const result = {
ranker(_num) {
if (_num < 50) {
this.header = 'Awwww You Failed...';
this.sub = "Try again next Time!";
this.rank = _num;
this.bgc = "danger";
} else if (_num < 70) {
this.header = "Passed by a Notch!";
this.sub = "You can do better!";
this.rank = _num;
this.bgc = "warning";
} else if (_num < 80) {
this.header = "Ok, Cool!";
this.sub = "You know stuff don't you..";
this.rank = _num;
this.bgc = "info";
} else if (_num < 90) {
this.header = "Not Bad!";
this.sub = "You know the materia mon ami";
this.rank = _num;
this.bgc = "info";
} else if (_num < 100) {
this.header = "Very Good!";
this.sub = "How many Goolges did you do??";
this.rank = _num;
this.bgc = "success";
} else if (_num = 100) {
this.header = "Douze Points!! (Actually 100)";
this.sub = "You are our King Rex! Don't forget ;that";
this.rank = _num;
this.bgc = "success";
}
}
};
const renderResult = (_div, _obj, _score) => {
_div.innerHTML = `
<div id="resultsContain">
<div class="jumbotron bg-${_obj.bgc} text-light text-center w-100">
<h1 class="display-4">${_obj.header}</h1>
<h5 class="lead mb-5">${_obj.sub}</h5>
<h5 class="lead mb-5">Score: ${_score}</h5>
<button id="back" class="btn btn-dark btn-lg">Back to Website</button>
</div>
</div>`;
};
const activateQuiz = (_app, _starter) => {
_starter.onclick = () => {
_app.classList.replace('inactive', 'active');
}
}
const backBtnHandler = (_app, _btn, _arr, _data) => {
_btn.addEventListener("click", () => {
_app.classList.replace('active', 'inactive');
_app.innerHTML = '';
renderQuestions(_app, _arr, _data);
})
}<file_sep># MardiGras
My first front-end project containing implementations of Vanilla JS/HTML5/CSS3(SCSS), JQuery, Bootstrap 4.
Deployed site: mardi-gras-yotam-aran.netlify.app
<file_sep>const showResult = () => {
const answerContainers = quizApp.querySelectorAll('.answers');
triviaQuestions.forEach((_quest, _index) => {
const answerContainer = answerContainers[_index];
const selector = `input[name="Q${_index + 1}"]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
console.log(_quest.correctAnswer)
if (userAnswer !== _quest.correctAnswer) {
currentRank -= 10;
}
})
result.ranker(currentRank);
renderResult(quizCard, result);
click.backBtnHndlr()
}
export default showResult;<file_sep>const scrollEffect = window.scrollEffect = $(() => {
const $lCorner = document.querySelector('.topLeftCorner');
const $rCorner = document.querySelector('.topRightCorner');
const vh = $(window).height() / 100;
const vw = $(window).width() / 100;
const tWdXxs = vw - 60;
$(window).on('scroll', () => {
if ($(window).width() >= 1200 && $(window).scrollTop() >= ($(window).height())) {
$lCorner.classList.replace('notScrolled', 'isScrolled');
$rCorner.classList.replace('notScrolled', 'isScrolled');
} else if ($(window).width() >= 992 && $(window).scrollTop() >= (vh * 44)) {
$lCorner.classList.replace('notScrolled', 'isScrolled');
$rCorner.classList.replace('notScrolled', 'isScrolled');
} else if ($(window).width() >= 768 && $(window).scrollTop() >= (vh * 44)) {
$lCorner.classList.replace('notScrolled', 'isScrolled');
$rCorner.classList.replace('notScrolled', 'isScrolled');
} else if ($(window).width() >= 375 && $(window).scrollTop() >= (vh * 40 - 165)) {
$lCorner.classList.replace('notScrolled', 'isScrolled');
$rCorner.classList.replace('notScrolled', 'isScrolled');
} else if ($(window).width() <= 374 && $(window).scrollTop() > 0 && $(window).scrollTop() > tWdXxs * 20 / 9 - 165) {
$lCorner.classList.replace('notScrolled', 'isScrolled');
$rCorner.classList.replace('notScrolled', 'isScrolled');
} else {
$lCorner.classList.replace('isScrolled', 'notScrolled');
$rCorner.classList.replace('isScrolled', 'notScrolled');
};
});
});
export default scrollEffect; | be29bd236327ce7ed9aabac9ba9f48c587320d1a | [
"JavaScript",
"Markdown"
] | 15 | JavaScript | YotQues/MardiGras | 06d2adb5f17e8cc733fe571ac59cd76c217404ae | d597636ce8463e2498189324dd88cca40adc7f11 |
refs/heads/master | <repo_name>zhangjiantao/NXDNS<file_sep>/nxdns.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import logging
import struct
import socket
import psutil
if sys.version_info.major == 2:
import thread
import SocketServer
else:
import _thread as thread
import socketserver as SocketServer
# DNS Query
class SinDNSQuery:
def __init__(self, data):
i = 1
self.name = ''
while True:
d = ord(data[i])
if d == 0:
break
if d < 32:
self.name = self.name + '.'
else:
self.name = self.name + chr(d)
i = i + 1
self.querybytes = data[0:i + 1]
(self.type, self.classify) = struct.unpack('>HH', data[i + 1:i + 5])
self.len = i + 5
def getbytes(self):
return self.querybytes + struct.pack('>HH', self.type, self.classify)
# DNS Answer RRS
# this class is also can be use as Authority RRS or Additional RRS
class SinDNSAnswer:
def __init__(self, ip):
self.name = 49164
self.type = 1
self.classify = 1
self.timetolive = 190
self.datalength = 4
self.ip = ip
def getbytes(self):
res = struct.pack('>HHHLH', self.name, self.type, self.classify, self.timetolive, self.datalength)
s = self.ip.split('.')
res = res + struct.pack('BBBB', int(s[0]), int(s[1]), int(s[2]), int(s[3]))
return res
# DNS frame
# must initialized by a DNS query frame
class SinDNSFrame:
def __init__(self, data):
(self.id, self.flags, self.quests, self.answers, self.author, self.addition) = struct.unpack('>HHHHHH',
data[0:12])
self.query = SinDNSQuery(data[12:])
def getname(self):
return self.query.name
def setip(self, ip):
self.answer = SinDNSAnswer(ip)
self.answers = 1
self.flags = 33152
def getbytes(self):
res = struct.pack('>HHHHHH', self.id, self.flags, self.quests, self.answers, self.author, self.addition)
res = res + self.query.getbytes()
if self.answers != 0:
res = res + self.answer.getbytes()
return res
# A UDPHandler to handle DNS query
class SinDNSUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
dns = SinDNSFrame(data)
namemap = SinDNSServer.namemap
if dns.query.type == 1:
# If this is query a A record, then response it
name = dns.getname()
toip = None
ifrom = "map"
if namemap.__contains__(name):
# If have record, response it
toip = namemap[name]
elif namemap.__contains__('*'):
# Response default address
toip = namemap['*']
else:
# ignore it
try:
toip = socket.getaddrinfo(name, 0)[0][4][0]
ifrom = "sev"
except Exception as e:
logging.error(e)
if toip:
dns.setip(toip)
logging.info('[DNS] %s: %s --> %s (%s)' % (self.client_address[0], name, toip, ifrom))
self.request[1].sendto(dns.getbytes(), self.client_address)
else:
self.request[1].sendto(data, self.client_address)
# DNS Server
# It only support A record query
# user it, U can create a simple DNS server
class SinDNSServer:
def __init__(self, addr='0.0.0.0', port=53):
SinDNSServer.namemap = {}
self.addr = addr
self.port = port
def addname(self, name, ip):
SinDNSServer.namemap[name] = ip
logging.info('[DNS] bind addr %s to %s' % (name, ip))
def start(self):
logging.info('[DNS] start dns server on %s:%d' % (self.addr, self.port))
server = SocketServer.UDPServer((self.addr, self.port), SinDNSUDPHandler)
server.serve_forever()
# A TCPHandler to handle HTTP request
class SinHTTPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(1024).strip().decode('utf-8')
logging.info('[HTTP] request from (%r):%r' % (self.client_address, data))
if data.find('Host: conntest.nintendowifi.net\r\n') != -1:
response_body = '''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>HTML Page</title>
</head>
<body bgcolor="#FFFFFF">
This is test.html page
</body>
</html>
'''
elif data.find('Host: ctest.cdn.nintendo.net\r\n') != -1:
response_body = 'ok'
else:
response_body = '''What's your problem?'''
response_headers = 'HTTP/1.0 200 OK\r\nContent-Length: %d\r\n' % len(response_body)
response_headers += 'Content-Type: text/html\r\nX-Organization: Nintendo\r\n\r\n'
response = response_headers + response_body
self.request.sendall(response.encode('utf-8'))
# HTTP Server
class SinHTTPServer:
def __init__(self, addr='0.0.0.0', port=80):
self.addr = addr
self.port = port
def start(self):
logging.info('[HTTP] start http server on %s:%d' % (self.addr, self.port))
server = SocketServer.TCPServer((self.addr, self.port), SinHTTPHandler)
server.serve_forever()
# PSUTIL
class psutils:
@staticmethod
def get_active_netcards():
netcard_info = []
info = psutil.net_if_addrs()
for k,v in info.items():
for item in v:
if item[0] == 2 and item[1] != '127.0.0.1' and item[1][:8] != '169.254.':
netcard_info.append((k,item[1]))
return netcard_info
@staticmethod
def get_addr():
info = psutils.get_active_netcards()
if len(info) == 1:
return info[0][1];
else:
while True:
for i in range(len(info)):
print(" <%d>: %s %s" % (i, info[i][1], info[i][0]))
id = input('which? >')
try:
idx = int(id)
if idx < len(info):
return info[idx][1]
except:
pass
def StartDNSServer(addr, port):
sev = SinDNSServer(addr, port)
sev.addname('*', '0.0.0.0') # block all
sev.addname('ctest.cdn.nintendo.net', addr) # add a A record
sev.addname('conntest.nintendowifi.net', addr) # add a A record
sev.addname('test.test.test', addr) # add a A record
sev.addname('test.test', addr) # add a A record
sev.start()
def StartHTTPServer(addr, port):
sev = SinHTTPServer(addr, port)
sev.start()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
try:
addr = psutils.get_addr()
logging.info("start on %s" % addr)
thread.start_new_thread(StartDNSServer, (addr, 53)) # start DNS server
thread.start_new_thread(StartHTTPServer, (addr, 80)) # start HTTP server
except Exception as e:
logging.error(e)
while True:
pass
<file_sep>/README.md
# NXDNS
DNS/HTTP server for blocking all Nintendo servers.
| 55f1f9644d5e3f58f90939f5b2f40443e1a37abc | [
"Markdown",
"Python"
] | 2 | Python | zhangjiantao/NXDNS | 10072b0b923f653326bb2326d60eba41d2fe5336 | 23971f894121dca452c794ee27f6b91702f71450 |
refs/heads/master | <file_sep>package attractions;
import people.Visitor;
import behaviours.ISecurity;
public class Playground extends Attraction implements ISecurity {
public Playground(String name, int rating) {
super(name, rating);
}
@Override
public boolean isAllowedTo(Visitor visitor){
if(visitor.getAge() < 16) return true;
return false; }
}
| 66aa19b4b19a9300857824e406e4891e77ed9955 | [
"Java"
] | 1 | Java | jackaquigley/ThemePark | c53ebc095b9080f68459997d956b477788d42c86 | 5ed8f7126ca80726a2568967ff694ccc90ae5ffc |
refs/heads/master | <repo_name>ironfroggy/Culet<file_sep>/culet/anycontent/views.py
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.contenttypes.models import ContentType
from culet.anycontent.models import Header, content_classes
from culet.anycontent.forms import AnyContentForm
def list(request):
all = Header.objects.all()
return render_to_response(
"anycontent/list.html",
RequestContext(request, {"posts": all}))
def read(request, slug):
header = Header.objects.get(slug=slug)
content = header.content
return render_to_response(
"anycontent/read.html",
RequestContext(request, {
"header": header,
"content": content,
})
)
def post(request, content_type_name=None):
if content_type_name is None:
forms = []
else:
forms = AnyContentForm(request, content_type_name)
posttypes = [
{
'name': t['name'],
'content_type_id': ContentType.objects.get_for_model(t['model']).id,
'content_type_name': t['name'],
}
for t in content_classes
]
return render_to_response(
"anycontent/form.html",
RequestContext(request, {"forms": forms, "posttypes": posttypes}))
<file_sep>/culet/roles/migrations/0001_initial.py
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Role'
db.create_table('roles_role', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('role_group', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.Group'])),
))
db.send_create_signal('roles', ['Role'])
# Adding model 'RoleAction'
db.create_table('roles_roleaction', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('role', self.gf('django.db.models.fields.related.ForeignKey')(related_name='actions', to=orm['roles.Role'])),
('action_module', self.gf('django.db.models.fields.CharField')(max_length=300)),
('action_class', self.gf('django.db.models.fields.CharField')(max_length=100)),
))
db.send_create_signal('roles', ['RoleAction'])
# Adding model 'ModelPermission'
db.create_table('roles_modelpermission', (
('role_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['roles.Role'], unique=True, primary_key=True)),
('model', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])),
))
db.send_create_signal('roles', ['ModelPermission'])
# Adding model 'ItemPermission'
db.create_table('roles_itempermission', (
('role_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['roles.Role'], unique=True, primary_key=True)),
('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])),
('object_id', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('roles', ['ItemPermission'])
def backwards(self, orm):
# Deleting model 'Role'
db.delete_table('roles_role')
# Deleting model 'RoleAction'
db.delete_table('roles_roleaction')
# Deleting model 'ModelPermission'
db.delete_table('roles_modelpermission')
# Deleting model 'ItemPermission'
db.delete_table('roles_itempermission')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'roles.itempermission': {
'Meta': {'object_name': 'ItemPermission', '_ormbases': ['roles.Role']},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'object_id': ('django.db.models.fields.IntegerField', [], {}),
'role_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['roles.Role']", 'unique': 'True', 'primary_key': 'True'})
},
'roles.modelpermission': {
'Meta': {'object_name': 'ModelPermission', '_ormbases': ['roles.Role']},
'model': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'role_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['roles.Role']", 'unique': 'True', 'primary_key': 'True'})
},
'roles.role': {
'Meta': {'object_name': 'Role'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'role_group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.Group']"})
},
'roles.roleaction': {
'Meta': {'object_name': 'RoleAction'},
'action_class': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'action_module': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'role': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actions'", 'to': "orm['roles.Role']"})
}
}
complete_apps = ['roles']
<file_sep>/testproject/templates/culet/myselves.html
<html>
<body>
<ul>
<li>Master User: <a href="{% url personality-become master_user.username %}">{{ master_user.username }}</a></li>
<li>Current: {{ current_user.username }}</li>
{% for personality in personalities %}
<li><a href="{% url personality-become personality.username %}">{{ personality.username }}</a></li>
{% endfor %}
</ul>
</body>
</html>
<file_sep>/culet/personality/forms.py
from django import forms
from django.contrib.auth.models import User
from culet.personality.models import Personality
class PersonalityForm(forms.Form):
personality_name = forms.CharField()
def __init__(self, request, *args, **kwargs):
self.request = request
super(PersonalityForm, self).__init__(*args, **kwargs)
def save(self):
master_user = self.request.user.master_user
self.instance = Personality.objects.create(
username=self.cleaned_data['personality_name'],
master_user=master_user
)
return True
def clean_personality_name(self):
name = self.cleaned_data['personality_name']
if User.objects.filter(username=name).count():
raise forms.ValidationError("Username is already taken. Please choose another.")
return name
<file_sep>/culet/personality/tests.py
import unittest
import mock
from django.contrib.auth.models import User
from culet.personality.models import Personality
from culet.personality.views import _viewier_dec, viewier, become, SuspicionError, SuspicionError_Permission, SuspicionError_Invalid
class PersonalityTest(unittest.TestCase):
setupalready = False
def setUp(self):
if not self.setupalready:
PersonalityTest.setupalready = True
self.oneTimeSetUp()
self.one = User.objects.get(username='one')
self.two = User.objects.get(username='two')
def oneTimeSetUp(self):
user = User.objects.create(username="one")
Personality.objects.create_for(user, "one-A")
Personality.objects.create_for(user, "one-B")
user = User.objects.create(username="two")
Personality.objects.create_for(user, "two-A")
Personality.objects.create_for(user, "two-B")
def test_getPersonalitiesOfUser(self):
self.assertEqual(2, self.one.personalities.count())
alts = set(alt.username for alt in self.one.personalities.all())
self.assertEqual(alts, set(('one-A', 'one-B')))
def test_getAlternates(self):
A = self.one.personalities.get(username='one-A')
alts = Personality.objects.alternates_of(A)
self.assertEqual(1, alts.count())
self.assertEqual("one-B", alts[0].username)
class ViewierTest(unittest.TestCase):
def test_handlesSuspicion(self):
request = mock.Mock()
user = mock.Mock()
def suspicious_function(request):
raise SuspicionError("test", user)
@apply
@mock.patch("culet.personality.views.render_to_response")
def _(render_to_response):
decorated = _viewier_dec(suspicious_function, "nothing.html")
result = decorated(request)
assert render_to_response.called_with("culet/error.html")
def test_usesTemplate(self):
request = mock.Mock()
user = mock.Mock()
def view(request):
return {
'ctx':{
'x': 123,
}
}
@apply
@mock.patch("culet.personality.views.render_to_response")
def _(render_to_response):
decorated = _viewier_dec(view, "the_template.html")
result = decorated(request)
assert render_to_response.called_with("the_template.html")
assert render_to_response.call_args[0][1]['x'] == 123
class MockSession(mock.Mock):
def __contains__(self, key):
return hasattr(self, key)
def __getitem__(self, key):
return getattr(self, key)
def __setitem__(self, key, value):
return setattr(self, key, value)
class BecomeTest(unittest.TestCase):
def test_refuseNonexistantUser(self):
request = mock.Mock()
def raise_user_doesnotexist(*args, **kwargs):
assert kwargs['username'] == 'alt1'
raise User.DoesNotExist()
request.session = MockSession()
request.session.SESSION_KEY = 'THE_KEY'
request.user = mock.Mock(spec=['personalities'])
request.user.is_anonymous = mock.Mock(return_value=False)
personality_get = request.user.personalities.get
personality_get.side_effect = raise_user_doesnotexist
self.assertRaises(SuspicionError_Invalid, become.wrapped, request, "alt1")
def test_refuseUnpermittedUser(self):
request = mock.Mock()
def raise_user_doesnotexist(*args, **kwargs):
assert kwargs['username'] == 'alt1'
raise User.DoesNotExist()
request.session = MockSession()
request.session.SESSION_KEY = 'THE_KEY'
request.user = mock.Mock(spec=['personalities'])
request.user.is_anonymous = mock.Mock(return_value=False)
personality_get = request.user.personalities.get
personality_get.side_effect = raise_user_doesnotexist
@apply
@mock.patch("django.contrib.auth.models.User.objects.get")
@mock.patch("django.contrib.auth.models.User.objects.filter")
def _(user_filter, user_get):
user_filter.return_value = mock.Mock()
user_filter.return_value.count = mock.Mock(return_value=1)
self.assertRaises(SuspicionError_Permission, become.wrapped, request, "alt1")
def test_refuseUnpermittedUser(self):
request = mock.Mock()
def raise_user_doesnotexist(*args, **kwargs):
assert kwargs['username'] == 'alt1'
raise User.DoesNotExist()
request.session = MockSession()
request.session.SESSION_KEY = 'THE_KEY'
request.user = mock.Mock(spec=['personalities'])
request.user.is_anonymous = mock.Mock(return_value=True)
personality_get = request.user.personalities.get
personality_get.side_effect = raise_user_doesnotexist
@apply
@mock.patch("django.contrib.auth.models.User.objects.get")
@mock.patch("django.contrib.auth.models.User.objects.filter")
def _(user_filter, user_get):
user_filter.return_value = mock.Mock()
user_filter.return_value.count = mock.Mock(return_value=1)
self.assertRaises(SuspicionError_Permission, become.wrapped, request, "alt1")
def test_acceptOwned(self):
request = mock.Mock()
alt_user = mock.Mock()
request.session = MockSession()
request.session.SESSION_key = 'THE_KEY'
request.user = mock.Mock(spec=['personalities'])
request.user.is_anonymous = mock.Mock(return_value=False)
original_user = request.user
personality_get = request.user.personalities.get
personality_get.return_value = alt_user
self._accept_test(request, original_user, original_user, alt_user, personality_get)
def test_acceptSibling(self):
request = mock.Mock()
alt_user = mock.Mock()
request.session = MockSession()
request.session.SESSION_key = 'THE_KEY'
request.user = mock.Mock(spec=['personalities'])
request.user.is_anonymous = mock.Mock(return_value=False)
original_user = request.user
original_user.master_user = mock.Mock()
master_user = original_user.master_user
personality_get = master_user.personalities.get
personality_get.return_value = alt_user
self._accept_test(request, original_user, master_user, alt_user, personality_get)
def _accept_test(self, request, original_user, master_user, alt_user, personality_get):
@apply
@mock.patch("culet.personality.views.login")
def _(login):
return_value = become.wrapped(request, "alt1")
R_previous_user = return_value['ctx']['previous_user']
R_became = return_value['ctx']['became']
R_master_user = return_value['ctx']['master_user']
del return_value
assert R_previous_user is original_user, locals()
assert R_became is alt_user, locals()
assert R_master_user is master_user, locals()
assert login.call_args[0][0] is request
assert login.call_args[0][1] is alt_user
<file_sep>/culet/personality/middleware.py
from culet.personality.models import Personality
class PersonalityMiddleware:
def process_request(self, request):
try:
current_user = request.user
except AttributeError:
return
else:
try:
if request.user.is_authenticated():
request.user = Personality.objects.get(user_ptr=request.user)
else:
request.user.master_user = request.user
except Personality.DoesNotExist:
request.user.master_user = request.user
<file_sep>/culet/anycontent/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns("culet.anycontent.views",
url(r'^$', 'list', name='anycontent-list'),
url(r'^post/$', 'post', name='anycontent-post-types'),
url(r'^post/([\w-]+)/$', 'post', name='anycontent-post'),
url(r'^read/([\w-]+)/$', 'read', name='anycontent-read'),
)
<file_sep>/culet/personality/models.py
from django.db import models
from django.contrib.auth.models import User
class PersonalityManager(models.Manager):
def create_for(self, master, alt_username, alt_email=''):
return self.create(
master_user=master,
username=alt_username,
email=alt_email)
def alternates_of(self, personality):
return self.filter(master_user=personality.master_user).exclude(id=personality.id)
class Personality(User):
objects = PersonalityManager()
master_user = models.ForeignKey(User, related_name='personalities')
<file_sep>/culet/personality/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('culet.personality.views',
url(r'become/(?P<alternate>[\w-]+)/$', 'become', name='personality-become'),
url(r'myselves/$', 'myselves', name='personality-myselves'),
url(r'delete/(?P<alternate>[\w-]+)/$', 'delete', name='personality-delete'),
url(r'delete/(?P<alternate>[\w-]+)/(?P<confirmation>.*)/$', 'delete', name='personality-delete-confirmation'),
url(r'create/$', 'create', name='personality-create'),
url(r'update/(?P<alternate>[\w-]+)/$', 'update', name='personality-update'),
)
<file_sep>/culet/personality/views.py
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.conf import settings
from culet.personality.models import Personality
from culet.personality.forms import PersonalityForm
class SuspicionError(Exception):
def __init__(self, msg, user):
self.msg = msg
self.user = user
self.args = (msg, user)
class SuspicionError_Permission(SuspicionError): pass
class SuspicionError_Invalid(SuspicionError): pass
def _viewier_dec(f, template, get_form=None, success_url=None):
def _(request, *args, **kwargs):
try:
ctx = {}
view_locals = f(request, *args, **kwargs) or {}
ctx.update(view_locals.get('ctx', {}))
def callback(name, *args, **kwargs):
cb_function = view_locals.get(name, lambda *a, **k: a[0])
ret = cb_function(*args, **kwargs)
return ret
# Creating a form
if request.method == 'GET' and get_form is not None:
ctx['form'] = form = get_form(request)
# Handling a form
elif request.method == 'POST' and get_form is not None:
ctx['form'] = form = get_form(request, request.POST)
if form.is_valid():
callback('fmrm_valid', form)
form.save()
callback('form_saved', form)
if success_url is not None:
return HttpResponseRedirect(reverse(success_url))
# Post-view processing and result
if view_locals.get('redirect', False):
return HttpResponseRedirect(reverse(success_url))
else:
return render_to_response(
template,
RequestContext(request, ctx)
)
except SuspicionError:
return render_to_response("culet/error.html", RequestContext(request, ctx))
# TODO: Figure out what the "standard" thing is here
_.wrapped = f
return _
def viewier(template, **kwargs):
return lambda func:_viewier_dec(func, template, **kwargs)
@viewier('culet/myselves.html')
def myselves(request):
"""List of current user's personalities."""
current_user = request.user
try:
master_user = current_user.master_user
except AttributeError:
master_user = current_user
personalities = master_user.personalities.all()
return {'ctx': locals()}
@viewier("culet/become.html", success_url="personality-myselves")
def become(request, alternate):
"""Log a user in as one of their alternates."""
current_user = request.user
if current_user.is_anonymous():
raise SuspicionError_Permission("User tried to become a personality while not logged in", user=current_user)
try:
master_user = current_user.master_user
except AttributeError:
master_user = current_user
try:
personality = master_user.personalities.get(username=alternate)
except Personality.DoesNotExist:
personality = User.objects.get(username=alternate)
if personality.personalities.count():
pass
else:
raise
except User.DoesNotExist:
if User.objects.filter(username=alternate).count():
raise SuspicionError_Permission("User tried to become a personality they do not own", user=current_user)
else:
raise SuspicionError_Invalid("User tried to become a personality that does not exist", user=current_user)
personality.backend = settings.AUTHENTICATION_BACKENDS[0]
login(request, personality)
return {'ctx':
{
'previous_user': current_user,
'became': personality,
'master_user': master_user,
},
'redirect': True,
}
def delete(request, alternate, confirmation=None):
"""Delete a personality."""
@viewier('culet/create.html',
get_form=PersonalityForm,
success_url='personality-myselves',
)
def create(request):
"""Create a personality."""
pass
def update(request, alternate):
"""Update a personality."""
<file_sep>/culet/anycontent/migrations/0001_initial.py
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Header'
db.create_table('anycontent_header', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=100)),
('slug', self.gf('django.db.models.fields.SlugField')(max_length=100, db_index=True)),
('content_type_name', self.gf('django.db.models.fields.CharField')(max_length=50)),
('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])),
('content_id', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('anycontent', ['Header'])
# Adding model 'PlainText'
db.create_table('anycontent_plaintext', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('body', self.gf('django.db.models.fields.TextField')(default='')),
))
db.send_create_signal('anycontent', ['PlainText'])
def backwards(self, orm):
# Deleting model 'Header'
db.delete_table('anycontent_header')
# Deleting model 'PlainText'
db.delete_table('anycontent_plaintext')
models = {
'anycontent.header': {
'Meta': {'object_name': 'Header'},
'content_id': ('django.db.models.fields.IntegerField', [], {}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'content_type_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '100', 'db_index': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'anycontent.plaintext': {
'Meta': {'object_name': 'PlainText'},
'body': ('django.db.models.fields.TextField', [], {'default': "''"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['anycontent']
<file_sep>/requirements.txt
south
django==1.2
<file_sep>/culet/anycontent/models.py
from django.db import models
from django.contrib.contenttypes import generic
class Header(models.Model):
title = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
edited = models.DateTimeField(auto_now=True)
content_type_name = models.CharField(max_length=50)
content_type = models.ForeignKey('contenttypes.ContentType')
content_id = models.IntegerField()
content = generic.GenericForeignKey('content_type', 'content_id')
def render_content(self):
from django import template
t = template.loader.get_template(content_classes[self.content_type_name]['template'])
return t.render(template.Context({
'header': self,
'content': self.content,
}))
def get_form(self):
register_meta = content_classes[self.content_type_name]
if register_meta['form'] is not None:
form_class = register_meta['form']
else:
form_class = type(self).ContentMeta.form
header = self
class _ContentForm(form_class, ContentBaseForm):
def save(self, *args, **kwargs):
header.title = self.cleaned_data['title']
header.slug = self.cleaned_data['slug']
header.save(*args, **kwargs)
nsform_class.save(*args, **kwargs)
return _ContentForm(instance=self.content)
class Meta:
ordering = ['-created']
class Stream(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
entries = models.ManyToManyField(Header, through='Entry')
def get_entries(self):
entries = self.entries.all()
posts = entries.values_list('header')
for (entry, post) in zip(entries, posts):
post.slug = entry.slug
return posts
class Entry(models.Model):
header = models.ForeignKey(Header)
stream = models.ForeignKey(Stream)
slug = models.SlugField()
def save(self, *args, **kwargs):
if self.slug is None:
self.slug = slugify(self.header.title)
super(Entry, self).save(*args, **kwargs)
class Meta:
unique_together = (
('stream', 'slug'),
)
class _ContentClasses(object):
def __init__(self):
self._types = {}
def register(self, name, model, template=None, form=None):
"""Register a content class and optionally bind it with a display template
and/or form.
"""
if template is None:
template = model.ContentMeta.template
if form is None:
form = model.ContentMeta.get_form()
self._types[name] = locals()
def __getitem__(self, name):
return self._types[name]
def __iter__(self):
return iter(self._types.values())
content_classes = _ContentClasses()
class PlainText(models.Model):
body = models.TextField(default="")
@property
def tease(self):
words = self.body.split(' ')
if len(words) >= 500:
words.append('...')
return ' '.join(words)
else:
return self.body
class ContentMeta:
template = "anycontent/plain.html"
@classmethod
def get_form(cls):
from django import forms
class TextForm(forms.ModelForm):
class Meta:
model = PlainText
return TextForm
content_classes.register("plain-text", PlainText)
content_classes.register("plain-html", PlainText, template="anycontent/plain-html.html")
<file_sep>/culet/anycontent/admin.py
from culet.anycontent.models import Header
from django.contrib import admin
admin.site.register(Header)
<file_sep>/culet/roles/models.py
from abc import ABCMeta, abstractmethod
from django.db import models
from django.contrib.contenttypes import generic
class Role(models.Model):
name = models.CharField(max_length=100)
role_group = models.ForeignKey('auth.Group')
def grant(self, user):
self.role_group.users.add(user)
def deny(self, user):
self.role_group.users.remove(user)
def check(self, user, nothing, action):
return user in self.role_group.users and action in self.actions.all()
def add_action(self, action):
RoleAction.objects.create(
role=self,
action_module=action.__module__,
action_class=action.__name__)
def drop_action(self, action):
RoleAction.objects.filter(
role=self,
action_module=action.__module__,
action_class=action.__name__).delete()
class RoleAction(models.Model):
role = models.ForeignKey(Role, related_name='actions')
action_module = models.CharField(max_length=300)
action_class = models.CharField(max_length=100)
def get_action(self):
module = __import__(self.action_module, fromlist=[1])
action_class = getattr(module, self.action_class)
return action_class
class Action(object):
"""Subclasses of action define things roles can do."""
def applies_to_instance(self, instance):
"""Returns true if the action can be used on the instance."""
class ModelPermission(Role):
model = models.ForeignKey('contenttypes.ContentType')
def check(self, user, instance_or_model):
if isinstance(instance_or_model, models.Model):
model = instance_or_model
else:
model = type(instance_or_model)
return model is self.model.get_model()
class ItemPermission(Role):
content_type = models.ForeignKey('contenttypes.ContentType')
object_id = models.IntegerField()
object = generic.GenericForeignKey()
def check(self, user, instance):
model = self.content_type.get_model()
return isinstance(instance, model) and instance.id == self.object_id
<file_sep>/culet/personality/admin.py
from django.contrib import admin
from culet.personality.models import Personality
admin.site.register(Personality)
<file_sep>/culet/anycontent/forms.py
from sys import stderr
from django import forms
from django.contrib.contenttypes.models import ContentType
from django.template.defaultfilters import slugify
from culet.anycontent.models import Header, content_classes
class _ccc(object):
def __iter__(self):
for cc in content_classes:
ct = ContentType.objects.get_for_model(cc['model'])
print >>stderr, "***", cc['name'], str(ct)
yield (
cc['name'],
cc['name'],
)
HF_DEBUG_FIELDS = forms.HiddenInput
class HeaderForm(forms.ModelForm):
content_type_name = forms.ChoiceField(widget=HF_DEBUG_FIELDS, choices=_ccc())
content_id = forms.CharField(widget=HF_DEBUG_FIELDS)
slug = forms.CharField(widget=HF_DEBUG_FIELDS)
class Meta:
model = Header
def AnyContentForm(request, content_type_name):
hf = HeaderForm(request.POST or None, prefix='header')
content_form = content_classes[content_type_name]['form']
cf = content_form(request.POST or None, prefix='content')
if request.method == 'POST':
if cf.is_valid():
content = cf.save()
hf.data = dict((k, v) for (k, v) in hf.data.items())
hf.data[hf.add_prefix('slug')] = slugify(hf.data[hf.add_prefix('title')])
hf.data[hf.add_prefix('content')] = content.id
hf.data[hf.add_prefix('content_type_name')] = content_classes[content_type_name]['name']
hf.data[hf.add_prefix('content_id')] = content.id
hf.data[hf.add_prefix('content_type')] = ContentType.objects.get_for_model(content_classes[content_type_name]['model']).id
if hf.is_valid():
hf.save()
return (hf, cf)
| fdf0d12ae35ee1ea8d07f34c4ec3cc7ebfbc54ea | [
"Python",
"Text",
"HTML"
] | 17 | Python | ironfroggy/Culet | a4fd74356d353ef2ff440549b5977c7e18dd3154 | e28bed7a542470aeb006b08a9dfd24130b6f463c |
refs/heads/master | <file_sep>import pandas as pd
import json
'''
def field_from_lat_long(latitude, longitude):
#MVP, create grid with corners, classify by switch statements
fieldInfo = {
#start top left like reading a book with two pages with a crease down the center
'field':[51,41,
52,42,
53,43,
31,21,11,
32,22,
33,23,12],
'botRight':[(48.990948,-116.522334),(48.991517,-116.515995),
(48.987710,-116.521631),(48.988252,-116.515086),
(48.985037,-116.520768),(48.985024,-116.514611),
(48.991111,-116.509549),(48.991681,-116.502916),(48.992418,-116.497356),
(48.987749,-116.508661),(48.988291,-116.501987),
(48.984388,-116.507812),(48.984806,-116.501284),(48.985105,-116.493662)
]
}
#to avoid major errors caused by fields not being lined up perfectly N-S, E-W
#compare the fields in this order
order = [0,1,2,6,3,4,5,7,9,10,11,8,12,13]
for i in order:
f_lat,f_lon = fieldInfo['botRight'][i]
if latitude > f_lat and longitude < f_lon:
return fieldInfo['field'][i]
return 404 #field not found
'''
class Farm:
# class for holding, calculating, and updating field threat levels for a single farm
# TODO:
# make it so lat,lon->field mapping data modifiable on init
# use euclidean norms and lat,long in center of fields for lat,lon->field mapping
def __init__(self, field_list, disease_list):
# fields is an array with field numbers
self.fields = field_list
self.diseases = field_list
self.df = pd.DataFrame(
columns=disease_list,
index=field_list
)
self.df['OTHER_NAME'] = pd.Series(['default' for i in field_list],
index=field_list
)
self.df = self.df.fillna(value=0)
def add_report_array(self, field, new_data):
# add a report to the field, update df
# data should be an array with same order as columns, 6 items
num_prev_reports = self.df.loc[field, 'num_reports']
other_name = new_data[-1]
new_data = [(self.df.loc[field, self.diseases[i]] * num_prev_reports + new_data[i])
/ (num_prev_reports + 1)
for i in range(5)] # SM through OTHER
new_data.append(other_name)
new_data.append(num_prev_reports + 1) # add 1 to prev reports
self.df.loc[field] = data # update stored field info
def add_report_df(self, report_df):
# updates internal df with the report
# takes data from a single-row df with the following columns, default index
# 'unix_time', 'lat','lon','SM','PRED','PM','DM','OTHER','OTHER_NAME'
# replace 'lat' and 'lon' columns with 'field'
for j in report_df.index:
print(self.field_from_lat_long(report_df[j, 'latitude'],
report_df[j, 'longitude']))
print(report_df[j, 'latitude'])
report_df['field'] = pd.Series(
[self.field_from_lat_long(report_df.loc[j, 'latitude'],
report_df.loc[j, 'longitude'])
for j in report_df.index]
)
report_df = report_df.drop(columns=['latitude', 'longitude'])
print(report_df)
# put report_df into array format to feed it into add_report_array
for j in report_df.index:
report_array = [report_df.loc[j, i] for i in self.diseases]
self.add_report_array(report_df.loc[j, 'field'], report_array)
def field_from_lat_long(self, latitude, longitude):
# MVP, create grid with corners, classify by switch statements
fieldInfo = {
# Start top left like reading a book with two pages with a crease down the center
'field': [51, 41,
52, 42,
53, 43,
31, 21, 11,
32, 22,
33, 23, 12],
'botRight': [(48.990948, -116.522334), (48.991517, -116.515995),
(48.987710, -116.521631), (48.988252, -116.515086),
(48.985037, -116.520768), (48.985024, -116.514611),
(48.991111, -116.509549), (48.991681, -116.502916), (48.992418, -116.497356),
(48.987749, -116.508661), (48.988291, -116.501987),
(48.984388, -116.507812), (48.984806, -116.501284), (48.985105, -116.493662)
]
}
# to avoid major errors caused by fields not being lined up perfectly N-S, E-W
# compare the fields in this order
order = [0, 1, 2, 6, 3, 4, 5, 7, 9, 10, 11, 8, 12, 13]
for i in order:
f_lat, f_lon = fieldInfo['botRight'][i]
if latitude > f_lat and longitude < f_lon:
return fieldInfo['field'][i]
return 404 # field not found
def print(self):
# print the dataFrame
print(self.df)
def returnDf(self):
# return the df
return self.df
def remove_num(self):
no_num_df = pd.DataFrame(
data=[self.df.loc[row, col][0] for row, col in self.df.iterrows],
index=self.df.index,
columns=self.df.columns
)
print(no_num_df)
return no_num_df
def to_JSON(self):
print([self.df.loc[row, col][0] for row, col in self.df.itterrows])
# return df as JSON string
return 3
#self.remove_num().to_json(orient='index')
fields = [51, 41, 52, 42, 53, 43, 31,
21, 11, 32, 22, 33, 23, 12]
diseases = ['Spider Mite', '<NAME> (Primary Infection)',
'Downy Mildew (Secondary Infection)',
'<NAME>', '<NAME>', 'Aphid',
]
emf = Farm(fields, diseases)
# JSON to DF
with open('agromoai-export.json') as f:
data = json.load(f)
df_json = pd.DataFrame(data['mites']).transpose()
# print it before and after adding the report
emf.print()
for i in range(len(df_json.index)):
emf.add_report_df(df_json)
emf.print()
# print JSON
print(emf.to_JSON())
'''example DF used for testing
df = pd.DataFrame(data=[[52241, 48.986, -116.512, 3, 1, 0, 1, 10, 'hops']],
columns=['unix_time', 'lat', 'lon', 'SM', 'PRED',
'PM', 'DM', 'OTHER', 'OTHER_NAME']
)
'''
'''#example
field = field_from_lat_long(48.986,-116.512)
print(field)
'''
'''
df['field'] = pd.Series(
[ field_from_lat_long(df.loc[j,'lat']
,df.loc[j,'lon'])
for j in range(len(df.index)) ]
)
df = df.drop(columns=['lat','lon'])
'''
'''
stuff from before started using a class
#add a report to the field, update df
df = pd.DataFrame(data=[[52241,48.986,-116.512,3,1,0,1,10,'hops'],
[53512,48.996,-116.532,3,1,0,1,11,'hops']],
columns=['unix_time','lat','lon','SM','PRED',
'PM','DM','OTHER','OTHER_NAME']
)
df['field'] = pd.Series(
[ field_from_lat_long(df.loc[j,'lat']
,df.loc[j,'lon'])
for j in range(len(df.index)) ]
)
df = df.drop(columns=['lat','lon'])
#print(df)
rawJSON = df.to_json(orient='index')
print( rawJSON )
'''
<file_sep>import pandas as pd
import json
###################################
# Farm class definition
###################################
class Farm:
# class for holding, calculating, and updating field threat levels for a single farm
# TODO:
# use euclidean norms and lat,long in center of fields for lat,lon->field mapping
# this is needed for non-square fields
# use time stamps
# this is needed to build a time map for threat values in each field using reports
def __init__(self, field_list, disease_list, field_gps_info):
# fields is an array with field numbers
self.field_info = field_gps_info
self.fields = field_list
self.diseases = field_list
self.df = pd.DataFrame(
data=[[[0, 0] for _ in disease_list]], # default empty values; [threat,num reports]
columns=disease_list,
index=field_list
)
def add_single_report(self, field, threat, disease):
# add a report to the field, update df
# data should be an array with same order as columns, 6 items
prev_threat, prev_reports = self.df.loc[field, disease]
new_threat = (prev_threat * prev_reports + threat) / (prev_reports + 1)
# update stored field info
self.df.loc[field, disease] = [new_threat, prev_reports+1]
def add_report_from_df(self, report_df):
# updates internal df with the report
# takes data from a single-row df with the following columns, default index
# replace 'lat' and 'lon' columns with 'field'
report_df['field'] = pd.Series(
[self.field_from_lat_long(report_df.loc[j, 'latitude'],
report_df.loc[j, 'longitude'])
for j in report_df.index]
)
report_df = report_df.drop(columns=['latitude', 'longitude'])
print(report_df)
# put report_df into array format to feed it into add_report_array
for j in report_df.index:
self.add_single_report(report_df.loc[j, 'field'],
report_df.loc[j, 'severity'],
report_df.loc[j, 'disease'])
def field_from_lat_long(self, latitude, longitude):
# MVP, create grid with corners, classify by switch statements
for k in self.field_info['order']:
f_lat, f_lon = self.field_info['botRight'][k]
if latitude > f_lat and longitude < f_lon:
return self.field_info['field'][k]
return 404 # field not found
def print_df(self):
# print the dataFrame
print(self.df)
def remove_num(self):
no_num_df = pd.DataFrame(
data=[[self.df.loc[row, col][0]
for col in self.df.columns]
for row in self.df.index],
index=self.df.index,
columns=self.df.columns
)
print(no_num_df)
return no_num_df
def to_JSON(self):
print([self.df.loc[row, col][0]
for row in self.df.index
for col in self.df.columns])
# return df as JSON string
return self.remove_num().to_json(orient='index')
def to_excel(self, file_name):
# saves as excel 2010 file using openpyxl
self.remove_num().to_excel(file_name, sheet_name='Sheet1')
def to_csv(self, file_name):
self.remove_num().to_csv(file_name)
###########################################################
# Field specific info (for Elk Mountain Farms)
###########################################################
emf_fields = [51, 41, 52, 42, 53, 43, 31,
21, 11, 32, 22, 33, 23, 12,
404] # 404 is used for not valid fields
emf_diseases = ['Spider Mite', 'Downy Mildew (Primary Infection)',
'<NAME> (Secondary Infection)',
'<NAME>', '<NAME>', 'Aphid',
]
emf_field_gps_info = {
# Start top left like reading a book with two pages with a crease down the center
'field': [51, 41,
52, 42,
53, 43,
31, 21, 11,
32, 22,
33, 23, 12],
# bottom right corner of each field, found from google earth
'botRight': [(48.990948, -116.522334), (48.991517, -116.515995),
(48.987710, -116.521631), (48.988252, -116.515086),
(48.985037, -116.520768), (48.985024, -116.514611),
(48.991111, -116.509549), (48.991681, -116.502916), (48.992418, -116.497356),
(48.987749, -116.508661), (48.988291, -116.501987),
(48.984388, -116.507812), (48.984806, -116.501284), (48.985105, -116.493662)
],
# avoid errors caused by fields not being perfectly lined up N-S/E-W
'order': [0, 1, 2, 6, 3, 4, 5, 7, 9, 10, 11, 8, 12, 13]
}
# set object, emf = Elk Mountain Farms
emf = Farm(emf_fields, emf_diseases, emf_field_gps_info)
##################################################
# Example using agromoai-export.json
##################################################
# JSON to DF
with open('agromoai-export.json') as f:
data = json.load(f)
df_json = pd.DataFrame(data['mites']).transpose()
df_json.index = [i for i in range(len(df_json.index))]
print(df_json)
# print it before and after adding the report
# to show change in data structure
emf.print_df()
emf.add_report_from_df(df_json)
# print JSON
print(emf.to_JSON())
emf.to_excel('EMF pd.xlsx')
emf.to_csv('EMF pd.csv')
<file_sep>import pandas as pd
import json
import datetime as dt
###################################
# Farm class definition
###################################
class Farm:
# class for holding, calculating, and updating field threat levels for a single farm
# TODO:
# use euclidean norms and lat,long in center of fields for lat,lon->field mapping
# this is needed for non-square fields
# use time stamps
# this is needed to build a time map for threat values in each field using reports
def __init__(self, field_list, disease_list, field_gps_info):
# fields is an array with field numbers
self.field_info = field_gps_info
self.fields = field_list
self.diseases = field_list
self.df = pd.DataFrame(
data=[[[0, 0] for _ in disease_list]], # default empty values; [threat,num reports]
columns=disease_list,
index=field_list
)
def add_single_report(self, field, threat, disease):
# add a report to the field, update df
# data should be an array with same order as columns, 6 items
prev_threat, prev_reports = self.df.loc[field, disease]
new_threat = (prev_threat * prev_reports + threat) / (prev_reports + 1)
# update stored field info
self.df.loc[field, disease] = [new_threat, prev_reports + 1]
def add_report_from_df(self, report_df):
# updates internal df with the report
# takes data from a single-row df with the following columns, default index
# replace 'lat' and 'lon' columns with 'field'
report_df['field'] = pd.Series(
[self.field_from_lat_long(report_df.loc[j, 'latitude'],
report_df.loc[j, 'longitude'])
for j in report_df.index]
)
report_df = report_df.drop(columns=['latitude', 'longitude'])
print(report_df)
# put report_df into array format to feed it into add_report_array
for j in report_df.index:
self.add_single_report(report_df.loc[j, 'field'],
report_df.loc[j, 'severity'],
report_df.loc[j, 'disease'])
def field_from_lat_long(self, latitude, longitude):
# MVP, create grid with corners, classify by switch statements
for k in self.field_info['order']:
f_lat, f_lon = self.field_info['botRight'][k]
if latitude > f_lat and longitude < f_lon:
return self.field_info['field'][k]
return 404 # field not found
def print_df(self):
# print the dataFrame
print(self.df)
def remove_num(self):
no_num_df = pd.DataFrame(
data=[[self.df.loc[row, col][0]
for col in self.df.columns]
for row in self.df.index],
index=self.df.index,
columns=self.df.columns
)
print(no_num_df)
return no_num_df
def to_JSON(self):
print([self.df.loc[row, col][0]
for row in self.df.index
for col in self.df.columns])
# return df as JSON string
return self.remove_num().to_json(orient='index')
def to_excel(self, file_name, sheet_name):
# saves as excel 2010 file using openpyxl
self.remove_num().to_excel(file_name, sheet_name=sheet_name)
def to_csv(self, file_name):
self.remove_num().to_csv(file_name)
class Farm_dates:
# holds multiple farm values, one for each day
# days are saved as three index tuples
# eg. August 26 1996 -> (26, 8, 1996)
def __init__(self):
self.farms = {}
self.raw_df = pd.DataFrame()
self.fields = []
self.field_info = []
self.diseases = []
def add_day(self, farm, day):
self.farms[day] = farm
def add_farms_from_json(self, json_in, farm_info):
# farm_info = fields, gps, diseases
self.fields = farm_info[0]
self.field_info = farm_info[1]
self.diseases = farm_info[2]
df_j = pd.DataFrame(json_in).transpose()
df_j.index = [i for i in range(len(df_j.index))]
df_j['date'] = [dt.datetime.fromtimestamp(unix).strftime('%Y-%m-%d')
for unix in df_j['timestamp']]
df_j = df_j.sort_values(by='date')
df_j['field'] = pd.Series(
[self.field_from_lat_long(df_j.loc[j, 'latitude'],
df_j.loc[j, 'longitude'])
for j in df_j.index]
)
df_j = df_j.sort_values(by='field')
self.raw_df = df_j
def field_from_lat_long(self, latitude, longitude):
# MVP, create grid with corners, classify by switch statements
for k in self.field_info['order']:
f_lat, f_lon = self.field_info['botRight'][k]
if latitude > f_lat and longitude < f_lon:
return self.field_info['field'][k]
return 404 # field not found
def to_excel(self, filename):
# exports a raw excel file
df = self.raw_df
writer = pd.ExcelWriter(filename)
# build the overall map and put it into sheet=main, first
front = Farm(emf_fields, emf_diseases, emf_field_gps_info)
front.add_report_from_df(df)
front.to_excel(writer, 'All Fields')
# loop through each field and build a df for diseases and dates
list_of_field_df, list_of_fields = self.build_list_of_field_df(df)
for n in range(len(list_of_fields)):
list_of_field_df[n].to_excel(
writer,
'Field %s' % list_of_fields[n]
)
# put raw list of querys to raw reports sheet, last
df.to_excel(writer, sheet_name='Raw Reports')
# save excel sheet, last step
writer.save()
def build_list_of_field_df(self, field_df):
# build stuff
list_of_fields = field_df['field'].unique()
list_of_field_df = []
# reindex with fields
field_df = field_df.sort_values(by='field')
print(field_df.columns)
# try using arrays
for i in field_df['field'].unique():
list_of_field_df.append(
self.build_time_field_df(
field_df[field_df['field'] == i]
)
)
# remove extra index
return list_of_field_df, list_of_fields
def build_time_field_df(self, field_df):
# return a formatted df
# field_df is isolated to a single field
field_df = field_df.sort_values(by='date')
tot_arr = []
for i in field_df['date'].unique():
date_arr = []
for j in self.diseases:
'''
field_dic[j] = field_df[field_df['date'] == i &
field_df['disease'] == j]['severity'].mean()
'''
k = field_df[(field_df['date'] == i) & (field_df['disease'] == j)]['severity'].mean()
if pd.isna(k):
k = ""
date_arr.append(k)
tot_arr.append(date_arr)
return pd.DataFrame(tot_arr,
index=field_df['date'].unique(),
columns=self.diseases)
###########################################################
# Field specific info (for Elk Mountain Farms)
###########################################################
emf_fields = [51, 41, 52, 42, 53, 43, 31,
21, 11, 32, 22, 33, 23, 12,
404] # 404 is used for not valid fields
emf_diseases = ['Spider Mite', 'Downy Mildew (Primary Infection)',
'Downy Mildew (Secondary Infection)',
'<NAME>', '<NAME>', 'Aphid'
]
emf_field_gps_info = {
# Start top left like reading a book with two pages with a crease down the center
'field': [51, 41,
52, 42,
53, 43,
31, 21, 11,
32, 22,
33, 23, 12
],
# bottom right corner of each field, found from google earth
'botRight': [(48.990948, -116.522334), (48.991517, -116.515995),
(48.987710, -116.521631), (48.988252, -116.515086),
(48.985037, -116.520768), (48.985024, -116.514611),
(48.991111, -116.509549), (48.991681, -116.502916), (48.992418, -116.497356),
(48.987749, -116.508661), (48.988291, -116.501987),
(48.984388, -116.507812), (48.984806, -116.501284), (48.985105, -116.493662)
],
# avoid errors caused by fields not being perfectly lined up N-S/E-W
'order': [0, 1, 2, 6, 3, 4, 5, 7, 9, 10, 11, 8, 12, 13]
}
# set object, emf = Elk Mountain Farms
emf = Farm(emf_fields, emf_diseases, emf_field_gps_info)
#######################################
# Testbed for Fields data structure
#######################################
with open('agromoai-export.json') as f:
data = json.load(f)
emf_FD = Farm_dates()
emf_FD.add_farms_from_json(data['mites'], [emf_fields, emf_field_gps_info, emf_diseases])
emf_FD.to_excel('temp_1100.xlsx')
| da101872b97f0b85a8006bf91b6e622225e563fe | [
"Python"
] | 3 | Python | stoddabr/EMFscoutAppParser | 82b74e5668bf66e17b2fbf3e3ddb70e387f47f7e | 3f3311141ebb2b22de38135abcf9ec6fc11fef15 |
refs/heads/master | <repo_name>dolphingarlic/stringstring<file_sep>/README.md
# StringString
A function that, when given a string, returns ASCII art of that string but using the letters of that string
<file_sep>/stringstring/stringstring.py
from stringstring.ascii_letters import ascii_letters
def stringstring(string):
base = ''
for i in range(6):
for j in string:
base += ascii_letters[i][j]
base += '\n'
string = string.replace(' ', '')
result = ''
counter = 0
for i in base:
if i == '~':
result += string[counter]
counter += 1
if counter == len(string):
counter = 0
else:
result += i
return result
if __name__ == "__main__":
print(stringstring('Hello World!'))
print(stringstring("This is StringString"))
<file_sep>/stringstring/parse.py
mp = [{} for i in range(6)]
with open('ascii_letters.txt', 'r') as fin:
while (fin.readline()):
letter = fin.readline()[:-1]
for j in range(6):
mp[j][letter] = fin.readline()[:-1].replace('.', ' ').replace('#', '~')
fin.close()
with open('ascii_letters.py', 'w') as fout:
fout.write('ascii_letters = ')
fout.write(str(mp))
fout.close()
<file_sep>/stringstring/__init__.py
from stringstring.stringstring import stringstring
from stringstring.ascii_letters import ascii_letters
| 281014dcde57a08a06caf671ec1e5c5a44c8cb9a | [
"Markdown",
"Python"
] | 4 | Markdown | dolphingarlic/stringstring | b475c028ef6abff880a6ed086fd60829678cf2e3 | 89e6ae6d0d11631e87d148a2296b6b9809750a1e |
refs/heads/master | <repo_name>itgsod-dennis-rydell/git-test<file_sep>/phytagoras.rb
def phytagoras(katet1,katet2)
result = katet1**2 + katet2**3
return Math.sqrt result
end
puts phytagoras(3,4)
puts phytagoras(6,15)<file_sep>/readme.md
#Hello, Github
This is my first project
* this
* is
* a
* list
| bfb0b9e8003970280e7f144f93532abbbe2735d4 | [
"Markdown",
"Ruby"
] | 2 | Ruby | itgsod-dennis-rydell/git-test | 04c89098bd638b3c6c7b7c6e085cb0938bb4088f | 20cefaf81cdef1a4575ef11af53c5e0c58dad9c9 |
refs/heads/master | <file_sep>/*
* <NAME>
* 991450576
*
*/
package week_3;
/**
*
* @author Sandeep
*/
public class GeometricObjects {
private String color;
private boolean filled;
private java.util.Date dateCreated;
public GeometricObjects(){}
public GeometricObjects(String color, boolean filled){
this.color=color;
this.filled=filled;
}
/**
* @return the color
*/
public String getColor() {
return color;
}
/**
* @param color the color to set
*/
public void setColor(String color) {
this.color = color;
}
/**
* @return the filled
*/
public boolean isFilled() {
return filled;
}
/**
* @param filled the filled to set
*/
public void setFilled(boolean filled) {
this.filled = filled;
}
/**
* @return the dateCreated
*/
public java.util.Date getDateCreated() {
return dateCreated;
}
public void setDate(){
dateCreated=new java.util.Date(System.currentTimeMillis());
}
public String toString(){
return "" ;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package week_3;
/**
*
* @author Robin
*/
public class extra {
private int hello;
private String bye;
/**
* @return the hello
*/
public int getHello() {
return hello;
}
/**
* @param hello the hello to set
*/
public void setHello(int hello) {
this.hello = hello;
}
/**
* @return the bye
*/
public String getBye() {
return bye;
}
/**
* @param bye the bye to set
*/
public void setBye(String bye) {
this.bye = bye;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package employee;
/**
*
* @author Robin
*/
public class HourlyEmployee extends Employee {
private double hours;
private double wage;
public HourlyEmployee(String fname,String lname,String ssn,double hours,double wage){
super(fname,lname,ssn);
this.hours=hours;
this.wage=wage;
}
/**
* @return the hours
*/
public double getHours() {
return hours;
}
/**
* @param hours the hours to set
*/
public void setHours(float hours) {
this.hours = hours;
}
/**
* @return the wage
*/
public double getWage() {
return wage;
}
/**
* @param wage the wage to set
*/
public void setWage(double wage) {
this.wage = wage;
}
public double earnings(){
double earning=wage*hours;
return earning;
}
public String toString(){
return "the amount you earned this week is "+earnings();
}
}
<file_sep>/*
* <NAME>
* 991450576
*
*/
package week_3;
import java.util.Scanner;
/**
*
* @author Sandeep
*/
public class Week_3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner x=new Scanner(System.in);
int v=5;
Circle c=new Circle(1,"red",true);
displayObject(c);
System.out.println(v);
// Rectangle r= new Rectangle(1,2,"blue", false);
// displayObject(r);
}
public static void displayObject(GeometricObjects a){
a.setDate();
System.out.println("created on"+a.getDateCreated()+" color is "+a.getColor());
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package employee;
/**
*
* @author Robin
*/
public class CommissionEmployee extends Employee{
private double grossSales;
private double commisionRate;
public CommissionEmployee(double grossSales,double commisionRate){
super();
this.grossSales=grossSales;
this.commisionRate=commisionRate;
}
/**
* @return the grossSales
*/
public double getGrossSales() {
return grossSales;
}
/**
* @param grossSales the grossSales to set
*/
public void setGrossSales(double grossSales) {
this.grossSales = grossSales;
}
/**
* @return the commisionRate
*/
public double getCommisionRate() {
return commisionRate;
}
/**
* @param commisionRate the commisionRate to set
*/
public void setCommisionRate(double commisionRate) {
this.commisionRate = commisionRate;
}
public double earnings(){
double earning=commisionRate * grossSales;
return earning;
}
@Override
public String toString(){
return "the total earning is ";
}
}
| a3c541b1c4fd3d017672df677ee9d73f5f552f28 | [
"Java"
] | 5 | Java | sing8624/week4_in | ea03c8693293d6ec90e408e5b81f4655cb00b186 | cdc0c4015c940f0cba7dba613fa47a6106d62a11 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Contact_Tracing_App
{
public partial class frmReadVisitors : Form
{
public frmReadVisitors()
{
InitializeComponent();
}
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide();
frmWelcome f1 = new frmWelcome();
f1.Show();
}
private void btnRead_Click(object sender, EventArgs e)
{
StreamReader inputFile;
inputFile = File.OpenText("visitors.txt");
while(!inputFile.EndOfStream)
{
txtVisitorsRead.AppendText(inputFile.ReadLine() + Environment.NewLine);
}
inputFile.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Contact_Tracing_App
{
public partial class frmCTA : Form
{
byte visitorcount = 0;
public frmCTA()
{
InitializeComponent();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtLN.Clear();
txtFN.Clear();
txtMI.Clear();
cmbxAge.SelectedItem = null;
cmbxSex.SelectedItem = null;
txtTemp.Clear();
txtPhone.Clear();
txtEmail.Clear();
txtHouse.Clear();
txtBrgy.Clear();
txtCity.Clear();
txtProvince.Clear();
txtZip.Clear();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
StreamWriter customerLog;
if (txtFN.Text == "" || txtLN.Text == "" || cmbxAge.Text == "" || cmbxSex.Text == "" || txtTemp.Text == "" || txtPhone.Text == "" || txtEmail.Text == ""
|| txtHouse.Text =="" || txtBrgy.Text == "" || txtCity.Text == "" || txtProvince.Text == "")
{
MessageBox.Show("Please provide input on the required fields!");
}
else
{
customerLog = File.AppendText("visitors.txt");
customerLog.WriteLine("Date: " + datePicker.Text);
customerLog.WriteLine("Name: " + txtLN.Text + ", " + txtFN.Text + " " + txtMI.Text);
customerLog.WriteLine("Age: " + cmbxAge.Text);
customerLog.WriteLine("Sex: " + cmbxSex.Text);
customerLog.WriteLine("Temperature: " + txtTemp.Text);
customerLog.WriteLine("Phone: " + txtPhone.Text);
customerLog.WriteLine("Email Address: " + txtEmail.Text);
customerLog.WriteLine("Address: " + txtHouse.Text + ", " + txtBrgy.Text + ", " + txtCity.Text + ", " + txtProvince.Text);
customerLog.WriteLine("Zipcode: " + txtZip.Text);
customerLog.WriteLine(" ");
customerLog.WriteLine(" ");
customerLog.Close();
MessageBox.Show("Thank you for your cooperation. Enjoy your visit!");
//clear textbox fields
txtLN.Clear();
txtFN.Clear();
txtMI.Clear();
cmbxAge.SelectedItem = null;
cmbxSex.SelectedItem = null;
txtTemp.Clear();
txtPhone.Clear();
txtEmail.Clear();
txtHouse.Clear();
txtBrgy.Clear();
txtCity.Clear();
txtProvince.Clear();
txtZip.Clear();
this.Hide();
frmWelcome f1 = new frmWelcome();
f1.ShowDialog();
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
frmWelcome f1 = new frmWelcome();
f1.Close();
frmReadVisitors f3 = new frmReadVisitors();
f3.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Contact_Tracing_App
{
public partial class frmWelcome : Form
{
public frmWelcome()
{
InitializeComponent();
}
private void btnVisitor_Click(object sender, EventArgs e)
{
this.Hide();
frmCTA f2 = new frmCTA();
f2.ShowDialog();
}
private void btnAdmin_Click(object sender, EventArgs e)
{
this.Hide();
frmReadVisitors f3 = new frmReadVisitors();
f3.ShowDialog();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
<file_sep># Contact Tracing Form(Final)
| 756220babfdcd4effbe3e9e05db250d44f66e0b3 | [
"Markdown",
"C#"
] | 4 | C# | Bryan-Monterozo/Contact-Tracing-Form | 800005c142564dd48f339c6a0845de83b452e3b0 | f1364520502c611f34bb8eb27073fd6b74326cde |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnboardingExperience
{
class Program
{
static void Main(string[] args)
{
var user = new User();
Console.WriteLine("Hello! Thank you for using our Onboard Application!");
user.FirstName = AskQuestion("What is your first name?");
Console.WriteLine("Awesome! Your first name is " + user.FirstName);
user.LastName = AskQuestion("What is your last name?");
Console.WriteLine("Awesome! Your full name is " + user.FirstName + " " + user.LastName);
user.IsAccountOwner = AskBoolQuestion("Are you the account owner?");
Console.WriteLine("Awesome! You are account owner: " + user.IsAccountOwner);
user.PinNumber = AskPinNumber("What is your 4 digit PIN?", 4);
Console.WriteLine("Awesome! You entered: " + user.PinNumber);
Console.ReadLine();
}
public static string AskQuestion(string question)
{
Console.WriteLine(question);
return Console.ReadLine();
}
static bool AskBoolQuestion(string question)
{
var isAccountOwner = false;
while (!isAccountOwner)
{
var response = AskQuestion(question + "(y/n)");
if (response == "y")
{
isAccountOwner = true;
}
else
{
Console.Write("You must be the account owner to proceed. ");
}
}
return isAccountOwner;
}
static string AskPinNumber(string question, int length)
{
string numberString = null;
while (numberString == null)
{
var response = AskQuestion(question);
if (response.Length == length && Int32.TryParse(response, out int possiblereturn))
{
numberString = response;
}
}
return numberString;
}
}
}
| 6d163ff3de81dee9de79245b13d3540ebe7c9042 | [
"C#"
] | 1 | C# | connordavis98/OnboardingExperience | 5dd2e82c65cd39c456c042d8cb046dfdc03934ed | a066ed50bfa7c029dde0c6b2c6de362252542717 |
refs/heads/master | <file_sep>#source other zsh configs
if [[ -f $HOME/rc/zsh/zsh.env ]];then
source $HOME/rc/zsh/zsh.env
fi
if [[ -f $HOME/rc/zsh/zsh.aliases ]];then
source $HOME/rc/zsh/zsh.aliases
fi
#source all the plugins
for files in $HOME/rc/zsh/plugins/*;do
source $files
done
# The following lines were added by compinstall
autoload -Uz compinit
compinit
zstyle ':completion:*' completer _complete _ignored
zstyle ':completion:*' menu select=2 # if there is more than 2 options,auto select the entries
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
zstyle :compinstall filename '/home/daniel/.zshrc'
# End of lines configured by zsh-newuser-install
# End of lines added by compinstall
# Lines configured by zsh-newuser-install
HISTFILE=~/.histfile
HISTSIZE=1000
SAVEHIST=1000
bindkey -v
#golang
export GOPATH=$HOME/Code/go
#bindkey from pi314 github repo
bindkey "\e[H" beginning-of-line
bindkey "\e[1~" beginning-of-line # for screen
bindkey "\eOH" beginning-of-line # for cygwin + mosh
bindkey "\e[F" end-of-line
bindkey "\e[4~" end-of-line # for screen
bindkey "\eOF" end-of-line # for cygwin + mosh
bindkey "\e[3~" delete-char # for mac
# color prompt
#git status prompt
if [ -f $HOME/rc/zsh/zsh-git-prompt/zshrc.sh ]; then
source $HOME/rc/zsh/zsh-git-prompt/zshrc.sh
fi
bindkey "^[[3~" delete-char
autoload -U colors
colors
b_yellow="%{$fg_bold[yellow]%}" #bold yellow
b_blue="%{$fg_bold[blue]%}"
b_cyan="%{$fg_bold[cyan]%}"
b_green="%{$fg_bold[green]%}"
b_white="%{$fg_bold[white]%}"
b_gray="%{$fg_bold[gray]%}"
b_magenta="%{$fg_bold[magenta]%}"
end="%{$reset_color%}"
function precmd()
{
PROMPT="${b_white}┌ %T - $end${b_cyan}%n${end}@ ${b_yellow}%m ${b_green}[%~]${end} $(git_super_status) ${b_green}$(echo $VIRTUAL_ENV | awk -F/ '{print $NF}')${end}
${b_white}└ >$end"
}
# for WSL
alias d="cd /mnt/d"
alias c="cd /mnt/c"
alias de="deactivate"
<file_sep>#!/bin/sh
files=`env ls|grep -v "\."`
files="${files} tmux.conf"
dir=`env pwd`
echo "linking rc files into $HOME"
for f in $files;do
if [ -L $HOME/.${f} ];then
rm $HOME/.${f}
fi
env ln -s $dir/$f $HOME/.${f}
if [ $? -eq 0 ];then
echo ".$f linked"
fi
done
if [ ! -d $HOME/.vim/colors ];then
mkdir -p $HOME/.vim/colors
fi
echo "copying vim molokai color scheme"
cp ./colors/molokai.vim $HOME/.vim/colors/
echo "initiating submodules"
cd "./zsh/zsh-git-prompt"
git submodule init
git submodule update
<file_sep>RCs
===
This is repo for my rc settings
## Usage
### Install
+ `git clone https://github.com/daniel0076/rc.git` in you $HOME
+ execute `link.sh` , will auto link them to you $HOME
+ Modified the link in zshrc if you move .zsh to other places
### YomCompleteMe
Please see the [Installation DOC](https://github.com/Valloric/YouCompleteMe#installation)
Below are my settings
+ precompile the completion support
```
cd ~/.vim/bundle/YouCompleteMe
./install.sh --clang-completer --gocode-completer
```
+ need to set the conf location
```
let g:ycm_global_ycm_extra_conf = '~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py'
```
+ If you want to use Syntastic, set diagnostics ui to 0, or it will turn off Syntastic
```
let g:ycm_show_diagnostics_ui = 0
```
I like Syntastic more, please refer the doc for more information about YCM syntastic support
### Syntastic
`:help syntastic` to get the document
---
## Change Log
- 20151105
- fix `link.sh` commented bug
- change vim color scheme to molokai
- add vim color file copy in `link.sh`
- fix vim and term color 256 problem
- new screen status bar
- new lscolor settings
- 20150704
- fix [zsh-git-prompt](https://github.com/olivierverdier/zsh-git-prompt) display error when sceen is not activated
- modified prompt display
- add zsh-git-prompt to submodule
- move plugins to `~/rc/zsh/plugins`
- Plugins cloned from [oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh)
- sudo
- screen
- 20150702
- Change auto-completion plugin to [YouCompleteMe](https://github.com/Valloric/YouCompleteMe),previously using [Neocomplete](https://github.com/Shougo/neocomplete.vim) but it significantly becomes slow when the code grows
- Change git intergration to [vim-fugitive](https://github.com/tpope/vim-fugitive), which is more powerful, go to it's website for more information and tutorial
- Add [vim-gitgutter](https://github.com/airblade/vim-gitgutter) for git status indicator
- Modified [Syntastic](https://github.com/scrooloose/syntastic) settings
- Modified [vim-airline](https://github.com/bling/vim-airline) settings
- remove Neocomplete (replaced with YCM)
- remove vimproc,vim-marching (C/C++ Completion with neocomplete)
- remove Neosnippet
- remove jedi-vim (replaced with YCM)
- remove emmet-vim (I don't need zen coding)
## Plugin list
+ 'Valloric/YouCompleteMe'
+ 'scrooloose/nerdtree'
+ 'scrooloose/nerdcommenter'
+ 'majutsushi/tagbar'
+ 'tpope/vim-fugitive'
+ 'bling/vim-airline'
+ 'fisadev/fisa-vim-colorscheme'
+ 'fisadev/FixedTaskList.vim'
+ 'michaeljsmith/vim-indent-object'
+ 'airblade/vim-gitgutter'
+ 'scrooloose/syntastic'
| a60d3cdd68981288e163adfd4daab9c244960d3b | [
"Markdown",
"Shell"
] | 3 | Shell | benkajaja/rc | 51b1254720b261c7b970c11810c6889c705e2e63 | ab3f2e44156469827c5ed50a673ab4b0ba44c38c |
refs/heads/master | <repo_name>lkhilton/ONTtranscripts<file_sep>/README.md
# ONTtranscripts
## Requirements
Conda: `https://docs.conda.io/en/latest/miniconda.html`
Snakemake: `conda install -c bioconda snakemake`
## Data
Download and unzip the tarballs containing fast5 and fastq files to the data directory
```
data
├── fast5
│ ├── IX7311
│ └── IX7312
├── fastq
└── metadata
```
## Reference files
Place or symlink a whole genome fasta file in `ref`. I used an hg19 build.
Generate a minimap index file: `minimap2 -d GRCh37-lite.mmi GRCh37-lite.fa`.
The transcript reference fasta and fai index files are included in this repo.
## Config
Modify `config/config.yaml` to include local paths to your reference files.
## Running Snakemake
Once the data directory is populated and the reference and config files are updated, `cd` into the top level directory and launch with:
```
snakemake -j {num_cpus} --use-conda --latency-wait 120
```
`{num_cpus}`: INT > 8
<file_sep>/Snakefile
# ---------------------------------------------------------------------------------------------- #
# GLOBAL
# ---------------------------------------------------------------------------------------------- #
### PACKAGES ###
import pandas as pd
import numpy as np
### CONFIGURATION ###
configfile: "config/config.yaml"
### VARIABLES ###
FASTQ_DIR = "data/fastq"
FAST5_DIR = "data/fast5"
METADATA="data/metadata/ONT_Metadata.txt"
wildcard_constraints:
IX = "IX731[12]"
# Lists here will be used in Snakemake rules -----------------------------
MD = pd.read_csv(METADATA, sep="\t")
SAMPLE = MD['External_Identifier'].tolist()
SAMPLE_IX = (MD['External_Identifier'] + "_" + MD['IX']).tolist()
GENES = ["FCGR2C", "FCGR2B"]
rule all:
input:
expand("results/minimap2/{sample}.hg19a.bam", sample=SAMPLE),
expand("results/minimap2/03-subsampled-fastq/{sample_IX}.index.complete", sample_IX=SAMPLE_IX),
expand("results/nanopolish/05-phased-reads/{sample}.{gene}.phased.bam", sample=SAMPLE, gene=GENES),
"results/nanopolish/06-phased-fasta/ONTtranscripts.fasta",
expand("results/nanopolish/07-clustal/{gene}.clustal", gene=GENES),
expand("results/nanopolish/08-translated/all.{gene}.protein.clustal", gene=GENES)
# ---------------------------------------------------------------------------------------------- #
# MINIMAP2
# ---------------------------------------------------------------------------------------------- #
### VARIABLES ###
MINIMAP_DIR = "results/minimap2"
MINIMAP_HG19 = f"{MINIMAP_DIR}/01-hg19"
MINIMAP_TX = f"{MINIMAP_DIR}/02-transcript-aligned"
MINIMAP_FQ = f"{MINIMAP_DIR}/03-subsampled-fastq"
rule minimap_to_hg19:
input:
fastq = f"{FASTQ_DIR}""/{sample}.fastq"
output:
bam = f"{MINIMAP_DIR}""/{sample}.hg19a.bam",
idx = f"{MINIMAP_DIR}""/{sample}.hg19a.bam.idxstats"
params:
ref = config["reference"]["grch37"]["minimap"]
threads: 4
conda: "config/envs/minimap2.yaml"
shell:
'minimap2 -ax splice -t {threads} {params.ref} {input.fastq} | '
'samtools view -b -@ {threads} | samtools sort -@ {threads} > {output.bam} && '
'samtools index {output.bam} && '
'samtools idxstats {output.bam} > {output.idx}'
rule minimap_to_transcripts:
input:
fastq = f"{FASTQ_DIR}""/{sample}.fastq"
output:
bam = f"{MINIMAP_TX}""/{sample}.transcripts.bam",
idx = f"{MINIMAP_TX}""/{sample}.transcripts.bam.idxstats"
params:
ref = config["reference"]["grch37"]["transcripts"]
threads: 4
conda: "config/envs/minimap2.yaml"
shell:
'minimap2 -ax map-ont -t {threads} {params.ref} {input.fastq} | '
'samtools view -b -m 1050 -s 0.1 -@ {threads} | samtools sort -@ {threads} > {output.bam} && '
'samtools index {output.bam} && '
'samtools idxstats {output.bam} > {output.idx}'
rule bam_to_fastq:
input:
bam = f"{MINIMAP_TX}""/{sample}.transcripts.bam"
output:
fastq = f"{MINIMAP_FQ}""/{sample}.subsampled.fastq"
threads: 4
conda: "config/envs/minimap2.yaml"
shell:
'samtools fastq {input.bam} | '
'awk \'BEGIN {{OFS = \"\\n\"}} {{header = $0 ; getline seq ; getline qheader ; getline qseq ; if (length(seq) >= 1050) {{print header, seq, qheader, qseq}} }}\' '
'> {output.fastq}'
# ---------------------------------------------------------------------------------------------- #
# NANOPOLISH
# ---------------------------------------------------------------------------------------------- #
### VARIABLES ###
NANOPOLISH_DIR = "results/nanopolish"
NP_CONSENSUS = f"{NANOPOLISH_DIR}/01-consensus"
NP_VARIANTS = f"{NANOPOLISH_DIR}/02-variants"
NP_MERGED = f"{NANOPOLISH_DIR}/03-merged-variants"
NP_PHASED_VCF = f"{NANOPOLISH_DIR}/04-phased-vcf"
NP_PHASED = f"{NANOPOLISH_DIR}/05-phased-reads"
NP_PHASED_FASTA = f"{NANOPOLISH_DIR}/06-phased-fasta"
NP_CLUSTAL = f"{NANOPOLISH_DIR}/07-clustal"
NP_TRANSLATE = f"{NANOPOLISH_DIR}/08-translated"
rule nanopolish_index:
input:
fast5 = f"{FAST5_DIR}""/{IX}",
fastq = f"{MINIMAP_FQ}""/{sample}.subsampled.fastq",
seq_summary = "data/sequencing_reports/{IX}/sequencing_summary.txt"
output:
complete = f"{MINIMAP_FQ}""/{sample}_{IX}.index.complete"
conda: "config/envs/nanopolish.yaml"
shell:
'nanopolish index -s {input.seq_summary} -d {input.fast5} {input.fastq} && '
'touch {output.complete}'
rule nanopolish_consensus:
input:
bam = f"{MINIMAP_TX}""/{sample}.transcripts.bam",
fastq = f"{MINIMAP_FQ}""/{sample}.subsampled.fastq"
output:
vcf = f"{NP_CONSENSUS}""/{sample}.{gene}.nanopolish.vcf"
params:
ref = config["reference"]["grch37"]["transcripts"]
conda: "config/envs/nanopolish.yaml"
threads: 8
shell:
'nanopolish variants -t {threads} --consensus --ploidy 2 -w {wildcards.gene}:1-2000 '
'--reads {input.fastq} --bam {input.bam} --genome {params.ref} -o {output.vcf}'
rule nanopolish_variants:
input:
bam = f"{MINIMAP_TX}""/{sample}.transcripts.bam",
fastq = f"{MINIMAP_FQ}""/{sample}.subsampled.fastq"
output:
vcf = f"{NP_VARIANTS}""/{sample}.{gene}.nanopolish.vcf"
params:
ref = config["reference"]["grch37"]["transcripts"]
conda: "config/envs/nanopolish.yaml"
threads: 8
shell:
'nanopolish variants -t {threads} --ploidy 2 -w {wildcards.gene}:1-2000 '
'--reads {input.fastq} --bam {input.bam} --genome {params.ref} -o {output.vcf}'
rule split_bam:
input:
bam = f"{MINIMAP_TX}""/{sample}.transcripts.bam"
output:
bam = f"{MINIMAP_TX}""/{sample}.{gene}.transcripts.bam"
conda: "config/envs/nanopolish.yaml"
shell:
'samtools view -b {input.bam} {wildcards.gene} > {output.bam} && '
'samtools index {output.bam}'
rule merge_variants:
input:
vars = f"{NP_VARIANTS}""/{sample}.{gene}.nanopolish.vcf",
cons = f"{NP_CONSENSUS}""/{sample}.{gene}.nanopolish.vcf"
output:
vcf = f"{NP_MERGED}""/{sample}.{gene}.merged.nanopolish.vcf"
conda: "config/envs/vcftools.yaml"
shell:
'vcfcombine {input.vars} {input.cons} > {output.vcf}'
rule whatshap_gt:
input:
vcf = f"{NP_VARIANTS}""/{sample}.{gene}.nanopolish.vcf",
bam = f"{MINIMAP_TX}""/{sample}.{gene}.transcripts.bam"
output:
vcf = f"{NP_PHASED_VCF}""/{sample}.{gene}.whatshap_gt.vcf"
params:
ref = config["reference"]["grch37"]["transcripts"]
conda: "config/envs/whatshap.yaml"
shell:
'whatshap genotype --indels --ignore-read-groups -o {output.vcf} --reference {params.ref} {input.vcf} {input.bam}'
rule phase_vcf:
input:
vcf = f"{NP_PHASED_VCF}""/{sample}.{gene}.whatshap_gt.vcf",
bam = f"{MINIMAP_TX}""/{sample}.{gene}.transcripts.bam"
output:
vcf = f"{NP_PHASED_VCF}""/{sample}.{gene}.phased.vcf"
params:
ref = config["reference"]["grch37"]["transcripts"]
conda: "config/envs/whatshap.yaml"
shell:
"whatshap phase --indels --ignore-read-groups --reference {params.ref} -o {output.vcf} {input.vcf} {input.bam}"
rule phase_bam:
input:
vcf = f"{NP_PHASED_VCF}""/{sample}.{gene}.phased.vcf",
bam = f"{MINIMAP_TX}""/{sample}.{gene}.transcripts.bam"
output:
vcf = f"{NP_PHASED_VCF}""/{sample}.{gene}.phased.vcf.gz",
bam = f"{NP_PHASED}""/{sample}.{gene}.phased.bam"
params:
ref = config["reference"]["grch37"]["transcripts"]
conda: "config/envs/whatshap.yaml"
shell:
'bgzip -c {input.vcf} > {output.vcf} && tabix {output.vcf} && '
'whatshap haplotag --ignore-read-groups -o {output.bam} --reference {params.ref} {output.vcf} {input.bam} && '
'samtools index {output.bam}'
rule consensus_fasta:
input:
vcf = f"{NP_PHASED_VCF}""/{sample}.{gene}.phased.vcf.gz"
output:
fasta = f"{NP_PHASED_FASTA}""/{sample}.{gene}.hap{hap}.fasta"
params:
ref = config["reference"]["grch37"]["transcripts"]
conda: "config/envs/whatshap.yaml"
shell:
'samtools faidx {params.ref} {wildcards.gene} | '
'bcftools consensus -H {wildcards.hap} {input.vcf} | '
'sed \'s|>|>{wildcards.sample}.hap{wildcards.hap}.|g\' > {output.fasta}'
rule concatenate_fasta:
input:
fasta = expand(f"{NP_PHASED_FASTA}""/{sample}.{gene}.hap{hap}.fasta", sample=SAMPLE, gene=GENES, hap=[1,2])
output:
fasta = f"{NP_PHASED_FASTA}""/ONTtranscripts.fasta"
shell:
'cat {input.fasta} >> {output.fasta}'
rule clustalo:
input:
fasta = expand(f"{NP_PHASED_FASTA}""/{sample}.{{gene}}.hap{hap}.fasta", sample=SAMPLE, hap=[1,2])
output:
clustal = f"{NP_CLUSTAL}""/{gene}.clustal"
params:
ref = config["reference"]["grch37"]["transcripts"]
conda: "config/envs/clustalo.yaml"
shell:
'samtools faidx {params.ref} {wildcards.gene} | '
'cat - {input.fasta} | '
'clustalo -i - -o {output.clustal} --outfmt=clu '
'--residuenumber --wrap=100 --output-order=input-order'
rule concatenate_by_gene:
input:
fasta = expand(f"{NP_PHASED_FASTA}""/{sample}.{{gene}}.hap{hap}.fasta", sample=SAMPLE, hap=[1,2])
output:
fasta = f"{NP_PHASED_FASTA}""/all.{gene}.fasta"
shell:
'cat {input.fasta} >> {output.fasta}'
rule translate:
input:
FCGR2B = f"{NP_PHASED_FASTA}""/all.FCGR2B.fasta",
FCGR2C = f"{NP_PHASED_FASTA}""/all.FCGR2C.fasta"
output:
FCGR2B = f"{NP_TRANSLATE}""/all.FCGR2B.translated.fasta",
FCGR2C = f"{NP_TRANSLATE}""/all.FCGR2C.translated.fasta"
params:
FCGR2B = "128-1200",
FCGR2C = "100-1200"
conda: "config/envs/emboss.yaml"
shell:
"transeq -region {params.FCGR2B} -sequence {input.FCGR2B} -outseq {output.FCGR2B} && "
"transeq -region {params.FCGR2C} -sequence {input.FCGR2C} -outseq {output.FCGR2C}"
rule clustalo_protein:
input:
fasta = f"{NP_TRANSLATE}""/all.{gene}.translated.fasta"
output:
clustal = f"{NP_TRANSLATE}""/all.{gene}.protein.clustal"
conda: "config/envs/clustalo.yaml"
shell:
'clustalo -i {input.fasta} -o {output.clustal} --outfmt=clu '
'--residuenumber --wrap=50 --output-order=input-order'
| 14c1366725b103833922cec66ec490ae9466be98 | [
"Markdown",
"Python"
] | 2 | Markdown | lkhilton/ONTtranscripts | c5a1a02af47359df83662e65c56594a18d74ac9a | 62bdcc8e5baa92c6b15892163ab6a1ad0b9c09c5 |
refs/heads/main | <file_sep>const Post = require('../model/testing')
module.exports = {
async getPosts() {
const Posts = await Post.find({}).sort({ "releaseDate": -1 })
return Posts
},
async getPost(id) {
const currentPost = await Post.findById(id)
return currentPost
},
async createOrUpdatePost(post) {
if(post._id) {
const updatedPost = await Post.findByIdAndUpdate(post._id, post, { new: true })
return updatedPost
}
const newPost = await Post.create(post)
return newPost
},
async deletePost(id) {
const deletedPost = await Post.findByIdAndRemove(id)
return deletedPost
}
}<file_sep>const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Este es mi proyecto\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
//conexion a la base de datos
const mongoose = require('mongoose');
const mongoDB = 'mongodb://127.0.0.1/3000';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
const db = mongoose.connection
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/', (req, res) => {
console.log(req.body);
res.send('Data received');
}) | e351f6beacd666f3cdaeb5cfb39d68e6df7feed6 | [
"JavaScript"
] | 2 | JavaScript | JulianH20/proyect | 0e799379b026f5883ca24af2d975dd86c0ae7bd4 | 5ff1bf8b2f6a808502561258169240812c73fe4c |
refs/heads/master | <repo_name>fakharkhan/booking-system<file_sep>/app/Http/Controllers/ClientsController.php
<?php
namespace App\Http\Controllers;
use App\Client;
use App\Http\Requests\ClientFormRequest;
use App\Services\ClientService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ClientsController extends Controller
{
protected $service;
public function __construct(ClientService $service)
{
$this->service = $service;
}
public function index()
{
// DB::raw('asdsad');
// $clients = new Client();
//
// if(request()->has('name'))
// {
// $clients = $clients->where('name','fakhar');
// }
//
// dd($clients->get());
//
// return $clients->get();
// dd($clients->where('name','fakhar'));
//$clients->fromQuery('');
$clients=$this->service->all(); //Return Collection
// $clients->where('name','<NAME>')[0]->name='<NAME>'; //find a record
// $clients->map(function ($client, $index){
// return $client->name='<NAME>';
// });
//
// $client = $clients[0];
// $client->name ="<NAME>";
// return $clients;
// Client::all()->sortBy('name')->where('name','aa');
//$clients->where('name','aa'); //executes where method on colleciton
//$clients=Client::where('name','aa'); //executes where method of query builder
// $clients = Client::orderBy('name')->where('name','<NAME>');
// return $clients->get();
// return $clients->sortBy('name');
return view('clients.index',compact('clients'));
}
public function show($id)
{
return "Customer Detail for ID:". $id;
}
public function create()
{
return view('clients.create');
}
public function store(ClientFormRequest $request)
{
Client::create(request()->all());
return redirect()->to('clients')->with('status','Client Saved!');
}
public function download()
{
return response()->download('robots.txt');
}
}
<file_sep>/README.md
# booking-system
Booking System aimed to use as a Practice Assignment for Laravel Training Session DEC17
#Week 2 Notes
return redirect()->route('clients'); //redirect to route name
return redirect()->to('/clients'); // redirects to url
return response()->json($client); // returns json response
return response()->download('robots.txt'); // return files to download in browser
### Collections
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);
$filtered->all();
return $filtered;
###Custom Helpers
https://laravel-news.com/creating-helpers
###Eloquent
1. Eloquent Class (collection:all(), Query Builder: where(),Eloquent Class Object: first())
2. Query Builder (Active Record Implementation)
3. Database
###Builders
1. https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Builder.html
2. https://laravel.com/api/5.5/Illuminate/Database/Query/Builder.html
##Validation
###Inline Validation
// $rules = [
// 'name' => 'required',
// 'phone' => 'required',
// ];
//
// $request->validate($rules);
#ACL
## Tables
1. Permissions
2. Roles
3. Permission_Role
4. Role_User
#Service Container and Depnedency Injection
//$app = new Illuminate\Container\Container();
//$arepo = new \App\Browns\Repositories\AirportRepository($app);
//$aservice = new App\Browns\Services\AirportService($arepo);
//dd($aservice->myName(),app('App\Browns\Services\AirportService')->myName());
//dd((new \Illuminate\Container\Container())->make('App\Browns\Services\AirportService'));
//dd(\Illuminate\Container\Container::getInstance()->make('App\Browns\Services\AirportService'));
/*
return Container::getInstance()->make($make, $parameters);
*/
//dd(new \Illuminate\Container\Container()->make('App\Browns\Services\AirportService'))
#Providing parameter to Service Container:
// $user = \App\Browns\Models\User::latest()->first();
// dd(app('App\Browns\Services\AirportService',['user'=>$user])->myName());
#https://medium.com/@NahidulHasan/laravel-ioc-container-why-we-need-it-and-how-it-works-a603d4cef10f
#Blade Directives:
https://laravelcollective.com/
#Multilayer Architecture
1.Model
2.Repositories -Extends Base Repository ( Maintain Data layer)
3.Services - Extends Base Services (Maintains Business Logic)
4.Controller <file_sep>/app/Services/ClientService.php
<?php
namespace App\Services;
use App\Client;
/**
* Created by PhpStorm.
* User: fakhar
* Date: 30/12/2017
* Time: 1:10 PM
*/
class ClientService
{
protected $client;
public function __construct(Client $client)
{
$this->client= $client;
}
public function getLastClient()
{
return $this->client->latest()->first();
}
public function __call($method, $args) {
return call_user_func_array(array($this->client, $method), $args);
throw new BadMethodCallException(sprintf('Call to undefined method %s::%s', get_class($model), $method));
}
}<file_sep>/app/Http/helpers.php
<?php
/**
* Created by PhpStorm.
* User: fakhar
* Date: 09/12/2017
* Time: 12:59 PM
*/
if (! function_exists('clients')) {
function clients()
{
return \App\Client::all();
}
}
<file_sep>/app/Providers/BladeServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;
class BladeServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
Blade::directive('text', function ($expression) {
if (!$expression) {
$expression = [];
}
$view ='controls.text';
return "<?php echo \$__env->make('{$view}',[$expression], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>";
});
}
}
| b8ecb89718c1008216a2987af1bdd2b58fd39feb | [
"Markdown",
"PHP"
] | 5 | PHP | fakharkhan/booking-system | 54ca022a3487d8b766ec1467d838a4375ed7245e | d472bd2e32222509e5b634d59dd164d2cb3c3afd |
refs/heads/master | <repo_name>Surya2602/Tugas1-AplikasiKaosKaki-InputOutput<file_sep>/input_r/app/src/main/java/com/example/lenovo/input_r/MainActivity.java
package com.example.lenovo.input_r;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText eMotif;
private EditText eUkuran;
private EditText eWarna;
private Button bCetak;
private TextView tOutputmotif;
private TextView tOutputukuran;
private TextView tOutputwarna;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eMotif = findViewById(R.id.motif);
eUkuran = findViewById(R.id.ukuran);
eWarna = findViewById(R.id.warna);
bCetak = findViewById(R.id.idcetak);
tOutputmotif = findViewById(R.id.outputmotif);
tOutputukuran = findViewById(R.id.outputukuran);
tOutputwarna = findViewById(R.id.outputwarna);
bCetak.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String inputMotif = eMotif.getText().toString();
String inputUkuran = eUkuran.getText().toString();
String inputWarna = eWarna.getText().toString();
if (inputMotif.length() == 0) {
eMotif.setError("Data tidak boleh kosong");
} else {
tOutputmotif.setText(inputMotif);
}
if (inputUkuran.length() == 0) {
eUkuran.setError("Data tidak boleh kosong");
} else {
tOutputukuran.setText(inputUkuran);
}
if (inputWarna.length() == 0) {
eWarna.setError("Data tidak boleh kosong");
} else {
tOutputwarna.setText(inputWarna);
}
}
} | a15ee2243e2237543a4e00c7947bfc428619f96a | [
"Java"
] | 1 | Java | Surya2602/Tugas1-AplikasiKaosKaki-InputOutput | f1b53455d69a1bbd75191b6d9dfd6a1848b5d4ff | 6ae3a5a81015b2a06d5229d77d2a61312e49e9f8 |
refs/heads/master | <repo_name>961almah/burger-app<file_sep>/db/seeds.sql
INSERT INTO burgers (name) VALUES ('Cheese Burger');
INSERT INTO burgers (name) VALUES ('Double-patty');
INSERT INTO burgers (name, eaten) VALUES ('Chicken Burger', true);
INSERT INTO burgers (name, eaten) VALUES ('Steak Burger', true);
INSERT INTO burgers (name, eaten) VALUES ('Homemade Burger', true);
INSERT INTO burgers (name) VALUES ('Beach Burger');
| 9dd29206babe45fa5bba87024470b0449216983d | [
"SQL"
] | 1 | SQL | 961almah/burger-app | 6c08cf49b386b080aac3dbe314e91a81ee7b75fe | 26992af69f9904fe02bf75c08bb9e67a693980d6 |
refs/heads/master | <repo_name>pparker0929/fickle<file_sep>/auditset.sh
#!/bin/sh
Auditctl -e 1
#service enable auditd.service
nano /etc/audit/aditd.conf
#Insert the following lines
#-w /etc/passwd -p wa -k identity <-Events that affect the /etc/passwd
#-w /etc/group -p wa -k identity <-Events that affect the /etc/group
#-w /etc/gshadow -p wa -k identity <-Events that affect the /etc/gshadow
#-w /etc/shadow -p wa -k identity <-Events that affect the /etc/shadow
#-w /etc/security/opasswd -p wa -k identity <-Events that affect the /etc/security/opasswd
#-a always,exit -F path=/bin/su -F perm=x -F auid>=1000 -F auid!=4294967295 -k privileged-priv_change <-Successful/Unsuccessful attempts to use the su cmd
#-a always,exit -F path=/usr/bin/ssh-agent -F perm=x -F auid>=1000 -F auid!=4294967295 -k privileged-ssh <-Successful/Unsuccessful attempts to use the ssh-agent cmd
#-a always,exit -F arch=b64 -S chown -F auid>=1000 -F auid!=4294967295 -k perm_chng <- Successful/Unsuccessful attempts to use the chown cmd
#-a always,exit -F arch=b64 -S chmod -F auid>=1000 -F auid!=4294967295 -k perm_chng <- Successful/Unsuccessful attempts to use the chmod cmd
#-a always,exit -F arch=b64 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -k perm_access <- Successful/Unsuccessful attempts to use the truncate cmd
#-a always,exit -F arch=b64 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -k perm_access <- Successful/Unsuccessful attempts to use the truncate cmd
#-a always,exit -F arch=b64 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -k perm_access <- Successful/Unsuccessful attempts to use the creat cmd
#-a always,exit -F arch=b64 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -k perm_access <- Successful/Unsuccessful attempts to use the creat cmd
#-a always,exit -F path=/usr/bin/sudo -F perm=x -F auid>=1000 -F auid!=4294967295 -k priv_cmd <- Successful/Unsuccessful attempts to use the sudo cmd
#-a always,exit -F path=/usr/bin/sudoedit -F perm=x -F auid>=1000 -F auid!=4294967295 -k priv_cmd <- Successful/Unsuccessful attempts to use the sudoedit cmd
#-w /var/log/faillog -p wa -k logins <- Successful/Unsuccessful mods to the faillog file
#-w /var/log/lastlog -p wa -k logins <- Successful/Unsuccessful mods to the lastlog file
#-a always,exit -F path=/usr/bin/passwd -F perm=x -F auid>=1000 -F auid!=4294967295 -k privileged-passwd <- Successful/Unsuccessful use of the passwd cmd
#-a always,exit -F path=/usr/sbin/usermod -F perm=x -F auid>=1000 -F auid!=4294967295 -k privileged-usermod <- Successful/Unsuccessful use of the usermod cmd
#-a always,exit -F path=/usr/bin/chsh -F perm=x -F auid>=1000 -F auid!=4294967295 -k priv_cmd
#-a always,exit -F path=/usr/bin/newgrp -F perm=x -F auid>=1000 -F auid!=4294967295 -k priv_cmd
#-a always,exit -F path=/sbin/apparmor_parser -F perm=x -F auid>=1000 -F auid!=4294967295 -k perm_chng
#-w /var/log/tallylog -p wa -k logins
#-w /var/log/faillog -p wa -k logins
#-w /var/log/lastlog -p wa -k logins
#-a always,exit -F path=/usr/bin/passwd -F perm=x -F auid>=1000 -F auid!=4294967295 -k privileged-passwd
#-a always,exit -F path=/usr/bin/gpasswd -F perm=x -F auid>=1000 -F auid!=4294967295 -k privileged-gpasswd
#-a always,exit -F path=/usr/bin/chage -F perm=x -F auid>=1000 -F auid!=4294967295 -k privileged-chage
#-a always,exit -F path=/usr/sbin/usermod -F perm=x -F auid>=1000 -F auid!=4294967295 -k privileged-usermod
#-a always,exit -F path=/usr/bin/crontab -F perm=x -F auid>=1000 -F auid!=4294967295 -k privileged-crontab
#-a always,exit -F arch=b64 -S delete_module -F auid>=1000 -F auid!=4294967295 -k module_chng
#service restart auditd.service
exit 0;<file_sep>/swinstall.sh
#!/bin/sh
# Holding off on the following lines to prevent ssh installation and usage
usermod -s /sbin/nologin root && service network-manager restart
apt-get install nmap
echo "nmap"
wget https://tinyurl.com/fjghdlgh
echo "Maldetect"
wget https://tinyurl.com/ydyujwnb
echo "RKHunter"
wget https://tinyurl.com/y7yy5p9h --no-check-certificate
echo "Lynis"
apt-get install fail2ban
echo "Fail2Ban"
tar xzf fjghdlgh && cd maldetect-1.6.3 && ./install.sh && cd
echo "Maldetect Done"
tar xzf ydyujwnb && cd rkhunter-1.4.6 && ./installer.sh -l /usr --install && cd
echo "RKHunter Done"
tar xzf y7yy5p9h && cd lynis && apt-get install lynis -y && cd
echo "Lynis Done"
apt-get install ssh -y
# sed -i '/#PermitRootLogin yes/c\PermitRootLogin no' /etc/ssh/sshd_config
# service sshd restart
echo "SSH"
apt-get install auditd
echo "AuditD"
# mkdir -p /home/USERNAME/{Conf,Bkup,Hrdn}
echo "Dirs Made"
tail -vn +1 /etc/passwd /etc/shadow /var/log/auth.log >> /home/USERNAME/Conf/stdlog
tail -vn +1 /var/log/dpkg.log | grep -w '/var/log\|installed' >> home/USERNAME/Conf/stdlog
echo "Init Conf Save"
(cat /etc/hosts; ip a show; route -n; w; arp -a) >> /home/USERNAME/Conf/net.txt
echo "Net Conf Save"
chmod 644 /etc/passwd /etc/group && chmod 640 /etc/shadow && chmod 600 /etc/ssh/sshd_config && chmod 555 /boot
echo "Atts Set"
# passwd root
# passwd username
# useradd -m username && passwd username && usermod -aG sudo username && su - username
#usermod -s /bin/false sysadmin
#usermod -L sysadmin
exit 0;<file_sep>/mont.sh
#!/bin/sh
#Check for extra 0 UIDs
echo "Extra Powerusers or Roots"
awk -F: '($3 == "0"){print}' /etc/passwd
#Check for pswd empty accts
echo "Empty Password Holders"
awk -F: '($2 == " "){print}' /etc/shadow
#Check for superusers
echo "Check for superusers"
grep -e ':x:0' /home/USERNAME/Conf/stdlog
#Check for user accts in Shadow
echo "Users in Shadow"
grep ':\$' /home/USERNAME/Conf/stdlog
#Check for Empty Password Accounts"
echo "Empty Password Holders"
awk -F: '(2 == " "){print}' /etc/shadow
#Check for Successful, opened or closed sessions by users
echo "Sessions Installed"
grep -e "installed" /home/USERNAME/Conf/stdlog | more
#Check for World Writeable Files
#Check Lynis Logs
echo "Lynis Logs Check"
grep 'warning\|suggestion\|details\|vulnerable\|listen_port' /var/log/lynis-report.dat
#Check RK Hunter Logs
echo "RK Hunter Log Check"
grep -e "Warning" /var/log/rkhunter.log
#Check for suspicious programs
echo "Suspicious Programs"
ps -eo pid,tty,user,args | less
#Check for who is logged on currently
echo "Whos on NOW"
w
echo "Added Users"
grep useradd /var/log/*
echo "Deleted Users"
grep userdel /var/log/*
echo "Check for recent altered files"
find . -mmin -5 -print
exit 0; | a2af0607a83c61f154320343eac711d20354169f | [
"Shell"
] | 3 | Shell | pparker0929/fickle | c813bf905ef3a11d822be96cae19357a792f485f | adfe6c6d29397d1287a0160927123ef3237c075a |
refs/heads/master | <repo_name>guomo233/TCP-Stack<file_sep>/create_randfile.sh
#!/bin/bash
dd if=/dev/urandom bs=2MB count=1 | base64 > client-input.dat
<file_sep>/include/retrans.h
// fix - retrans
#ifndef __RETRANSE_H__
#define __RETRANSE_H__
#include "tcp_sock.h"
#include "list.h"
#include "tcp_timer.h"
#include "ip.h"
#include "log.h"
#include "congestion_control.h"
#define TCP_CONTROL_ACK 0
#define TCP_DATA_ACK 1
struct snt_pkt
{
struct list_head list ;
char *packet ;
int len ;
int retrans_times ;
} ;
struct rcvd_pkt
{
struct list_head list ;
char *payload ;
u32 seq ;
int pl_len ;
} ;
static inline void retrans_pkt (struct tcp_sock *tsk, int inc)
{
struct snt_pkt *pkt_bak = list_entry (tsk->send_buf.next, struct snt_pkt, list) ;
char *packet = (char *) malloc (sizeof(char) * pkt_bak->len) ;
if (!packet)
return ;
memcpy (packet, pkt_bak->packet, pkt_bak->len) ;
ip_send_packet (packet, pkt_bak->len) ;
pkt_bak->retrans_times += inc ;
if (pkt_bak->retrans_times > 3)
{
log(DEBUG, "retrans 3 times") ;
//tcp_sock_close (tsk) ;
tcp_send_control_packet (tsk, TCP_RST) ;
tcp_set_state (tsk, TCP_CLOSED) ;
tcp_unset_retrans_timer (tsk) ;
if (!tsk->parent)
tcp_bind_unhash (tsk) ;
tcp_unhash (tsk) ; // auto free memory
}
else
{
tsk->retrans_timer.timeout = TCP_RETRANS_INTERVAL_INITIAL ;
for (int i=0; i<pkt_bak->retrans_times; i++)
tsk->retrans_timer.timeout *= 2 ;
}
/*struct iphdr *ip = packet_to_ip_hdr(packet);
struct tcphdr *tcp = (struct tcphdr *)((char *)ip + IP_BASE_HDR_SIZE);
int pl_len = ntohs(ip->tot_len) - IP_HDR_SIZE(ip) - TCP_HDR_SIZE(tcp) ;
log(DEBUG, "retrans seq:(%d,%d), snd_wnd:%d", ntohl(tcp->seq), (ntohl(tcp->seq) + pl_len), tsk->snd_wnd) ;*/
}
static inline void remove_ack_pkt (struct tcp_sock *tsk, int ack, int ack_type)
{
tcp_unset_retrans_timer (tsk);
struct snt_pkt *pkt, *temp ;
list_for_each_entry_safe (pkt, temp, &(tsk->send_buf), list)
{
struct tcphdr *tcp = packet_to_tcp_hdr (pkt->packet) ;
struct iphdr *ip = packet_to_ip_hdr (pkt->packet) ;
int pl_len = ntohs(ip->tot_len) - IP_BASE_HDR_SIZE - TCP_BASE_HDR_SIZE ;
int seq = ntohl(tcp->seq) ;
int seq_end = seq + pl_len ;
if ((ack_type == TCP_DATA_ACK && seq_end > seq && ack >= seq_end) ||
(ack_type == TCP_CONTROL_ACK))
{
//log(DEBUG, "ack:(%d, %d)", seq, seq_end);
//tsk->snd_wnd += pl_len ;
/*if (tsk->snd_wnd - pl_len <= 0)
wake_up (tsk->wait_send) ;*/
int old_snd_una = tsk->snd_una ;
tsk->snd_una += pl_len ;
if (tsk->snd_nxt - old_snd_una >= tsk->snd_wnd &&
tsk->snd_nxt - tsk->snd_una < tsk->snd_wnd)
wake_up (tsk->wait_send) ;
list_delete_entry (&(pkt->list)) ;
free (pkt->packet) ;
free (pkt) ;
}
}
//log(DEBUG, "received ack:%d, snd_una:%d", ack, tsk->snd_una) ;
if (!list_empty (&(tsk->send_buf)))
tcp_set_retrans_timer (tsk) ;
else if (tsk->cg_state == TCP_CG_LOSS)
{
//log(DEBUG, "from LOSS change to OPEN") ;
tsk->cg_state = TCP_CG_OPEN ;
}
}
#endif
<file_sep>/tcp_in.c
#include "tcp.h"
#include "tcp_sock.h"
#include "tcp_timer.h"
#include "log.h"
#include "ring_buffer.h"
#include "retrans.h" // fix
#include "congestion_control.h" // fix
#include <stdlib.h>
// update the snd_wnd of tcp_sock
//
// if the snd_wnd before updating is zero, notify tcp_sock_send (wait_send)
static inline void tcp_update_window(struct tcp_sock *tsk, struct tcp_cb *cb)
{
u16 old_snd_wnd = tsk->snd_wnd;
tsk->snd_wnd = cb->rwnd;
if (old_snd_wnd == 0)
wake_up(tsk->wait_send);
}
// update the snd_wnd safely: cb->ack should be between snd_una and snd_nxt
static inline void tcp_update_window_safe(struct tcp_sock *tsk, struct tcp_cb *cb)
{
if (less_or_equal_32b(tsk->snd_una, cb->ack) && less_or_equal_32b(cb->ack, tsk->snd_nxt))
tcp_update_window(tsk, cb);
}
#ifndef max
# define max(x,y) ((x)>(y) ? (x) : (y))
#endif
// check whether the sequence number of the incoming packet is in the receiving
// window
static inline int is_tcp_seq_valid(struct tcp_sock *tsk, struct tcp_cb *cb)
{
u32 rcv_end = tsk->rcv_nxt + max(tsk->rcv_wnd, 1);
if (less_than_32b(cb->seq, rcv_end) && less_or_equal_32b(tsk->rcv_nxt, cb->seq_end)) {
return 1;
}
else {
//log(ERROR, "received packet with invalid seq, drop it.");
//log(ERROR, "need (%d,%d), drop (%d,%d)", tsk->rcv_nxt, tsk->rcv_nxt + tsk->rcv_wnd, cb->seq, cb->seq_end);
return 0;
}
}
struct tcp_cb *fin_cb ;
// Process the incoming packet according to TCP state machine.
void tcp_process(struct tcp_sock *tsk, struct tcp_cb *cb, char *packet)
{
// RST
if (!tsk || tsk->state == TCP_CLOSED)
tcp_send_reset (cb) ;
else if (cb->flags == TCP_RST)
{
tcp_set_state (tsk, TCP_CLOSED) ;
if (!tsk->parent)
tcp_bind_unhash (tsk) ;
tcp_unhash (tsk) ; // auto free memory
}
// Connect
if (tsk->state == TCP_LISTEN && cb->flags == TCP_SYN)
{
struct tcp_sock *csk = alloc_tcp_sock () ;
csk->sk_sip = cb->daddr ;
csk->sk_sport = cb->dport ;
csk->sk_dip = cb->saddr ;
csk->sk_dport = cb->sport ;
csk->rcv_nxt = cb->seq_end ;
csk->parent = tsk ;
list_add_tail (&(csk->list), &(tsk->listen_queue)) ;
tcp_set_state (csk, TCP_SYN_RECV) ;
tcp_hash (csk) ;
tcp_send_control_packet (csk, TCP_SYN | TCP_ACK) ;
}
else if (tsk->state == TCP_SYN_SENT &&
cb->flags == (TCP_SYN | TCP_ACK) &&
cb->ack == tsk->snd_nxt)
{
tsk->rcv_nxt = cb->seq_end ;
tsk->snd_una++ ;
remove_ack_pkt (tsk, cb->ack, TCP_CONTROL_ACK) ;
tcp_update_window_safe (tsk, cb) ; // Update snd_wnd
tsk->adv_wnd = cb->rwnd ;
tsk->cwnd = TCP_MSS ;
tsk->ssthresh = cb->rwnd ;
tcp_set_state (tsk, TCP_ESTABLISHED) ;
tcp_send_control_packet (tsk, TCP_ACK) ;
wake_up (tsk->wait_connect) ;
}
else if (tsk->state == TCP_ESTABLISHED &&
cb->flags == (TCP_SYN | TCP_ACK) &&
cb->ack == tsk->snd_nxt) // prevent ACK loss
{
log(DEBUG, "resend ACK") ;
tcp_send_control_packet (tsk, TCP_ACK) ;
}
else if (tsk->state == TCP_SYN_RECV &&
cb->flags == TCP_ACK &&
cb->ack == tsk->snd_nxt)
{
if (tsk->parent && !tcp_sock_accept_queue_full (tsk->parent))
{
tsk->snd_una++ ;
tsk->cwnd = TCP_MSS ;
tsk->adv_wnd = cb->rwnd ;
tsk->ssthresh = cb->rwnd ;
remove_ack_pkt (tsk, cb->ack, TCP_CONTROL_ACK) ;
tcp_sock_accept_enqueue (tsk) ;
tcp_set_state (tsk, TCP_ESTABLISHED) ;
wake_up (tsk->parent->wait_accept) ;
}
}
// Close
if (tsk->state == TCP_ESTABLISHED &&
cb->flags == TCP_FIN &&
cb->seq == tsk->rcv_nxt)
{
tsk->rcv_nxt = cb->seq_end ;
tcp_set_state (tsk, TCP_CLOSE_WAIT) ;
tcp_send_control_packet (tsk, TCP_ACK) ;
wake_up (tsk->wait_recv) ;
}
else if (tsk->state == TCP_FIN_WAIT_1 &&
cb->flags == TCP_ACK &&
cb->ack == tsk->snd_nxt)
{
tsk->snd_una++ ;
remove_ack_pkt (tsk, cb->ack, TCP_CONTROL_ACK) ;
tcp_set_state (tsk, TCP_FIN_WAIT_2) ;
}
else if ((tsk->state == TCP_FIN_WAIT_2 ||
tsk->state == TCP_TIME_WAIT) &&
cb->flags == TCP_FIN &&
cb->seq == tsk->rcv_nxt)
{
tsk->rcv_nxt = cb->seq_end ;
tcp_set_state (tsk, TCP_TIME_WAIT) ;
tcp_send_control_packet (tsk, TCP_ACK) ;
tsk->rcv_nxt = cb->seq ; // for TIME_WAIT to receive FIN
//log(DEBUG, "receive FIN") ;
tcp_set_timewait_timer (tsk) ;
}
else if (tsk->state == TCP_LAST_ACK &&
cb->flags == TCP_ACK &&
cb->ack == tsk->snd_nxt)
{
tsk->snd_una++ ;
remove_ack_pkt (tsk, cb->ack, TCP_CONTROL_ACK) ;
tcp_set_state (tsk, TCP_CLOSED) ;
tcp_unhash (tsk) ; // auto free memory
}
else if (tsk->state == TCP_LAST_ACK &&
cb->flags == TCP_FIN &&
cb->ack == tsk->snd_nxt - 1) // prevent ACK loss
tcp_send_control_packet (tsk, TCP_ACK) ;
// drop
//if (!is_tcp_seq_valid (tsk, cb))
// return ;
// Receive data
if ((tsk->state == TCP_ESTABLISHED ||
tsk->state == TCP_FIN_WAIT_1 ||
tsk->state == TCP_FIN_WAIT_2) &&
cb->pl_len > 0)
{
if (cb->seq == tsk->rcv_nxt && cb->seq_end <= tsk->rcv_nxt + tsk->rcv_wnd)
{
int seq = cb->seq ;
int seq_end = cb->seq_end ;
int pl_len = cb->pl_len ;
char *payload = cb->payload ;
int wait_to_ack = 1 ;
while (wait_to_ack)
{
pthread_mutex_lock (&(tsk->rcv_buf->rw_lock)) ;
write_ring_buffer (tsk->rcv_buf, payload, pl_len) ;
tsk->rcv_nxt = seq_end ;
tsk->rcv_wnd -= pl_len ;
pthread_mutex_unlock (&(tsk->rcv_buf->rw_lock)) ;
if (list_empty (&(tsk->rcv_ofo_buf)))
break ;
wait_to_ack = 0 ;
struct rcvd_pkt *pkt_bak, *temp ;
list_for_each_entry_safe (pkt_bak, temp, &(tsk->rcv_ofo_buf), list)
{
if (pkt_bak->seq == tsk->rcv_nxt &&
pkt_bak->seq + pkt_bak->pl_len <= tsk->rcv_nxt + tsk->rcv_wnd)
{
pl_len = pkt_bak->pl_len ;
seq = pkt_bak->seq ;
seq_end = seq + pl_len ;
payload = pkt_bak->payload ;
list_delete_entry (&(pkt_bak->list)) ;
wait_to_ack = 1 ;
break ;
}
}
}
if (cb->pl_len > 0) // prevent zero window probe
wake_up (tsk->wait_recv) ;
}
else if (cb->seq > tsk->rcv_nxt && cb->seq_end <= tsk->rcv_nxt + tsk->rcv_wnd) // store
{
struct rcvd_pkt *pkt_bak = (struct rcvd_pkt *) malloc (sizeof(struct rcvd_pkt)) ;
pkt_bak->pl_len = cb->pl_len ;
pkt_bak->seq = cb->seq ;
pkt_bak->payload = (char *) malloc (sizeof(char) * cb->pl_len) ;
memcpy (pkt_bak->payload, cb->payload, cb->pl_len) ;
list_add_tail (&(pkt_bak->list), &(tsk->rcv_ofo_buf)) ;
}
//if (tsk->rcv_wnd <= 0)
// log(DEBUG, "rcv_wnd = 0") ;
//log(DEBUG, "send ack:%d, rcv_wnd = %d", tsk->rcv_nxt, tsk->rcv_wnd) ;
tcp_send_control_packet (tsk, TCP_ACK) ;
}
// Receive ACK about sent data
if ((tsk->state == TCP_ESTABLISHED ||
tsk->state == TCP_FIN_WAIT_1 ||
tsk->state == TCP_FIN_WAIT_2 ||
tsk->state == TCP_CLOSE_WAIT) &&
cb->flags == TCP_ACK)
{
if (cb->ack > tsk->snd_una) // receive new ack
{
remove_ack_pkt (tsk, cb->ack, TCP_DATA_ACK) ;
if (tsk->cg_state == TCP_CG_RECOVERY &&
cb->ack < tsk->recovery_point) // partial ack
{
//log(DEBUG, "RECOVERY: fast retrans") ;
retrans_pkt (tsk, 0) ;
}
else if (tsk->cg_state != TCP_CG_OPEN) // full ack || cg_state == TCP_CG_DISORDER
{
//log(DEBUG, "change to OPEN") ;
tsk->cg_state = TCP_CG_OPEN ;
tsk->dupack_times = 0 ;
}
if (tsk->cg_state == TCP_CG_OPEN ||
tsk->cg_state == TCP_CG_DISORDER)
{
if (tsk->cwnd < tsk->ssthresh) // slow start
tsk->cwnd += TCP_MSS ;
else // congestion advoidance
tsk->cwnd += (TCP_MSS * 1.0 / tsk->cwnd) * TCP_MSS ;
}
}
else if (cb->ack == tsk->snd_una) // receive dup ack
{
//log(DEBUG, "dupack:%d", cb->ack) ;
if (tsk->cg_state != TCP_CG_LOSS)
tsk->dupack_times++ ;
if (tsk->dupack_times == 1) // OPEN
{
//log(DEBUG, "change to DISORDER") ;
tsk->cg_state = TCP_CG_DISORDER ;
}
else if (tsk->dupack_times == 3) // OPEN -> RECOVERY
{
tsk->cg_state = TCP_CG_RECOVERY ;
tsk->recovery_point = tsk->snd_nxt ;
//log(DEBUG, "change to RECOVERY: fast retrans ") ;
retrans_pkt (tsk, 0) ;
tsk->ssthresh = tsk->cwnd / 2 ;
tsk->cwnd = tsk->ssthresh + 3 * TCP_MSS ;
}
else if (tsk->dupack_times > 3) // RECOVERY
{
tsk->cwnd += TCP_MSS ;
//log(DEBUG, "RECOVERY: fast retrans") ;
retrans_pkt (tsk, 0) ;
}
}
int old_adv_wnd = tsk->adv_wnd ;
tsk->adv_wnd = cb->rwnd ;
if (old_adv_wnd <= 0 && tsk->adv_wnd > 0)
{
tcp_unset_zwp_timer (tsk) ;
//log(DEBUG, "unset zwp timer") ;
wake_up (tsk->wait_send) ;
}
}
/*FILE *cwnd_fp ;
cwnd_fp = fopen ("cwnd.txt", "a+") ;
if (cwnd_fp && cb->flags == TCP_ACK)
{
fprintf (cwnd_fp, "%d\n", tsk->cwnd) ;
fclose (cwnd_fp) ;
}*/
//fprintf(stdout, "TODO: implement %s please.\n", __FUNCTION__);
}
<file_sep>/tcp_apps.c
#include "tcp_sock.h"
#include "log.h"
#include <unistd.h>
#define BUF_SIZE 1000
// tcp server application, listens to port (specified by arg) and serves only one
// connection request
void *tcp_server(void *arg)
{
u16 port = *(u16 *)arg;
struct tcp_sock *tsk = alloc_tcp_sock();
struct sock_addr addr;
addr.ip = htonl(0);
addr.port = port;
if (tcp_sock_bind(tsk, &addr) < 0) {
log(ERROR, "tcp_sock bind to port %hu failed", ntohs(port));
exit(1);
}
if (tcp_sock_listen(tsk, 3) < 0) {
log(ERROR, "tcp_sock listen failed");
exit(1);
}
log(DEBUG, "listen to port %hu.", ntohs(port));
struct tcp_sock *csk = tcp_sock_accept(tsk);
log(DEBUG, "accept a connection.");
char rbuf[BUF_SIZE];
FILE *file = fopen("server-output.dat", "wb");
while (1) {
int rlen = tcp_sock_read(csk, rbuf, BUF_SIZE);
if (rlen == 0) {
log(DEBUG, "tcp_sock_read return 0, finish transmission.");
break;
}
else if (rlen > 0) {
fwrite(rbuf, 1, rlen, file);
}
}
fclose(file);
log(DEBUG, "close this connection.");
printf("server: close tsk.\n");
tcp_sock_close(csk);
return NULL;
}
// tcp client application, connects to server (ip:port specified by arg), and
// send file to it.
void *tcp_client(void *arg)
{
struct sock_addr *skaddr = arg;
struct tcp_sock *tsk = alloc_tcp_sock();
if (tcp_sock_connect(tsk, skaddr) < 0) {
log(ERROR, "tcp_sock connect to server ("IP_FMT":%hu)failed.", \
NET_IP_FMT_STR(skaddr->ip), ntohs(skaddr->port));
exit(1);
}
char buf[BUF_SIZE];
FILE *file = fopen("client-input.dat", "rb");
while (!feof(file)) {
int ret_size = fread(buf, 1, BUF_SIZE, file);
tcp_sock_write(tsk, buf, ret_size);
if (ret_size < BUF_SIZE) break;
//usleep(500000);
}
fclose(file);
printf("client: close tsk.\n");
tcp_sock_close(tsk);
return NULL;
}
<file_sep>/include/congestion_control.h
#ifndef __CONGESTION_CONTROL_H__
#define __CONGESTION_CONTROL_H__
#include "tcp_sock.h"
#define TCP_CG_OPEN 0
#define TCP_CG_DISORDER 1
#define TCP_CG_RECOVERY 2
#define TCP_CG_LOSS 3
#endif
<file_sep>/tcp_timer.c
#include "tcp.h"
#include "tcp_timer.h"
#include "tcp_sock.h"
#include "retrans.h" // fix
#include "congestion_control.h" // fix
#include <stdio.h>
#include <unistd.h>
static struct list_head timer_list;
// scan the timer_list, find the tcp sock which stays for at 2*MSL, release it
void tcp_scan_timer_list()
{
struct tcp_timer *timer, *temp ;
list_for_each_entry_safe (timer, temp, &timer_list, list)
{
timer->timeout -= TCP_TIMER_SCAN_INTERVAL ;
if (timer->timeout > 0)
continue ;
if (timer->type == 0)
{
struct tcp_sock *tsk = timewait_to_tcp_sock (timer) ;
tcp_set_state (tsk, TCP_CLOSED) ;
tcp_unhash (tsk) ;
if (!tsk->parent)
tcp_bind_unhash (tsk) ; // auto free memory
list_delete_entry (&(timer->list)) ;
}
else if (timer->type == 1) // retrans
{
struct tcp_sock *tsk = retranstimer_to_tcp_sock (timer) ;
retrans_pkt (tsk, 1) ;
if (tsk->cg_state != TCP_CG_LOSS)
{
tsk->ssthresh = tsk->cwnd / 2 ;
tsk->cwnd = TCP_MSS ;
tsk->dupack_times = 0 ;
tsk->cg_state = TCP_CG_LOSS ;
log(DEBUG, "change to LOSS") ;
}
}
else // type = 2, zero window probe
{
struct tcp_sock *tsk = zwptimer_to_tcp_sock (timer) ;
int hdr_size = ETHER_HDR_SIZE + IP_BASE_HDR_SIZE + TCP_BASE_HDR_SIZE ;
char *packet = (char *) malloc (sizeof(char) * hdr_size) ;
tcp_send_packet (tsk, packet, hdr_size) ;
tsk->zwp_times++ ;
if (tsk->zwp_times > 3)
{
log(DEBUG, "3 times zero window probe") ;
//tcp_sock_close (tsk) ;
tcp_send_control_packet (tsk, TCP_RST) ;
tcp_set_state (tsk, TCP_CLOSED) ;
tcp_unset_zwp_timer (tsk) ;
if (!tsk->parent)
tcp_bind_unhash (tsk) ;
tcp_unhash (tsk) ; // auto free memory
}
else
{
timer->timeout = TCP_ZERO_WINDOW_PROBE_INITIAL ;
for (int i=0; i<tsk->zwp_times; i++)
timer->timeout *= 2 ;
}
}
}
//fprintf(stdout, "TODO: implement %s please.\n", __FUNCTION__);
}
// set the timewait timer of a tcp sock, by adding the timer into timer_list
void tcp_set_timewait_timer(struct tcp_sock *tsk)
{
tsk->timewait.type = 0 ;
tsk->timewait.timeout = TCP_TIMEWAIT_TIMEOUT ;
if (list_empty(&(tsk->timewait.list)))
list_add_tail (&(tsk->timewait.list), &timer_list) ;
//fprintf(stdout, "TODO: implement %s please.\n", __FUNCTION__);
}
// set the retrans timer of a tcp sock, by adding the timer into timer_list
void tcp_set_retrans_timer(struct tcp_sock *tsk)
{
tsk->retrans_timer.type = 1 ;
tsk->retrans_timer.timeout = TCP_RETRANS_INTERVAL_INITIAL ;
list_add_tail (&(tsk->retrans_timer.list), &timer_list) ;
//fprintf(stdout, "TODO: implement %s please.\n", __FUNCTION__);
}
// unset the retrans timer of a tcp sock, by removing the timer from timer_list
void tcp_unset_retrans_timer(struct tcp_sock *tsk)
{
if (!list_empty (&(tsk->retrans_timer.list)))
list_delete_entry (&(tsk->retrans_timer.list)) ;
//fprintf(stdout, "TODO: implement %s please.\n", __FUNCTION__);
}
// fix - zero window probe
void tcp_set_zwp_timer (struct tcp_sock *tsk)
{
tsk->zwp_times = 0 ;
tsk->zwp_timer.type = 2 ;
tsk->zwp_timer.timeout = TCP_ZERO_WINDOW_PROBE_INITIAL ;
list_add_tail (&(tsk->zwp_timer.list), &timer_list) ;
}
// fix - zero window probe
void tcp_unset_zwp_timer (struct tcp_sock *tsk)
{
if (!list_empty (&(tsk->zwp_timer.list)))
list_delete_entry (&(tsk->zwp_timer.list)) ;
}
// scan the timer_list periodically by calling tcp_scan_timer_list
void *tcp_timer_thread(void *arg)
{
init_list_head(&timer_list);
while (1) {
usleep(TCP_TIMER_SCAN_INTERVAL);
tcp_scan_timer_list();
}
return NULL;
}
<file_sep>/README.md
# TCP-Stack
Mininet 网络环境下对 TCP 协议栈主要功能的实现,包括:链接建立(三次握手)、链接释放(四次挥手)、可靠传输(超时重传)、流量控制(包含窗口探测)、拥塞控制(慢启动、拥塞避免、快速重传/快速恢复等)
## 项目说明
在装好 Mininet 后通过 `make` 编译该项目,通过 `sudo python tcp_topo_loss.py` 可以在 Mininet 中搭建一个5%丢包率的拓扑网络结构,通过 `xterm h1 h2` 可以分别打开两个待通信节点的终端

将 h1(10.0.0.1)作为服务端,h2(10.0.0.2)作为客户端,h1 通过 `./tcp_stack server 10001` 对 10001 端口进行监听,

h2 通过 `./tcp_stack client 10.0.0.1 10001` 请求与 h1 的 10001 端口建立 TCP 链接

h2 将随机生成的文件 `client-input.dat` 通过 TCP 双方完成了链接建立(三次握手)、数据传输(可靠传输、流量控制、拥塞避免)、链接释放(四次挥手)等过程传送到 h1,名为 `server-output.dat`
下图为 h1 的过程:

下图为 h2 的过程:

通过 `md5sum` 命令检验文件是否无差错的传送了

如下是传输过程中拥塞控制导致拥塞窗口的变化过程(进行了 19547 次采样)

| 10ad39bdbcecd0999651054ca66263f98669c399 | [
"Markdown",
"C",
"Shell"
] | 7 | Shell | guomo233/TCP-Stack | df1e2c3110af6ef45ebb6c550fcfc7b20ebe7f5b | 291c1123fda370ee6b774e05204854bb70aa75b9 |
refs/heads/master | <repo_name>mjetconnor/mindjetgraph<file_sep>/js/mjAuth.js
/* mjAuth.js */
/* Parse query parameter style name/value pairs into an associative array,
(IOW a simple Javascript object)
*/
function parseParams(paramStr) {
if (!paramStr)
return {};
var map = {};
var arr = paramStr.split('&');
for (var spl, i = 0; i < arr.length; i++) {
spl = arr[i].split('=');
map[spl[0]] = decodeURIComponent(spl[1]);
}
return map;
}
var authModule = angular.module('authModule', []);
authModule.factory('authenticator', function(){
var auth = {
authorityUrl: null,
authorityError: null,
accessToken: null,
meUri: null,
homeUri: null,
/* change who the authentication authority is */
setAuthority: function(authUrl) {
auth.authorityUrl = authUrl;
auth.authorityError = null;
},
/* perform an authentication using the currently configured authority */
authenticate: function() {
if (auth.authorityError || !auth.authorityUrl)
return;
var baseUrl = window.location.href;
baseUrl = /^([^#]*)/.exec(baseUrl)[1]; // the location without the hash
console.log('reauthenticating...');
var redirUrl = auth.authorityUrl
+ '/oauth/authorize?response_type=token&client_id=X2nbuI4GnGQ9&redirect_uri='
+ encodeURIComponent(baseUrl) + '&state=' + encodeURIComponent(auth.authorityUrl);
window.location = redirUrl;
},
/* do this on entry to the app */
checkOnEntry: function() {
// Check if we are receiving a return redirection that contains access info in the hash tag
var hash = window.location.hash;
if (hash) {
var params = parseParams(hash.replace(/^\#/,''));
if (params.error) {
auth.authorityError = params.error;
return;
}
var token = params.access_token;
if (token) {
auth.accessToken = token;
auth.meUri = params.userId;
auth.homeUri = params.communityId;
auth.authorityUrl = params.state;
var cookieScope = {expires: 365, path: '/'};
$.cookie('mjDemoAccessToken', token, cookieScope);
$.cookie('mjDemoMeId', auth.meUri, cookieScope);
$.cookie('mjDemoHomeId', auth.homeUri, cookieScope);
$.cookie('mjDataSource', auth.authorityUrl, cookieScope);
// hide the auth info by navigating to the same URL without the hash tag
window.location.hash = null;
return;
}
}
// Look for access info in cookies
auth.accessToken = $.cookie('mjDemoAccessToken');
auth.meUri = $.cookie('mjDemoMeId');
auth.homeUri = $.cookie('mjDemoHomeId');
auth.authorityUrl = $.cookie('mjDataSource');
// If nothing in the cookies, gotta authenticate now
if ((!auth.accessToken || !auth.meUri) && auth.authorityUrl) {
auth.authenticate();
}
}
};
return auth;
});
authModule.run(function(authenticator) {
authenticator.checkOnEntry();
});
<file_sep>/README.txt
Useful tools for accessing the Mindjet Graph API.
| bdb8add9334b1a4936b4b27d35cff15a98d7737c | [
"JavaScript",
"Text"
] | 2 | JavaScript | mjetconnor/mindjetgraph | cd3c24bdeb9410bc2625b36c83fb53322685e690 | 3bb5b279069329a3beb8884255ae452455388a92 |
refs/heads/main | <repo_name>xhoangluong5567/js2018<file_sep>/slide.js
var i = 0; // Đặt biến i = 0
var img = []; // Đặt một mảng tên là img
var time = 2000; // đặt biến time = 2000 , 2000 là 2000 mili giây = 2 giây
img[0] = 'img/dulichbien.jpg'; // bỏ ảnh vào
img[1] = 'img/dulichnui.jpg';
img[2] = 'img/dulichvn.png';
// tiếp theo tạo 1 sự kiện function tên là doiAnh
function doiAnh(){
document.slide.src = img[i]; // truyền ảnh vào slide
if(i < img.length - 1){ // nếu như i < độ dài của mảng img trừ 1 thì i tăng dần
i++;
} else {
i = 0; // ngược lại i = 0
}
setTimeout("doiAnh()",time); // setTimeout là chạy sự kiện doiAnh , time là thời gian đổi
}
window.onload = doiAnh; // Dòng này là gọi hàm để cho chạy chương trình
<file_sep>/animation.js
function myFunction() {
document.getElementById("demo").innerHTML = "Rất tiếc hiện tại vẫn chưa có chương trình khuyến mãi trong tháng tới.Quý khách vui lòng quay lại sau. Xin cám ơn!";
}<file_sep>/dattuor.js
function checkInfo() {
var user = document.getElementById('user').value;
var email = document.getElementById('email').value;
var tour = document.getElementById('tour').value;
var noidung = document.getElementById('noidung').value;
if(user == ""){
document.getElementById('username').innerHTML = "** <NAME>";
return false;
}
else if (email == ""){
document.getElementById('emails').innerHTML = "** Mời nhập Email";
return false;
}
else if (tour == ""){
document.getElementById('tours').innerHTML = "** Mời nhập Tour";
return false;
}
else if (noidung == ""){
document.getElementById('noidungs').innerHTML = "** Mời nhập Nội dung";
return false;
}
else if(email.indexOf('@') <=0){
document.getElementById('emails').innerHTML = "** Vị trí @ không hợp lệ";
return false;
}
else{
alert('Gửi thành công');
}
} | f1f4613375512ddc9cf5128c0207c97498000347 | [
"JavaScript"
] | 3 | JavaScript | xhoangluong5567/js2018 | 6c8398d3734e7aeda1e0d58565933b9f267581b3 | 705c4f57c5ad644d3713bf883d57f18cc80edcac |
refs/heads/master | <repo_name>dslztx/java_object_size<file_sep>/src/main/java/sizeofagent/LayoutSizeCalculator.java
package sizeofagent;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
/**
* @author dslztx
* @date 2016Äê09ÔÂ21ÈÕ
*/
public class LayoutSizeCalculator {
private static SizeTable sizeTable;
private static final char[] CC = new char[] {'0', '0', '0', '0', '0', '0', '0', '1'};
private static Map<Class, ClassInfo> cache = new HashMap<Class, ClassInfo>();
static {
// default setting is 32 bits JDK
int bits = 32;
try {
// may be 32 or 64
bits = Integer.valueOf(System.getProperty("sun.arch.data.model"));
} catch (Exception e) {
e.printStackTrace();
}
sizeTable = new SizeTable(bits);
}
/**
* compute Java Object Size itself other than recursively
*
* @param obj
* @return
*/
public static long sizeOf(Object obj) {
if (obj == null) {
return 0;
}
Class clz = obj.getClass();
if (clz.isArray()) {
int len = Array.getLength(obj);
Class elementClz = clz.getComponentType();
long totalExcludePadding = sizeTable.arrayHeader() + len * sizeTable.fieldType(elementClz);
long padding = sizeTable.padding(totalExcludePadding);
return totalExcludePadding + padding;
} else {
if (cache.get(clz) == null) {
build(clz);
}
ClassInfo clzInfo = cache.get(clz);
long totalExcludePadding =
sizeTable.markWord() + sizeTable.classPointer() + clzInfo.getAncestorSize() + clzInfo.getSelfSize();
long padding = sizeTable.padding(totalExcludePadding);
return totalExcludePadding + padding;
}
}
/**
* compute Java Object Size recursively
*
* @param obj
* @return
*/
public static long graphSizeOf(Object obj) {
if (obj == null) {
return 0;
}
Queue<Object> queue = new LinkedList<Object>();
IdentitySet<Object> visited = new IdentitySet<Object>();
long total = 0;
queue.add(obj);
while (!queue.isEmpty()) {
total += internalSizeOf(queue.poll(), queue, visited);
}
return total;
}
private static ClassInfo build(Class clz) {
if (cache.get(clz) != null) {
return cache.get(clz);
}
if (clz == Object.class) {
ClassInfo clzInfo = new ClassInfo();
cache.put(clz, clzInfo);
return clzInfo;
}
ClassInfo superClzInfo = build(clz.getSuperclass());
ClassInfo clzInfo = new ClassInfo();
long totalExcludePadding =
superClzInfo.getAncestorSize() + superClzInfo.getExtra() + superClzInfo.getSelfSize();
long padding = sizeTable.paddingSuperClass(totalExcludePadding);
clzInfo.setAncestorSize(totalExcludePadding + padding);
List<Field> fieldList = new LinkedList<Field>();
long selfSize = 0;
char[] c = new char[8];
for (int index = 0; index < c.length; index++) {
c[index] = '0';
}
int size;
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
size = sizeTable.fieldType(field.getType());
selfSize += size;
c[size - 1] = '1';
if (!field.getType().isPrimitive()) {
field.setAccessible(true);
fieldList.add(field);
}
}
clzInfo.setSelfSize(selfSize);
if (sizeTable.is32Bits() && (totalExcludePadding + padding) % 8 != 0 && Arrays.equals(c, CC)) {
clzInfo.setExtra(4);
}
fieldList.addAll(superClzInfo.getFields());
clzInfo.setFields(fieldList);
cache.put(clz, clzInfo);
return clzInfo;
}
private static long internalSizeOf(Object obj, Queue<Object> queue, IdentitySet<Object> visited) {
if (visited.contains(obj)) {
return 0;
}
Class clz = obj.getClass();
long totalExcludePadding = 0;
long padding = 0;
if (clz.isArray()) {
int len = Array.getLength(obj);
Class elementClz = clz.getComponentType();
if (len != 0 && !elementClz.isPrimitive()) {
for (int index = 0; index < len; index++) {
Object target = Array.get(obj, index);
if (target != null) {
queue.add(target);
}
}
}
totalExcludePadding = sizeTable.arrayHeader() + len * sizeTable.fieldType(elementClz);
padding = sizeTable.padding(totalExcludePadding);
} else {
if (cache.get(clz) == null) {
build(clz);
}
ClassInfo clzInfo = cache.get(clz);
for (Field field : clzInfo.getFields()) {
try {
Object target = field.get(obj);
if (target != null) {
queue.add(target);
}
} catch (Exception e) {
e.printStackTrace();
}
}
totalExcludePadding =
sizeTable.markWord() + sizeTable.classPointer() + clzInfo.getAncestorSize() + clzInfo.getSelfSize();
padding = sizeTable.padding(totalExcludePadding);
}
visited.add(obj);
return totalExcludePadding + padding;
}
}
/**
* compare reference,not content
*
* @param <E>
*/
class IdentitySet<E> {
IdentityHashMap<E, Object> map = new IdentityHashMap<E, Object>();
public void add(E obj) {
map.put(obj, null);
}
public boolean contains(E obj) {
return map.containsKey(obj);
}
}
class ClassInfo {
/**
* the size after align
*/
long ancestorSize = 0;
long selfSize = 0;
long extra = 0;
List<Field> fields = new LinkedList<Field>();
public long getAncestorSize() {
return ancestorSize;
}
public void setAncestorSize(long ancestorSize) {
this.ancestorSize = ancestorSize;
}
public long getSelfSize() {
return selfSize;
}
public void setSelfSize(long selfSize) {
this.selfSize = selfSize;
}
public long getExtra() {
return extra;
}
public void setExtra(long extra) {
this.extra = extra;
}
public List<Field> getFields() {
return fields;
}
public void setFields(List<Field> fields) {
this.fields = fields;
}
}
<file_sep>/README.md
1、doc/first_method下资源来自:http://openjdk.java.net/projects/code-tools/jol<br/>
2、doc/second_method下资源来自:http://www.javaspecialists.co.za/archive/Issue078.html<br/>
3、doc/third_method下资源来自:https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/objectsize/ObjectSizeCalculator.java<br/>
4、doc/fourth_method下资源来自:http://jroller.com/maxim/entry/again_about_determining_size_of<br/>
5、doc/fifth_method下资源来自:http://www.javamex.com/classmexer/<br/>
6、“java-object-size.jar”包在本项目下执行“mvn package”命令得到<br/>
7、由测试结果可知:“MemoryCounter.java”实现有瑕疵,使用“jol-core-0.3.2.jar”不稳定,“ObjectSizeCalculator”实现也有瑕疵<br/>
8、要使用基于“java.lang.instrument.Instrumentation”的方式,必须指定“-javaagent”命令行参数<br/>
9、如何使用?根据是否基于“java.lang.instrument.Instrumentation”,采用如下两种方式的其中一种:
```
java -javaagent:java-object-size.jar -classpath ".:java-object-size.jar" YourMainClass
java -classpath ".:java-object-size.jar" YourMainClass
```
<file_sep>/src/test/java/sizeofagent/Main.java
package sizeofagent;
import com.javamex.classmexer.MemoryUtil;
import org.openjdk.jol.info.GraphLayout;
import sizeof.agent.SizeOfAgent;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// 48
MyObject a = new MyObject();
// 72
MyObject2 b = new MyObject2();
// 816
long[] c = new long[100];
for (int i = 0; i < 100; i++) {
c[i] = i;
}
// 5216
MyObject[] d = new MyObject[100];
for (int i = 0; i < 100; i++) {
d[i] = new MyObject();
}
// 32
C e = new C();
Set<Object> set = new HashSet<Object>();
set.add(a);
set.add(b);
set.add(c);
set.add(d);
set.add(e);
set.addAll(Arrays.asList(StringGenerator.generate(100000)));
long aSize = LayoutSizeCalculator.graphSizeOf(a);
long bSize = LayoutSizeCalculator.graphSizeOf(b);
long cSize = LayoutSizeCalculator.graphSizeOf(c);
long dSize = LayoutSizeCalculator.graphSizeOf(d);
long eSize = LayoutSizeCalculator.graphSizeOf(e);
long setSize = LayoutSizeCalculator.graphSizeOf(set);
System.out.println("\nCur Project Layout Algorithm");
System.out.println("" + aSize + "," + bSize + "," + cSize + "," + dSize + "," + eSize + "," + setSize);
long aSize2 = AgentSizeCalculator.graphSizeOf(a);
long bSize2 = AgentSizeCalculator.graphSizeOf(b);
long cSize2 = AgentSizeCalculator.graphSizeOf(c);
long dSize2 = AgentSizeCalculator.graphSizeOf(d);
long eSize2 = AgentSizeCalculator.graphSizeOf(e);
long setSize2 = AgentSizeCalculator.graphSizeOf(set);
System.out.println("\nCur Project Agent Algorithm");
System.out.println("" + aSize2 + "," + bSize2 + "," + cSize2 + "," + dSize2 + "," + eSize2 + "," + setSize2);
test1(a, b, c, d, e, set);
test2(a, b, c, d, e, set);
test3(a, b, c, d, e, set);
test4(a, b, c, d, e, set);
test5(a, b, c, d, e, set);
}
private static void test5(MyObject a, MyObject2 b, long[] c, MyObject[] d, C e, Set<Object> set) {
long aSize = MemoryUtil.deepMemoryUsageOf(a, MemoryUtil.VisibilityFilter.ALL);
long bSize = MemoryUtil.deepMemoryUsageOf(b, MemoryUtil.VisibilityFilter.ALL);
long cSize = MemoryUtil.deepMemoryUsageOf(c, MemoryUtil.VisibilityFilter.ALL);
long dSize = MemoryUtil.deepMemoryUsageOf(d, MemoryUtil.VisibilityFilter.ALL);
long eSize = MemoryUtil.deepMemoryUsageOf(e, MemoryUtil.VisibilityFilter.ALL);
long setSize = MemoryUtil.deepMemoryUsageOf(set, MemoryUtil.VisibilityFilter.ALL);
System.out.println("\nClassMexer.jar Algorithm");
System.out.println("" + aSize + "," + bSize + "," + cSize + "," + dSize + "," + eSize + "," + setSize);
}
private static void test4(MyObject a, MyObject2 b, long[] c, MyObject[] d, C e, Set<Object> set) {
long aSize = SizeOfAgent.fullSizeOf(a);
long bSize = SizeOfAgent.fullSizeOf(b);
long cSize = SizeOfAgent.fullSizeOf(c);
long dSize = SizeOfAgent.fullSizeOf(d);
long eSize = SizeOfAgent.fullSizeOf(e);
long setSize = SizeOfAgent.fullSizeOf(set);
System.out.println("\nSizeOfAgent.jar Algorithm");
System.out.println("" + aSize + "," + bSize + "," + cSize + "," + dSize + "," + eSize + "," + setSize);
}
private static void test3(MyObject a, MyObject2 b, long[] c, MyObject[] d, C e, Set<Object> set) {
long aSize = ObjectSizeCalculator.getObjectSize(a);
long bSize = ObjectSizeCalculator.getObjectSize(b);
long cSize = ObjectSizeCalculator.getObjectSize(c);
long dSize = ObjectSizeCalculator.getObjectSize(d);
long eSize = ObjectSizeCalculator.getObjectSize(e);
long setSize = ObjectSizeCalculator.getObjectSize(set);
System.out.println("\nObjectSizeCalculator Algorithm");
System.out.println("" + aSize + "," + bSize + "," + cSize + "," + dSize + "," + eSize + "," + setSize);
}
private static void test2(MyObject a, MyObject2 b, long[] c, MyObject[] d, C e, Set<Object> set) {
MemoryCounter counter = new MemoryCounter();
long aSize = counter.estimate(a);
long bSize = counter.estimate(b);
long cSize = counter.estimate(c);
long dSize = counter.estimate(d);
long eSize = counter.estimate(e);
long setSize = counter.estimate(set);
System.out.println("\nMemoryCounter Algorithm");
System.out.println("" + aSize + "," + bSize + "," + cSize + "," + dSize + "," + eSize + "," + setSize);
}
private static void test1(MyObject a, MyObject2 b, long[] c, MyObject[] d, C e, Set<Object> set) {
long aSize = GraphLayout.parseInstance(a).totalSize();
long bSize = GraphLayout.parseInstance(b).totalSize();
long cSize = GraphLayout.parseInstance(c).totalSize();
long dSize = GraphLayout.parseInstance(d).totalSize();
long eSize = GraphLayout.parseInstance(e).totalSize();
long setSize = GraphLayout.parseInstance(set).totalSize();
System.out.println("\njol.jar Algorithm");
System.out.println("" + aSize + "," + bSize + "," + cSize + "," + dSize + "," + eSize + "," + setSize);
}
}
class MyObject {
boolean a;
byte b;
char c;
short d;
int e;
float f;
long g;
double h;
Object i;
}
class MyObject2 extends MyParent {
boolean a;
byte b;
char c;
short d;
int e;
float f;
long g;
double h;
Object i;
}
class MyParent {
int a;
int b;
char c;
Object j;
Object k;
Object l;
}
class A {
int a;
}
class B extends A {
long b;
}
class C extends B {
char c;
}
<file_sep>/src/main/java/sizeofagent/SizeTable.java
package sizeofagent;
/**
* @author dslztx
* @date 2016Äê09ÔÂ11ÈÕ
*/
public class SizeTable {
private int bits;
public SizeTable(int bits) {
this.bits = bits;
}
public int markWord() {
if (bits == 64) {
return 8;
} else {
return 4;
}
}
public int classPointer() {
if (bits == 64) {
return 8;
} else {
return 4;
}
}
public int arrayHeader() {
if (bits == 64) {
return (8 + 8 + 4) + 4;
} else {
return 4 + 4 + 4;
}
}
public int fieldType(Class clz) {
if (clz == boolean.class || clz == byte.class) {
return 1;
} else if (clz == char.class || clz == short.class) {
return 2;
} else if (clz == int.class || clz == float.class) {
return 4;
} else if (clz == long.class || clz == double.class) {
return 8;
} else {
if (bits == 64) {
return 8;
} else {
return 4;
}
}
}
public int padding(long curByteSize) {
if (curByteSize % 8 == 0) {
return 0;
} else {
return (int) (8 - (curByteSize % 8));
}
}
public int paddingSuperClass(long curByteSize) {
int paddingLen = 8;
if (bits == 32) {
paddingLen = 4;
}
if (curByteSize % paddingLen == 0) {
return 0;
} else {
return (int) (paddingLen - (curByteSize % paddingLen));
}
}
public boolean is32Bits() {
return bits == 32;
}
}
| 0c6b202e01c842acdc8e35bc7390144ff3849a8e | [
"Markdown",
"Java"
] | 4 | Java | dslztx/java_object_size | 32d48e29c795f8f64ab2838e143702846d80c121 | 278969742212fff5d22a775062edaaa9296fc41f |
refs/heads/master | <repo_name>billhett/ShowerTimer<file_sep>/ShowerTimer WatchKit Extension/InterfaceController.swift
//
// InterfaceController.swift
// ShowerTimer WatchKit Extension
//
// Created by <NAME> on 3/23/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import WatchKit
import Foundation
import UIKit
class InterfaceController: WKInterfaceController {
@IBOutlet var todaysDateLabel: WKInterfaceDate!
@IBOutlet var myTimer: WKInterfaceTimer!
@IBOutlet var showerDayLabel: WKInterfaceLabel!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
let currentDate = NSDate()
let myday = Date()
let cal = Calendar.current
let dayofyear = cal.ordinality(of: .day, in: .year, for: myday)
//showerDayLabel.setText("Day of Year: \(dayofyear!)")
if dayofyear!%2 == 0{
showerDayLabel.setTextColor(UIColor.green)
showerDayLabel.setText("A long Shower")
} else {
showerDayLabel.setTextColor(UIColor.red)
showerDayLabel.setText("Not a long Shower")
}
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
@IBAction func startTapped() {
var currentDateTime = NSDate()
myTimer.setDate(currentDateTime as Date)
myTimer.start()
}
@IBAction func stopTapped() {
myTimer.stop()
}
func startTimer() {
var currentDateTime = NSDate()
myTimer.setDate(currentDateTime as Date)
myTimer.start()
}
}
| bb0b77af1438fabc21f9fbe67343098c458f8950 | [
"Swift"
] | 1 | Swift | billhett/ShowerTimer | 92d324fb6997086dfbeddc978aaccfc1c3e7118c | fafe320a38847db9d3a82abc0bce9bf8aedc4218 |
refs/heads/master | <repo_name>IkeCode-SmartSolutions/WeeERP<file_sep>/UI/Themes/Wee.Theme.Remark/Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Wee.Common.Contracts;
namespace Wee.Theme.Remark
{
public class Startup
{
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Wee.Theme.Remark :: Running...");
});
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/IWeeTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Wee.UI.Core.TagHelpers
{
/// <summary>
///
/// </summary>
/// <typeparam name="TBaseClass"></typeparam>
public interface IWeeTagHelper<TBaseClass>
where TBaseClass : TagHelper
{
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/WeeTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Razor;
using System.Reflection;
using Microsoft.AspNetCore.Razor.Runtime.TagHelpers;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Razor.TagHelpers;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Wee.UI.Core.TagHelpers
{
/// <summary>
///
/// </summary>
/// <typeparam name="TBaseClass"></typeparam>
public abstract class WeeTagHelper<TBaseClass> : TagHelper
where TBaseClass : TagHelper
{
protected readonly IServiceProvider ServiceProvider;
//protected readonly IAweOverrideTagHelper<TBaseClass> Overrider;
public WeeTagHelper(IServiceProvider serviceProvider/*, IAweOverrideTagHelper<TBaseClass> overrider*/)
{
ServiceProvider = serviceProvider;
//Overrider = overrider;
}
public abstract TBaseClass Self { get; }
public abstract TagBuilder Builder { get; }
public abstract Task ProcessAsync(TagBuilder builder, TagHelperContext context, TagHelperOutput output);
public sealed override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
await ProcessAsync(Builder, context, output);
var customImplementations = ServiceProvider.GetServices<IWeeOverrideTagHelper<TBaseClass>>();
if (customImplementations != null & customImplementations.Count() > 0)
{
foreach (var impl in customImplementations)
{
impl.CustomProcess(Self, Builder, context, output);
}
}
await base.ProcessAsync(context, output);
}
}
/// <summary>
/// A <see cref="ITagHelperActivator"/> that retrieves tag helpers as services from the request's
/// <see cref="IServiceProvider"/>.
/// </summary>
public class WeeServiceBasedTagHelperActivator : ITagHelperActivator
{
/// <inheritdoc />
public TTagHelper Create<TTagHelper>(ViewContext context) where TTagHelper : ITagHelper
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
return context.HttpContext.RequestServices.GetRequiredService<TTagHelper>();
}
}
/// <summary>
/// Resolves tag helper types from the <see cref="ApplicationPartManager.ApplicationParts"/>
/// of the application.
/// </summary>
public class WeeFeatureTagHelperTypeResolver : TagHelperTypeResolver
{
private readonly TagHelperFeature _feature;
/// <summary>
/// Initializes a new <see cref="FeatureTagHelperTypeResolver"/> instance.
/// </summary>
/// <param name="manager">The <see cref="ApplicationPartManager"/> of the application.</param>
public WeeFeatureTagHelperTypeResolver(ApplicationPartManager manager)
{
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
_feature = new TagHelperFeature();
manager.PopulateFeature(_feature);
}
/// <inheritdoc />
protected override IEnumerable<TypeInfo> GetExportedTypes(AssemblyName assemblyName)
{
if (assemblyName == null)
{
throw new ArgumentNullException(nameof(assemblyName));
}
var results = new List<TypeInfo>();
for (var i = 0; i < _feature.TagHelpers.Count; i++)
{
var tagHelperAssemblyName = _feature.TagHelpers[i].Assembly.GetName();
if (AssemblyNameComparer.OrdinalIgnoreCase.Equals(tagHelperAssemblyName, assemblyName))
{
results.Add(_feature.TagHelpers[i]);
}
}
return results;
}
/// <inheritdoc />
protected sealed override bool IsTagHelper(TypeInfo typeInfo)
{
// Return true always as we have already decided what types are tag helpers when GetExportedTypes
// gets called.
return true;
}
private class AssemblyNameComparer : IEqualityComparer<AssemblyName>
{
public static readonly IEqualityComparer<AssemblyName> OrdinalIgnoreCase = new AssemblyNameComparer();
private AssemblyNameComparer()
{
}
public bool Equals(AssemblyName x, AssemblyName y)
{
// Ignore case because that's what Assembly.Load does.
return string.Equals(x.Name, y.Name, StringComparison.OrdinalIgnoreCase) &&
string.Equals(x.CultureName ?? string.Empty, y.CultureName ?? string.Empty, StringComparison.Ordinal);
}
public int GetHashCode(AssemblyName obj)
{
var hashCode = 0;
if (obj.Name != null)
{
hashCode ^= obj.Name.GetHashCode();
}
hashCode ^= (obj.CultureName ?? string.Empty).GetHashCode();
return hashCode;
}
}
}
public static class WeeTagHelpersAsServices
{
public static void AddTagHelpersAsServices(ApplicationPartManager manager, IServiceCollection services)
{
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
var feature = new TagHelperFeature();
manager.PopulateFeature(feature);
foreach (var type in feature.TagHelpers.Select(t => t.AsType()))
{
services.TryAddTransient(type, type);
}
services.Replace(ServiceDescriptor.Transient<ITagHelperActivator, WeeServiceBasedTagHelperActivator>());
services.Replace(ServiceDescriptor.Transient<ITagHelperTypeResolver, WeeFeatureTagHelperTypeResolver>());
}
}
}
<file_sep>/Common/Wee.Common/Contracts/IWeePackage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Wee.Common.Contracts
{
public interface IWeePackage
{
string Name { get; }
string Description { get; }
int? Order { get; }
void RegisterServices();
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Nav/NavTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-nav")]
public class NavTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string NavClass { get; set; }
public NavTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("nav " + this.NavClass));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Tabs/TabsNavItemTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-tab")]
public class TabsNavItemTagHelper : TagHelper
{
[HtmlAttributeName("active")]
public bool Active { get; set; }
[HtmlAttributeName("class")]
public string TabClass { get; set; }
public TabsNavItemTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("role", (object) "presentation");
if (this.Active)
output.Attributes.SetAttribute("class", (object) ("active " + this.TabClass));
else
output.Attributes.SetAttribute("class", (object) this.TabClass);
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Themes/Wee.Core.Theme/PackageDefinition.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Wee.Common.Contracts;
using Wee.Common;
[assembly: DefaultNamespace("Wee.Core.Theme")]
namespace Wee.Core.Theme
{
public class PackageDefinition : IWeeTheme
{
private readonly IServiceCollection _services;
public PackageDefinition(IServiceCollection services)
{
_services = services;
}
public string Description { get { return "Core theme description"; } }
public string Name { get { return "Core Theme"; } }
public int? Order
{
get
{
return 0;
}
}
public void RegisterServices()
{
}
}
}
<file_sep>/UI/Themes/Wee.Theme.Remark/TagHelpers/RemarkButtonTagHelper.cs
using System;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Wee.UI.Core.TagHelpers;
namespace Wee.Theme.Remark.TagHelpers
{
/// <summary>
///
/// </summary>
[HtmlTargetElement("bootstrap-button")]
public class RemarkButtonTagHelper : IWeeOverrideTagHelper<ButtonTagHelper>
{
/// <summary>
///
/// </summary>
/// <param name="serviceProvider">Injected IServiceProvider</param>
public RemarkButtonTagHelper(IServiceProvider serviceProvider)
: base()
{
}
/// <summary>
/// Custom implementation
/// </summary>
/// <param name="context"></param>
/// <param name="output"></param>
/// <returns></returns>
public async void CustomProcess(ButtonTagHelper baseClassInstance, TagBuilder builder, TagHelperContext context, TagHelperOutput output)
{
builder.MergeAttribute("data-custommerge", "true");
builder.Attributes.Add("data-customadd", "true");
var childContent = output.Content.IsModified ? output.Content.GetContent() : (await output.GetChildContentAsync()).GetContent();
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Modal/ModalToggleTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement(Attributes = "bootstrap-toggle-modal")]
public class ModalToggleTagHelper : TagHelper
{
[HtmlAttributeName("bootstrap-toggle-modal")]
public string ToggleModal { get; set; }
public ModalToggleTagHelper()
{
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Attributes.SetAttribute("data-toggle", (object) "modal");
output.Attributes.SetAttribute("data-target", (object) string.Format("#{0}", (object) this.ToggleModal));
}
}
}
<file_sep>/UI/Wee.UI.Core/Registers/RazorViewFileProvidersRegister.cs
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wee.Common.Contracts;
using Microsoft.Extensions.FileProviders;
using Wee.Common.Reflection;
using Wee.Common;
using Microsoft.AspNetCore.Mvc.Razor;
namespace Wee.UI.Core.Registers
{
/// <summary>
///
/// </summary>
internal sealed class RazorViewFileProvidersRegister : BaseFileProvidersRegister, IWeeRegister<IServiceCollection>
{
private IServiceCollection _serviceCollection;
/// <summary>
///
/// </summary>
/// <param name="serviceCollection"></param>
/// <param name="folderPath"></param>
public RazorViewFileProvidersRegister(IServiceCollection serviceCollection, string folderPath)
: base(folderPath)
{
_serviceCollection = serviceCollection;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IServiceCollection Invoke<T>()
where T : class
{
var providers = base.LoadProviders<T>();
if (providers.Count > 0)
{
//Add the file provider to the Razor view engine
_serviceCollection.Configure<RazorViewEngineOptions>(options =>
{
foreach (var provider in providers)
{
options.FileProviders.Add(provider);
}
});
}
return _serviceCollection;
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Carousel/CarouselTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-carousel")]
public class CarouselTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string CarouselClass { get; set; }
public CarouselTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) (this.CarouselClass + " carousel"));
output.Attributes.SetAttribute("data-ride", (object) "carousel");
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Media/MediaBodyTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-media-body")]
public class MediaBodyTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string MediaBodyClass { get; set; }
public MediaBodyTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("media-body " + this.MediaBodyClass));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Themes/Wee.Theme.Remark/PackageDefinition.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Wee.Common.Contracts;
using Wee.UI.Core.TagHelpers;
using Wee.Theme.Remark.TagHelpers;
using Wee.Common;
[assembly: DefaultNamespace("Wee.Theme.Remark")]
namespace Wee.Theme.Remark
{
public class PackageDefinition : IWeeTheme
{
private readonly IServiceCollection _services;
public PackageDefinition(IServiceCollection services)
{
_services = services;
}
public string Description { get { return "Remark theme description"; } }
public string Name { get { return "Remark"; } }
public int? Order
{
get
{
return 1;
}
}
public void RegisterServices()
{
_services.AddTransient<IWeeOverrideTagHelper<ButtonTagHelper>, RemarkButtonTagHelper>();
}
}
}
<file_sep>/UI/Wee.UI.Core/Registers/MenuRegister.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wee.Common.Contracts;
using Wee.Common.Reflection;
using System.Reflection;
using Wee.Common;
using Wee.UI.Core.Services;
namespace Wee.UI.Core.Registers
{
/// <summary>
///
/// </summary>
internal sealed class MenuRegister : IWeeRegister<IApplicationBuilder>
{
private IApplicationBuilder _appBuilder;
private string _folderPath;
/// <summary>
///
/// </summary>
/// <param name="appBuilder"></param>
/// <param name="folderPath"></param>
public MenuRegister(IApplicationBuilder appBuilder, string folderPath)
{
_appBuilder = appBuilder;
_folderPath = folderPath;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IApplicationBuilder Invoke<T>()
where T : class
{
var menuService = _appBuilder.ApplicationServices.GetService<IMenuService>();
if (menuService != null)
{
var asms = AssemblyTools.LoadAssembliesThatImplements<T>(_folderPath);
var t = typeof(Controller);
var tMethod = typeof(IActionResult);
var tModule = typeof(IWeeModule);
foreach (var asm in asms)
{
var moduleType = asm.GetTypes().FirstOrDefault(i => !i.GetTypeInfo().IsInterface && tModule.IsAssignableFrom(i));
var module = AssemblyTools.CreateInstance<IWeeModule>(moduleType);
var rootMenuDefaultTitle = module?.RootMenuDefaultTitle;
var controllers = asm.GetTypes().Where(i => !i.GetTypeInfo().IsInterface
&& t.IsAssignableFrom(i))
.ToList();
foreach (var controller in controllers)
{
var methods = controller.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.Where(m => !m.IsVirtual
&& tMethod.IsAssignableFrom(m.ReturnType)
&& m.GetCustomAttribute<MenuAttribute>() != null)
.ToList();
foreach (var method in methods)
{
var menuAttr = method.GetCustomAttribute<MenuAttribute>();
var routeAttr = method.GetCustomAttribute<RouteAttribute>();
IMenuItem menu;
var category = string.IsNullOrWhiteSpace(rootMenuDefaultTitle) ? menuAttr.Category : rootMenuDefaultTitle;
if (routeAttr == null)
{
menu = new MenuItem(controller.Name, method.Name, menuAttr.Parent, menuAttr.Title, menuAttr.Hint, menuAttr.Order, menuAttr.Icon);
}
else
{
menu = new MenuItem(routeAttr.Name, menuAttr.Parent, menuAttr.Title, menuAttr.Hint, menuAttr.Order, menuAttr.Icon);
}
var categoryOrder = module?.Order ?? menuAttr.CategoryOrder ?? 9999;
menuService.RegisterMenu(categoryOrder, category, menu);
}
}
}
}
return _appBuilder;
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Media/MediaLeftTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-media-left")]
public class MediaLeftTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string MediaLeftClass { get; set; }
public MediaLeftTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("media-left " + this.MediaLeftClass));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/DropDown/DropDownMenuTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-dropdown-menu")]
public class DropDownMenuTagHelper : TagHelper
{
[HtmlAttributeName("labelledby")]
public string LabelledById { get; set; }
[HtmlAttributeName("class")]
public string DropDownMenuClass { get; set; }
public DropDownMenuTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("dropdown-menu " + this.DropDownMenuClass));
output.Attributes.SetAttribute("aria-labelledby", (object) this.LabelledById);
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Button/ButtonGroupTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-button-group")]
public class ButtonGroupTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string ButtonGroupClass { get; set; }
[HtmlAttributeName("orientation")]
public string ButtonGroupOrientation { get; set; }
public ButtonGroupTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
string content = (await output.GetChildContentAsync()).GetContent();
string str = "btn-group";
if (this.ButtonGroupOrientation == "vertical")
str = "btn-group-vertical";
output.Content.AppendHtml(content);
output.Attributes.SetAttribute("class", (object) (str + " " + this.ButtonGroupClass));
output.Attributes.SetAttribute("data-toggle", (object) "buttons");
output.Attributes.SetAttribute("role", (object) "group");
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Input/InputGroupAddonTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-input-group-addon")]
public class InputGroupAddonTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string InputGroupAddonClass { get; set; }
[HtmlAttributeName("type")]
public string InputGroupAddonType { get; set; }
public InputGroupAddonTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
string content = (await output.GetChildContentAsync()).GetContent();
string str = "input-group-addon";
if (this.InputGroupAddonType == "button")
str = "input-group-btn";
output.Content.AppendHtml(content);
if (this.InputGroupAddonClass.Length > 0)
output.Attributes.SetAttribute("class", (object) (str + " " + this.InputGroupAddonClass));
else
output.Attributes.SetAttribute("class", (object) str);
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Nav/NavBarTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-nav-bar")]
public class NavBarTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string NavBarClass { get; set; }
[HtmlAttributeName("container")]
public string NavBarContainer { get; set; }
public NavBarTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
string content = (await output.GetChildContentAsync()).GetContent();
string str = "navbar";
output.Content.AppendHtml("<div class='" + this.NavBarContainer + "'>" + content + "</div>");
if (this.NavBarClass.Length > 0)
output.Attributes.SetAttribute("class", (object) (str + " " + this.NavBarClass));
else
output.Attributes.SetAttribute("class", (object) (str + " navbar navbar-default"));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Carousel/CarouselCaptionTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-carousel-caption")]
public class CarouselCaptionTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string CarouselCaptionClass { get; set; }
public CarouselCaptionTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("carousel-caption " + this.CarouselCaptionClass));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/Common/Wee.Common/Attributes/MenuAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Wee.Common
{
public class MenuAttribute : Attribute
{
private string _category;
private int? _categoryOrder;
private string _parent;
private string _title;
private int _order;
private string _icon;
private string _hint;
/// <summary>
/// Configure a menu to be automatically loaded on application start.
/// It's try to get Menu Category Title from IAweModule.MenuCategoryTitle
/// </summary>
/// <param name="parent">Parent menu key</param>
/// <param name="title">Displayed title</param>
/// <param name="hint">Help text on mouse over, if null or empty assumes Title</param>
/// <param name="order">Position on related parent children list</param>
/// <param name="icon">Menu icon</param>
public MenuAttribute(string parent, string title, string hint = "", int order = 0, string icon = "")
{
_parent = parent;
_title = title;
_order = order;
_icon = icon;
_hint = string.IsNullOrWhiteSpace(hint) ? title : hint;
}
/// <summary>
/// Configure a menu to be automatically loaded on application start.
/// </summary>
/// <param name="category">Menu Category key</param>
/// <param name="parent">Parent menu key</param>
/// <param name="title">Displayed title</param>
/// <param name="hint">Help text on mouse over, if null or empty assumes Title</param>
/// <param name="order">Position on related parent children list</param>
/// <param name="icon">Menu icon</param>
public MenuAttribute(string category, int categoryOrder, string parent, string title, string hint = "", int order = 0, string icon = "")
: this(parent, title, hint, order, icon)
{
_category = category;
_categoryOrder = categoryOrder;
}
public string Category { get { return _category; } }
public int? CategoryOrder { get { return _categoryOrder; } }
public string Parent { get { return _parent; } }
public string Title { get { return _title; } }
public int Order { get { return _order; } }
public string Icon { get { return _icon; } }
public string Hint { get { return _hint; } }
}
}
<file_sep>/Common/Wee.Common/Contracts/IWeeModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Wee.Common.Contracts
{
public interface IWeeModule : IWeePackage
{
string RootMenuDefaultTitle { get; }
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Others/ThumbnailTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-thumbnail")]
public class ThumbnailTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string ThumbnailClass { get; set; }
[HtmlAttributeName("href")]
public string ThumbnailHref { get; set; }
public ThumbnailTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("thumbnail " + this.ThumbnailClass));
if (this.ThumbnailHref.Length > 0)
{
output.TagName = "a";
output.Attributes.SetAttribute("href", (object) this.ThumbnailHref);
}
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/Registers/BaseFileProvidersRegister.cs
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wee.Common.Contracts;
using Microsoft.Extensions.FileProviders;
using Wee.Common.Reflection;
using Wee.Common;
using Microsoft.AspNetCore.Mvc.Razor;
namespace Wee.UI.Core.Registers
{
/// <summary>
///
/// </summary>
internal class BaseFileProvidersRegister
{
protected string _folderPath;
/// <summary>
///
/// </summary>
/// <param name="folderPath"></param>
public BaseFileProvidersRegister(string folderPath)
{
_folderPath = folderPath;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected List<IFileProvider> LoadProviders<T>()
{
var moduleAsms = AssemblyTools.LoadAssembliesThatImplements<T>(_folderPath);
var providers = new List<IFileProvider>();
var type = typeof(T);
foreach (var moduleAsm in moduleAsms)
{
var ns = AssemblyTools.GetDefaultNamespace(moduleAsm);
if (string.IsNullOrWhiteSpace(ns))
{
var asmName = moduleAsm.GetName().Name;
throw new BaseComponentLoadException($"'{nameof(DefaultNamespaceAttribute)}' was not found on type {asmName}. Consider add attribute on {type.Name} class implementation (e.g. [assembly: DefaultNamespace(nameof({asmName}))])");
}
var embeddedFileProvider = new EmbeddedFileProvider(moduleAsm, ns);
providers.Add(embeddedFileProvider);
}
return providers;
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Breadcrumb/BreadcrumbTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-breadcrumb")]
public class BreadcrumbTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string BreadcrumbClass { get; set; }
public BreadcrumbTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("breadcrumb " + this.BreadcrumbClass));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/Common/Wee.Common/Attributes/DefaultNamespaceAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Wee.Common
{
public class DefaultNamespaceAttribute : Attribute
{
private string _defaultNamespace;
public DefaultNamespaceAttribute(string defaultNamespace)
{
_defaultNamespace = defaultNamespace;
}
public string DefaultNamespace { get { return _defaultNamespace; } }
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Modal/ModalTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-modal")]
public class ModalTagHelper : TagHelper
{
[HtmlAttributeName("id")]
public string ModalId { get; set; }
[HtmlAttributeName("size")]
public string ModalSize { get; set; }
[HtmlAttributeName("class")]
public string ModalClass { get; set; }
public ModalTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
string content = (await output.GetChildContentAsync()).GetContent();
string str = "modal-dialog";
if (this.ModalSize == "sm" || this.ModalSize == "lg")
str = "modal-dialog modal-" + this.ModalSize;
output.Content.AppendHtml("<bootstrap-modal-dialog class='" + str + "' role='document'><bootstrap-modal-content class='modal-content'>" + content + "</bootstrap-modal-content></bootstrap-modal-dialog>");
output.Attributes.SetAttribute("id", (object) this.ModalId);
output.Attributes.SetAttribute("class", (object) "modal");
output.Attributes.SetAttribute("tabindex", (object) "-1");
output.Attributes.SetAttribute("role", (object) "dialog");
output.Attributes.SetAttribute("aria-labelledby", (object) "myModalLabel");
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/Common/Wee.Common/Contracts/UI/IMenuCategory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Wee.Common.Contracts
{
public interface IMenuCategory
{
string Title { get; }
int Order { get; }
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Modal/ModalFadeTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-modal-fade")]
public class ModalFadeTagHelper : TagHelper
{
public ModalFadeTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
(await output.GetChildContentAsync()).GetContent();
output.Attributes.SetAttribute("class", (object) "modal");
output.Attributes.SetAttribute("tabindex", (object) "-1");
output.Attributes.SetAttribute("role", (object) "dialog");
output.Attributes.SetAttribute("aria-labelledby", (object) "myModalLabel");
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/DropDown/DropUpTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-dropup")]
public class DropUpTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string DropupClass { get; set; }
public DropUpTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
(await output.GetChildContentAsync()).GetContent();
output.Attributes.SetAttribute("class", (object) ("dropup " + this.DropupClass));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/Common/Wee.Common/Contracts/UI/IMenuItem.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Wee.Common.Contracts
{
public interface IMenuItem
{
string Parent { get; set; }
string Title { get; set; }
string Hint { get; set; }
int Order { get; set; }
string RouteName { get; set; }
string ControllerName { get; }
string ActionName { get; }
string Icon { get; set; }
List<IMenuItem> Children { get; set; }
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/DropDown/DropDownMenuSeparatorTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-dropdown-menu-separator")]
public class DropDownMenuSeparatorTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string DropDownSeparatorClass { get; set; }
public DropDownMenuSeparatorTagHelper()
{
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Content.AppendHtml(string.Format("<div class='{0}'></div>", (object) this.DropDownSeparatorClass));
output.Attributes.SetAttribute("role", (object) "dropdown-menu");
output.Attributes.SetAttribute("class", (object) this.DropDownSeparatorClass);
base.Process(context, output);
}
}
}
<file_sep>/Common/Wee.Common/Contracts/UI/IWeeTheme.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Wee.Common.Contracts
{
public interface IWeeTheme : IWeePackage
{
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Others/BadgeTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-badge")]
public class BadgeTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string BadgeClass { get; set; }
public BadgeTagHelper() : base()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object)("badge " + BadgeClass));
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/IWeeOverrideTagHelper.cs
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Wee.UI.Core.TagHelpers
{
/// <summary>
///
/// </summary>
/// <typeparam name="TBaseClass"></typeparam>
public interface IWeeOverrideTagHelper<TBaseClass> : IWeeTagHelper<TBaseClass>
where TBaseClass : TagHelper
{
void CustomProcess(TBaseClass baseClassInstance, TagBuilder builder, TagHelperContext context, TagHelperOutput output);
}
}
<file_sep>/Common/Wee.Common/Contracts/UI/IMenuService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Wee.Common.Contracts
{
public interface IMenuService
{
Dictionary<IMenuCategory, List<IMenuItem>> RegisteredMenus { get; }
void RegisterMenu(int categoryOrder, string categoryName, IMenuItem menu);
void RegisterMenu(IMenuCategory category, IMenuItem menu);
Dictionary<string, List<IMenuItem>> BuildMenu();
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Carousel/CarouselControlTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-carousel-control")]
public class CarouselControlTagHelper : TagHelper
{
[HtmlAttributeName("type")]
public string CollapseCarouselType { get; set; }
[HtmlAttributeName("slide")]
public string CollapseCarouselSlide { get; set; }
[HtmlAttributeName("class")]
public string CarouselControlClass { get; set; }
[HtmlAttributeName("target")]
public string CollapseCarouselTarget { get; set; }
public CarouselControlTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) (this.CollapseCarouselType + " carousel-control " + this.CarouselControlClass));
output.Attributes.SetAttribute("href", (object) this.CollapseCarouselTarget);
output.Attributes.SetAttribute("role", (object) "button");
output.Attributes.SetAttribute("data-slide", (object) this.CollapseCarouselSlide);
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Pagination/PaginationTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-pagination")]
public class PaginationTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string PaginationClass { get; set; }
[HtmlAttributeName("type")]
public string PaginationType { get; set; }
public PaginationTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.PreElement.AppendHtml("<bootstrap-pagination-nav>");
output.PostElement.AppendHtml("</bootstrap-pagination-nav>");
output.Attributes.SetAttribute("class", (object) (this.PaginationType + " " + this.PaginationClass));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Panel/PanelGroupTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-panel-group")]
public class PanelGroupTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string PanelClass { get; set; }
public PanelGroupTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("panel-group " + this.PanelClass));
output.Attributes.SetAttribute("role", (object) "tablist");
output.Attributes.SetAttribute("aria-multiselectable", (object) "true");
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/Customers/ACME/Site.Acme/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Wee.Common;
namespace Site.Acme.Controllers
{
public class HomeController : Controller
{
[Menu("", -1, null, "Home", icon: "wb-dashboard")]
public IActionResult Index()
{
return View();
}
[Menu("Outros", 9999, "Ajuda", "Sobre")]
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
[Menu("Outros", 9999, "Ajuda", "Contato")]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View();
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Others/CollapseTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-collapse")]
public class CollapseTagHelper : TagHelper
{
[HtmlAttributeName("trigger")]
public string CollapseTrigger { get; set; }
[HtmlAttributeName("id")]
public string CollapseId { get; set; }
[HtmlAttributeName("class")]
public string CollapseClass { get; set; }
public CollapseTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
(await output.GetChildContentAsync()).GetContent();
output.PostContent.AppendHtml("<script>$(function() { $('" + this.CollapseTrigger + "').on('click', function () { $('#" + this.CollapseId + "').collapse('toggle'); }); });</script>");
output.Attributes.SetAttribute("class", (object) ("collapse " + this.CollapseClass));
output.Attributes.SetAttribute("id", (object) this.CollapseId);
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/DropDown/DropDownMenuHeaderTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-dropdown-menu-header")]
public class DropDownMenuHeaderTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string DropDownMenuHeader { get; set; }
public DropDownMenuHeaderTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("dropdown-header " + this.DropDownMenuHeader));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Alert/AlertCloseTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
using System;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-alert-close")]
public class AlertCloseTagHelper : TagHelper
{
//public override AlertCloseTagHelper Self
//{
// get
// {
// return this;
// }
//}
public AlertCloseTagHelper(IServiceProvider serviceProvider)
//: base(serviceProvider)
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("type", (object)"button");
output.Attributes.SetAttribute("class", (object)("close " + this.AlertCloseClass));
output.Attributes.SetAttribute("data-dismiss", (object)"alert");
output.Attributes.SetAttribute("aria-label", (object)"Close");
await base.ProcessAsync(context, output);
}
[HtmlAttributeName("class")]
public string AlertCloseClass { get; set; }
}
}
<file_sep>/UI/Wee.UI.Core.Services/MenuCategory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wee.Common.Contracts;
namespace Wee.UI.Core.Services
{
public class MenuCategory : IMenuCategory
{
public string Title { get; private set; }
public int Order { get; private set; }
public MenuCategory(MenuCategory menuCategory)
{
Title = menuCategory.Title;
Order = menuCategory.Order;
}
public MenuCategory(int order, string title)
{
title = title == null ? "Outros" : title;
Title = title;
Order = order;
}
public override int GetHashCode()
{
return ($"{this.Order}{this.Title}").GetHashCode();
}
public override bool Equals(object obj)
{
var o = obj as MenuCategory;
return o.Order == this.Order && o.Title.Equals(this.Title, StringComparison.CurrentCultureIgnoreCase);
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Others/ListgroupItemTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-listgroup-item")]
public class ListgroupItemTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string ListGroupItemClass { get; set; }
[HtmlAttributeName("type")]
public string ItemType { get; set; }
[HtmlAttributeName("href")]
public string ItemHref { get; set; }
[HtmlAttributeName("class")]
public string ItemTarget { get; set; }
public ListgroupItemTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
string content = (await output.GetChildContentAsync()).GetContent();
if (this.ItemType == "button")
output.Content.AppendHtml("<button type=\"button\" class=\"list-group-item\"" + this.ListGroupItemClass + ">" + content + "</button>");
else if (this.ItemHref.Length > 0)
{
output.Content.AppendHtml("<a href=" + this.ItemHref + " target=" + this.ItemTarget + " class=\"list-group-item " + this.ListGroupItemClass + "\">" + content + "</a>");
}
else
{
output.Content.AppendHtml(content);
output.Attributes.SetAttribute("class", (object) ("list-group-item " + this.ListGroupItemClass));
}
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Others/TooltipTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("div", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("img", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("span", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("nav", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("button", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("a", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("p", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("h1", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("h2", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("h3", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("h4", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("h5", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("h6", Attributes = "bootstrap-tooltip")]
[HtmlTargetElement("bootstrap-button", Attributes = "bootstrap-tooltip")]
public class TooltipTagHelper : TagHelper
{
[HtmlAttributeName("bootstrap-tooltip-toggle")]
public string TooltipToggle { get; set; }
[HtmlAttributeName("bootstrap-tooltip")]
public string TooltipTitle { get; set; }
[HtmlAttributeName("static")]
public bool TooltipStatic { get; set; }
[HtmlAttributeName("placement")]
public string TooltipPlacement { get; set; }
public TooltipTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
string content = (await output.GetChildContentAsync()).GetContent();
if (!this.TooltipStatic)
{
if (this.TooltipToggle == "")
this.TooltipToggle = this.TooltipTitle;
if (this.TooltipTitle != "")
{
output.PostElement.AppendHtml("<script>$(function() {$('[data-toggle=\"" + this.TooltipToggle + "\"]').tooltip();});</script>");
output.Attributes.SetAttribute("title", (object) this.TooltipTitle);
}
output.Attributes.SetAttribute("data-toggle", (object) this.TooltipToggle);
}
else
output.Content.AppendHtml("<div class=\"tooltip fade " + this.TooltipPlacement + " in static\" style=\"z-index:0;\" role=\"tooltip\"><div class=\"tooltip-arrow\"></div><div class=\"tooltip-inner\">" + content + "</div></div>");
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/Registers/StaticFilesRegister.cs
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wee.Common.Contracts;
using Microsoft.Extensions.FileProviders;
using Wee.Common.Reflection;
using Wee.Common;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Builder;
namespace Wee.UI.Core.Registers
{
/// <summary>
///
/// </summary>
internal sealed class StaticFilesRegister : BaseFileProvidersRegister, IWeeRegister<IApplicationBuilder>
{
private IApplicationBuilder _app;
/// <summary>
///
/// </summary>
/// <param name="app"></param>
/// <param name="folderPath"></param>
public StaticFilesRegister(IApplicationBuilder app, string folderPath)
: base(folderPath)
{
_app = app;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IApplicationBuilder Invoke<T>()
where T : class
{
var providers = base.LoadProviders<T>();
if (providers.Count > 0)
{
_app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new CompositeFileProvider(providers)
});
}
return _app;
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Others/PopoverTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("div", Attributes = "bootstrap-popover")]
[HtmlTargetElement("img", Attributes = "bootstrap-popover")]
[HtmlTargetElement("span", Attributes = "bootstrap-popover")]
[HtmlTargetElement("nav", Attributes = "bootstrap-popover")]
[HtmlTargetElement("button", Attributes = "bootstrap-popover")]
[HtmlTargetElement("a", Attributes = "bootstrap-popover")]
[HtmlTargetElement("p", Attributes = "bootstrap-popover")]
[HtmlTargetElement("h1", Attributes = "bootstrap-popover")]
[HtmlTargetElement("h2", Attributes = "bootstrap-popover")]
[HtmlTargetElement("h3", Attributes = "bootstrap-popover")]
[HtmlTargetElement("h4", Attributes = "bootstrap-popover")]
[HtmlTargetElement("h5", Attributes = "bootstrap-popover")]
[HtmlTargetElement("h6", Attributes = "bootstrap-popover")]
[HtmlTargetElement("bootstrap-button", Attributes = "bootstrap-popover")]
public class PopoverTagHelper : TagHelper
{
[HtmlAttributeName("bootstrap-popover")]
public string PopoverTitle { get; set; }
[HtmlAttributeName("id")]
public string PopoverId { get; set; }
[HtmlAttributeName("static")]
public bool PopoverStatic { get; set; }
[HtmlAttributeName("placement")]
public string PopoverPlacement { get; set; }
[HtmlAttributeName("title")]
public string PopoverTitle1 { get; set; }
[HtmlAttributeName("content")]
public string PopoverContent { get; set; }
public PopoverTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
(await output.GetChildContentAsync()).GetContent();
if (!this.PopoverStatic)
{
if (this.PopoverTitle != "")
output.PostElement.AppendHtml("<script>$(function() {$('#" + this.PopoverId + "').popover();});</script>");
output.Attributes.SetAttribute("data-toggle", (object) "popover");
output.Attributes.SetAttribute("title", (object) this.PopoverTitle1);
output.Attributes.SetAttribute("id", (object) this.PopoverId);
}
else
{
output.Content.AppendHtml("<div class='arrow'></div> <h3 class='popover-title'>" + this.PopoverTitle1 + "</h3><div class='popover-content'><p>" + this.PopoverContent + "</p></div>");
output.Attributes.SetAttribute("class", (object) ("popover static " + this.PopoverPlacement));
output.Attributes.SetAttribute("id", (object) this.PopoverId);
}
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Others/ProgressBarTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-progress-bar")]
public class ProgressBarTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string ProgressBarClass { get; set; }
[HtmlAttributeName("value")]
public string ProgressVal { get; set; }
[HtmlAttributeName("valuemin")]
public string ProgressValMin { get; set; }
[HtmlAttributeName("valuemax")]
public string ProgressValMax { get; set; }
[HtmlAttributeName("minwidth")]
public string ProgressMinWidth { get; set; }
public ProgressBarTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
string content = (await output.GetChildContentAsync()).GetContent();
string str = "";
if (this.ProgressMinWidth.Length > 0)
str = "min-width: " + this.ProgressMinWidth + ";";
output.Content.AppendHtml(content);
output.Attributes.SetAttribute("class", (object) ("progress-bar " + this.ProgressBarClass));
output.Attributes.SetAttribute("style", (object) ("width: " + this.ProgressVal + "%; " + str));
output.Attributes.SetAttribute("aria-valuenow", (object) this.ProgressVal);
output.Attributes.SetAttribute("aria-valuemin", (object) this.ProgressValMin);
output.Attributes.SetAttribute("aria-valuemax", (object) this.ProgressValMax);
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core.Services/MenuService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wee.Common.Contracts;
namespace Wee.UI.Core.Services
{
public class MenuService : IMenuService
{
public Dictionary<IMenuCategory, List<IMenuItem>> RegisteredMenus { get; private set; } = new Dictionary<IMenuCategory, List<IMenuItem>>();
public void RegisterMenu(int categoryOrder, string categoryName, IMenuItem menu)
{
var category = new MenuCategory(categoryOrder, categoryName);
RegisterMenu(category, menu);
}
public void RegisterMenu(IMenuCategory menuCategory, IMenuItem menu)
{
if (RegisteredMenus.ContainsKey(menuCategory))
{
RegisteredMenus[menuCategory].Add(menu);
}
else
{
var newMenu = new List<IMenuItem>() { menu };
RegisteredMenus[menuCategory] = newMenu;
}
//Adiciona os parents como item de menu, é apenas um "holder" pros filhos e evita de ter que criar [MenuAttribute] só pra isso.
if (!string.IsNullOrWhiteSpace(menu.Parent) && !RegisteredMenus[menuCategory].Any(i => i.Title == menu.Parent))
{
RegisteredMenus[menuCategory].Add(new MenuItem() { Title = menu.Parent });
}
}
public Dictionary<string, List<IMenuItem>> BuildMenu()
{
var result = new Dictionary<string, List<IMenuItem>>();
var ordered = RegisteredMenus.OrderBy(i => i.Key.Order).ToDictionary(i => i.Key.Title, i => i.Value);
foreach (var registeredMenu in ordered)
{
var tree = RecursiveMenu(null, registeredMenu.Value);
result.Add(registeredMenu.Key, tree);
}
return result;
}
private List<IMenuItem> RecursiveMenu(string parent, List<IMenuItem> source)
{
var filtered = source.Where(i => i.Parent == parent).ToList();
var recursive = from menu in filtered
select new MenuItem(menu)
{
Children = RecursiveMenu(menu.Title, source)
};
return recursive.ToList<IMenuItem>();
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/DropDown/DropDownMenuItemTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-dropdown-menu-item")]
public class DropDownMenuItemTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string DropDownItemClass { get; set; }
public DropDownMenuItemTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("bootstrap-dropdown-menu-item " + this.DropDownItemClass));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Pagination/PaginationItemTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-pagination-item")]
public class PaginationItemTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string PaginationItemClass { get; set; }
public PaginationItemTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) this.PaginationItemClass);
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/Registers/RegisterExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Wee.UI.Core.Registers;
using Wee.Common.Contracts;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
namespace Wee.UI.Core
{
/// <summary>
///
/// </summary>
public static class RegisterExtensions
{
/// <summary>
///
/// </summary>
/// <param name="app"></param>
/// <param name="folderPath"></param>
/// <returns></returns>
public static IApplicationBuilder WeeRegisterPackages(this IApplicationBuilder app, string folderPath = "")
{
if (string.IsNullOrWhiteSpace(folderPath))
folderPath = PlatformServices.Default.Application.ApplicationBasePath;
var instance = new StaticFilesRegister(app, folderPath);
instance.Invoke<IWeePackage>();
var menuInstance = new MenuRegister(app, folderPath);
menuInstance.Invoke<Controller>();
return app;
}
/// <summary>
///
/// </summary>
/// <param name="services"></param>
/// <param name="folderPath"></param>
/// <returns></returns>
public static IServiceCollection WeeRegisterPackages(this IServiceCollection services, string folderPath = "")
{
if (string.IsNullOrWhiteSpace(folderPath))
folderPath = PlatformServices.Default.Application.ApplicationBasePath;
var razorViewInstance = new RazorViewFileProvidersRegister(services, folderPath);
razorViewInstance.Invoke<IWeePackage>();
var themeInstance = new ThemeRegister(services, folderPath);
themeInstance.Invoke<IWeePackage>();
return services;
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Button/ButtonTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-button")]
public class ButtonTagHelper : WeeTagHelper<ButtonTagHelper>
{
public override ButtonTagHelper Self { get { return this; } }
public override TagBuilder Builder
{
get
{
if (ButtonElement == "a")
{
return new TagBuilder("a");
}
else if (ButtonElement == "input")
{
return new TagBuilder("input");
}
else
{
return new TagBuilder("button");
}
}
}
public ButtonTagHelper(IServiceProvider serviceProvider/*, IAweOverrideTagHelper<ButtonTagHelper> overrider*/)
: base(serviceProvider/*, overrider*/)
{
}
public override async Task ProcessAsync(TagBuilder builder, TagHelperContext context, TagHelperOutput output)
{
string btnValue = ButtonValue.Length <= 0 ? (await output.GetChildContentAsync()).GetContent() : ButtonValue;
if (Array.IndexOf<string>(allowedButtonElements, ButtonElement) == -1)
throw new ArgumentException("Invalid element! Please, use one of the following HTML elements - 'a', 'button' or 'input'");
if (Array.IndexOf<string>(allowedButtonTypes, ButtonType) == -1)
throw new ArgumentException("Invalid button type! Please, use one of the following types - 'button', 'submit' or 'reset'");
if (Array.IndexOf<string>(allowedButtonOptions, ButtonOption) == -1)
throw new ArgumentException("Invalid button option! Please, use one of the following options - 'default', 'primary', 'success', 'info', 'warning', 'danger' or 'link'");
string btnOption = "btn-" + ButtonOption;
ButtonClass += $" btn {btnOption}";
string btnDisabled = "";
if (ButtonDisabled)
btnDisabled = !(ButtonElement == "a") ? "disabled='disabled'" : "disabled";
string str4;
var attrs = new Dictionary<string, string>();
if (ButtonElement == "a")
{
attrs.Add("target", ButtonTarget);
str4 = string.Format("<a href='{0}' target='{1}' role='{2}' class='{3}' id='{4}' autocomplete='{5}' data-loading-text='{6}'>{7}</a>", (object)ButtonLink, (object)ButtonTarget, (object)ButtonType, (object)ButtonClass, (object)ButtonId, (object)ButtonAutocomplete, (object)ButtonLoadingText, (object)btnValue);
}
else if (ButtonElement == "input")
{
attrs.Add("value", btnValue);
attrs.Add("type", ButtonType);
str4 = string.Format("<input type='{0}' class='{1}' {2} value='{3}' id='{4}' autocomplete='{5}' data-loading-text='{6}'/>", (object)ButtonType, (object)ButtonClass, (object)btnDisabled, (object)btnValue, (object)ButtonId, (object)ButtonAutocomplete, (object)ButtonLoadingText);
}
else
{
attrs.Add("type", ButtonType);
str4 = string.Format("<button type='{0}' class='{1}' {2} id='{3}' autocomplete='{4}' data-loading-text='{5}'>{6}</button>", (object)ButtonType, (object)ButtonClass, (object)btnDisabled, (object)ButtonId, (object)ButtonAutocomplete, (object)ButtonLoadingText, (object)btnValue);
}
attrs.Add("id", ButtonId);
attrs.Add("autocomplete", ButtonAutocomplete);
attrs.Add("data-loading-text", ButtonLoadingText);
builder.InnerHtml.Append(btnValue);
builder.AddCssClass(ButtonClass);
builder.MergeAttributes(attrs);
output.Content.SetHtmlContent(builder);
//output.Content.AppendHtml(str4);
}
#region Properties
[HtmlAttributeName("element")]
public string ButtonElement { get; set; }
[HtmlAttributeName("id")]
public string ButtonId { get; set; }
[HtmlAttributeName("autocomplete")]
public string ButtonAutocomplete { get; set; }
[HtmlAttributeName("loading-text")]
public string ButtonLoadingText { get; set; }
[HtmlAttributeName("class")]
public string ButtonClass { get; set; }
[HtmlAttributeName("type")]
public string ButtonType { get; set; }
[HtmlAttributeName("option")]
public string ButtonOption { get; set; }
[HtmlAttributeName("size")]
public string ButtonSize { get; set; }
[HtmlAttributeName("active")]
public bool ButtonActive { get; set; }
[HtmlAttributeName("disabled")]
public bool ButtonDisabled { get; set; }
[HtmlAttributeName("block")]
public bool ButtonBlock { get; set; }
[HtmlAttributeName("value")]
public string ButtonValue { get; set; }
[HtmlAttributeName("link")]
public string ButtonLink { get; set; }
[HtmlAttributeName("target")]
public string ButtonTarget { get; set; }
readonly string[] allowedButtonElements = new string[3]
{
"a",
"button",
"input"
};
readonly string[] allowedButtonTypes = new string[3]
{
"button",
"submit",
"reset"
};
readonly string[] allowedButtonOptions = new string[7]
{
"default",
"primary",
"success",
"info",
"warning",
"danger",
"link"
};
readonly string[] allowedButtonSizes = new string[4]
{
"default",
"large",
"small",
"extrasmall"
};
#endregion Properties
}
public enum ButtonElement
{
Link,
Input,
Button
};
public enum ButtonType
{
Button,
Submit,
Reset
};
public enum ButtonOption
{
Default,
Primary,
Success,
Info,
Warning,
Danger,
Link
}
public enum ButtonSize
{
Default,
Large,
Small,
Extrasmall
};
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/README.md
# ASP .NET MVC Core Bootstrap Tag Helpers #
ASP.NET Core MVC Bootstrap tag helpers.
This package includes tag helpers for the following bootstrap components:
- Alert
- Badge
- Breadcrumb
- Button
- Carousel
- Collapse
- DropDown
- Input
- Jumbotron
- Label
- ListGroup
- Media
- Modal
- NavBar
- PageHeader
- Pagination
- Panel
- Popover
- ProgressBar
- Tabs
- Thumbnail
- Tooltip
- Well
## Installation ##
* Create a new ASP .NET Core Web Application.
* Update `_ViewImports.cshtml`.
```html
@using Awe.Mvc.Core
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Awe.Mvc.Core
```
* Add a reference to `bootstrap.mvc.css` in `_Layout.cshtml`. `bootstrap.mvc.css` is included in this repository.
```html
<environment names="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/wwwroot/css/bootstrap.mvc.css" />
</environment>
```
* Build the Solution.
* Add a Bootstrap Tag Helper to a Page.
## Modal ##
To create a Bootstrap Modal, add the following Tag Helper:
```html
<bootstrap-modal id="myModal" aria-labelledby="myModalLabel" size="sm">
<bootstrap-modal-header>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Sample modal header</h4>
</bootstrap-modal-header>
<bootstrap-modal-body>
Sample modal body
</bootstrap-modal-body>
</bootstrap-modal>
```
To open the modal from a button, add the bootstrap-toggle-modal attribute to the button with the id of the modal as value:
```html
<bootstrap-button type="button" class="btn btn-primary" bootstrap-toggle-modal="myModal">
Open sample modal
</bootstrap-button>
```
***Related Tag Helpers:***
* `<bootstrap-modal-header>` - denotes the Modal's header section.
* `<bootstrap-modal-body>` - denotes the Modal's content section.
* `<bootstrap-modal-footer>` - denotes the Modal's footer section.
***Applicable attributes:***
Animation can be added to the Modal by adding the class "fade" to it.
* data-backdrop - true (default)/false/"static" - includes a modal-backdrop element. Specify "static" for a backdrop which doesn't close the modal on click.
* data-keyboard - true (default)/false - closes the modal when escape key is pressed.
* data-show - true (default)/false - shows the modal when initialized.
* size - "xs"/"sm"/"lg". If size is not set, the size of the widget will be normal.
***Methods:***
```javascript
$().modal('toggle')
$().modal('show')
$().modal('hide')
$().modal('handleUpdate')
```
***Events:***
```javascript
show.bs.modal
shown.bs.modal
hide.bs.modal
hidden.bs.modal
loaded.bs.modal
```
## Dropdown ##
To create a Bootstrap Dropdown, add the following Tag Helper:
```html
<bootstrap-dropdown>
<bootstrap-dropdown-label id="newDropDown" class="btn btn-danger btn-lg" content="DropDown Button"></bootstrap-dropdown-label>
<bootstrap-dropdown-menu labelledby="newDropDown">
<bootstrap-dropdown-menu-item><a href="#">Action</a></bootstrap-dropdown-menu-item>
<bootstrap-dropdown-menu-item><a href="#">Another action</a></bootstrap-dropdown-menu-item>
<bootstrap-dropdown-menu-item><a href="#">Something else here</a></bootstrap-dropdown-menu-item>
<bootstrap-dropdown-menu-separator></bootstrap-dropdown-menu-separator>
<bootstrap-dropdown-menu-item><a href="#">Separated link</a></bootstrap-dropdown-menu-item>
</bootstrap-dropdown-menu>
</bootstrap-dropdown>
```
You can add more Dropdown options by inserting more <bootstrap-dropdown-menu-item> Tag Helpers.
**Related Tag Helpers:**
* `<bootstrap-dropdown-label>` - denotes the Dropdown's label (button). Its content can be set via the content attribute.
* `<bootstrap-dropdown-menu>` - denotes the container (popup) for the Dropdown's items. It has a labelledby attribute that should be set to the id of the <bootstrap-dropdown-label> to denote connection between them.
* `<bootstrap-dropdown-menu-item>` - denotes a Dropdown item.
* `<bootstrap-dropdown-menu-separator>` - denotes a separator between Dropdown items.
***Methods:***
```javascript
$().dropdown('toggle')
```
***Events:***
* show.bs.dropdown
* shown.bs.dropdown
* hide.bs.dropdown
* hidden.bs.dropdown
## Tab ##
To create a Bootstrap togglable Tab, add the following Tag Helper:
```html
<bootstrap-tabs>
<bootstrap-tabs-nav id="tabs3" class="">
<bootstrap-tab active="true"><a href="#home" aria-controls="home" role="tab">Home</a></bootstrap-tab>
<bootstrap-tab><a href="#profile" aria-controls="profile" role="tab">Profile</a></bootstrap-tab>
<bootstrap-tab>
<bootstrap-dropdown>
<bootstrap-dropdown-label id="bootstrapDropdown" class="btn btn-link" content="Dropdown"></bootstrap-dropdown-label>
<bootstrap-dropdown-menu labelledby="bootstrapDropdown">
<bootstrap-dropdown-menu-item><a href="#dropdown1">fat</a></bootstrap-dropdown-menu-item>
<bootstrap-dropdown-menu-item><a href="#dropdown2">mdo</a></bootstrap-dropdown-menu-item>
</bootstrap-dropdown-menu>
</bootstrap-dropdown>
</bootstrap-tab>
</bootstrap-tabs-nav>
<bootstrap-tabs-content>
<bootstrap-tab-pane active="true" id="home" class="fade in">Content 1.</bootstrap-tab-pane>
<bootstrap-tab-pane id="profile" class="fade">Content 2.</bootstrap-tab-pane>
<bootstrap-tab-pane id="dropdown1" class="fade">Content 3.</bootstrap-tab-pane>
<bootstrap-tab-pane id="dropdown2" class="fade">Content 4.</bootstrap-tab-pane>
</bootstrap-tabs-content>
</bootstrap-tabs>
````
To add more tabs to this sample Tab, insert <bootstrap-tab> Tag Helpers in `<bootstrap-tabs-nav>` and `<bootstrap-tab-pane>` Tag Helpers to `<bootstrap-tabs-content>`. These act as tab header and tab content sections respectively.
***Related Tag Helpers:***
* <bootstrap-tabs-nav> - denotes the Tab's header section.
* <bootstrap-tab> - denotes a Tab's tab in the header section. The attribute active denotes if the tab is selected.
* <bootstrap-tabs-content> - denotes the Tab's content section.
* <bootstrap-tab-pane> - denotes a Tab's content panel in the content section. The attribute active denotes if the content panel is visible. If the class "fade" is added, selection animation will be enabled.
***Methods:***
```javascript
$().tab('show')
```
***Events:***
```javascript
hide.bs.tab
show.bs.tab
hidden.bs.tab
shown.bs.tab
```
## Tooltip ##
To create a Bootstrap Tooltip, add the attribute bootstrap-tooltip to an existing tag or Tag Helper. The value of the attribute specifies the tooltip's content. Supported tags are: `<div>, <img>, <span>, <nav>, <button>, <a>, <p>, <h1>, <h2>, <h3>, <h4>, <h5> and <h6>`
`<bootstrap-button bootstrap-tooltip-toggle="btn2" bootstrap-tooltip="Tooltip on the top" type="button" id="btn2" class="btn btn-default" data-placement='top'>Tooltip on top</bootstrap-button>`
***Applicable attributes:***
* data-animation - true (default)/false - apply a CSS fade transition to the tooltip.
* data-container - string/false - appends the tooltip to a specific element. Example: data-container="body".
* data-delay - number/object - delay showing and hiding the tooltip (ms) - does not apply to manual trigger type. If a number is supplied, delay is applied to both hide/show. Object structure is: delay: { "show": 500, "hide": 100 }.
* data-html - true/false (default) - insert HTML into the tooltip. If false, jQuery's text method will be used to insert content into the DOM. Use text if you're worried about XSS attacks.
* data-placement - "top" (default)/"left"/"right"/"bottom"/"auto"/function - sets the tooltip's position relative to the host element. When "auto" is specified, it will dynamically reorient the tooltip. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right. When a function is used to determine the placement, it is called with the tooltip DOM node as its first argument and the triggering element DOM node as its second. The this context is set to the tooltip instance.
* data-selector - string/false (default) - if a selector is provided, tooltip objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have tooltips added.
* data-trigger - "click"/"hover"/"focus"/"manual" (default is "hover focus") - how tooltip is triggered. You may pass multiple triggers; separate them with a space. "manual" cannot be combined with any other trigger.
* data-viewport - string/object/function (default is { selector: 'body', padding: 0 }) - keeps the tooltip within the bounds of this element. Example: viewport: '#viewport' or { "selector": "#viewport", "padding": 0 }. If a function is given, it is called with the triggering element DOM node as its only argument. The this context is set to the tooltip instance.
***Methods:***
```javascript
$().tooltip('show')
$().tooltip('hide')
$().tooltipal('toggle')
$().tooltip('destroy')
```
***Events:***
```javascript
show.bs.tooltip
shown.bs.tooltip
hide.bs.tooltip
hidden.bs.tooltip
inserted.bs.tooltip
```
## Popover ##
To create a Bootstrap Popover, add the attribute bootstrap-popover to an existing tag or Tag Helper. Supported tags are: `<div>, <img>, <span>, <nav>, <button>, <a>, <p>, <h1>, <h2>, <h3>, <h4>, <h5> and <h6>`
```javascript
<bootstrap-button bootstrap-popover="popover1b" type="button" id="myButton1b" class="btn btn-lg btn-danger" data-placement='right' title="Popover title" data-content="And here's some amazing content.">`
Click to toggle popover
</bootstrap-button>
```
***Applicable attributes:***
* data-animation - true (default)/false - apply a CSS fade transition to the popover.
* data-container - string/false - appends the popover to a specific element. Example: data-container="body".
* data-content - string (default is "")/function - sets the popover's content. If a function is given, it will be called with its this reference set to the element that the popover is attached to.
* data-delay - number/object - delay showing and hiding the popover (ms) - does not apply to manual trigger type. If a number is supplied, delay is applied to both hide/show. Object structure is: delay: { "show": 500, "hide": 100 }.
* data-html - true/false (default) - insert HTML into the popover. If false, jQuery's text method will be used to insert content into the DOM. Use text if you're worried about XSS attacks.
* data-placement - "top" (default)/"left"/"right"/"bottom"/"auto"/function - sets the popover's position relative to the host element. When "auto" is specified, it will dynamically reorient the popover. For example, if placement is "auto left", the popover will display to the left when possible, otherwise it will display right. When a function is used to determine the placement, it is called with the popover DOM node as its first argument and the triggering element DOM node as its second. The this context is set to the popover instance.
* data-selector - string/false (default) - if a selector is provided, popover objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have tooltips added.
* data-title (alternative to title) - string (default is "")/function - sets the popover's title. If a function is given, it will be called with its this reference set to the element that the popover is attached to.
* data-trigger - "click"/"hover"/"focus"/"manual" (default is "hover focus") - how popover is triggered. You may pass multiple triggers; separate them with a space. "manual" cannot be combined with any other trigger.
* data-viewport - string/object/function (default is { selector: 'body', padding: 0 }) - keeps the popover within the bounds of this element. Example: viewport: '#viewport' or { "selector": "#viewport", "padding": 0 }. If a function is given, it is called with the triggering element DOM node as its only argument. The this context is set to the popover instance.
* title (alternative to data-title) - string (default is "")/function - sets the popover's title. If a function is given, it will be called with its this reference set to the element that the popover is attached to.
***Methods:***
```javascript
$().popover(show)
$().popover(hide)
$().popover(toggle)
$().popover(destroy)
```
***Events:***
```javascript
show.bs.popover
shown.bs.popover
hide.bs.popover
hidden.bs.popover
inserted.bs.popover
```
## Alert ##
To create a Bootstrap Alert, add the following Tag Helper:
```html
<bootstrap-alert class="alert-danger alert-dismissible fade in">
<bootstrap-alert-close><span aria-hidden="true">×</span></bootstrap-alert-close>
<strong>Holy guacamole!</strong> Best check yo self, you're not looking too good.
</bootstrap-alert>
```
***Related Tag Helpers:***
`<bootstrap-alert-close>` - denotes the Alert's close button.
***Applicable attributes:***
* The color scheme of the Alert can be changed by adding the class "alert-success", "alert-info", "alert-warning" or "alert-danger".
* To denote that the Alert can be closed, add the "alert-dismissible" class.
* Enable animation by adding the classes "fade", "in" and/or "out".
***Methods:***
```javascript
$().alert('close')
```
***Events:***
```javascript
close.bs.alert
closed.bs.alert
```
## Button ##
To create a Bootstrap Button, add the following Tag Helper:
```html
<button type='button' class='btn btn-default' data-placement="top">Bootstrap Button</button>
```
***Related Tag Helpers:***
`<bootstrap-button-group>` - enclose several <bootstrap-button> Tag Helpers in this Tag Helper to create a button group.
***Applicable attributes:***
* autocomplete - set this attribute to "off" for cross-browser compatibility.
* data-toggle - "button" (for a single button)/"buttons" (for a button group).
* The class "active" has to be applied to pre-toggled buttons. To change the button's color scheme (template), add the class "btn-default", "btn-primary", "btn-success", "btn-info", "btn-warning", "btn-danger" or "btn-link".
***Methods:***
```javascript
$().button('toggle')
$().button('reset')
```
## Collapse ##
To create a Bootstrap Collapse, add the following Tag Helper:
```html
<bootstrap-collapse trigger="#triggerA, #triggerB, #triggerBB" id="collapseExample">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
</bootstrap-collapse>
```
***Applicable attributes:***
* data-parent - false (default)/selector - if a selector is provided, then all collapsible elements under the specified parent will be closed when this collapsible item is shown.
* data-toggle - toggles the collapsible element on invocation.
* trigger - selector - denotes the element that toggles the Collapse.
***Methods:***
```javascript
$().collapse('toggle')
$().collapse('show')
$().collapse('hide')
```
***Events:***
```javascript
show.bs.collapse
shown.bs.collapse
hide.bs.collapse
hidden.bs.collapse
```
## Carousel ##
To create a Bootstrap Carousel, add the following Tag Helper:
```html
<bootstrap-carousel class="slide" id="carousel-example-generic1" style="width:900px; display:block;">
<bootstrap-carousel-indicators style="display:block;">
<bootstrap-carousel-indicator target="#carousel-example-generic1" slide-to="0" active="true" class=""></bootstrap-carousel-indicator>
<bootstrap-carousel-indicator target="#carousel-example-generic1" slide-to="1"></bootstrap-carousel-indicator>
<bootstrap-carousel-indicator target="#carousel-example-generic1" slide-to="2"></bootstrap-carousel-indicator>
</bootstrap-carousel-indicators>
<bootstrap-carousel-items style="display:block;">
<bootstrap-carousel-item active="true"><img src="..." /></bootstrap-carousel-item>
<bootstrap-carousel-item><img src="..." /></bootstrap-carousel-item>
<bootstrap-carousel-item><img src="..." /></bootstrap-carousel-item>
</bootstrap-carousel-items>
<bootstrap-carousel-control type="left" slide="prev" target="#carousel-example-generic1">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</bootstrap-carousel-control>
<bootstrap-carousel-control type="right" slide="next" target="#carousel-example-generic1">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</bootstrap-carousel-control>
</bootstrap-carousel>
```
***Related Tag Helpers:***
* `<bootstrap-carousel-indicators>` - denotes the container of Carousel's indicators.
* `<bootstrap-carousel-indicator>` - denotes a Carousel indicator. Applicable attributes:
◦active - denotes the initially selected indicator.
◦target - has to be set to the selector of the Carousel that the indicator controls.
* `<bootstrap-carousel-items` - denotes the container of Carousel's items.
* `<bootstrap-carousel-item` - denotes a Carousel item. Its active attribute denotes the initially shown item.
* `<bootstrap-carousel-caption` - specifies a Carousel item's caption.
* `<bootstrap-carousel-control` - denotes a Carousel control arrow.
* Applicable attributes:
* slide - specifies which item to go to when the arrow is clicked ("prev"/"next").
* target - has to be set to the selector of the Carousel that the arrow controls.
* type - specifies the position of the arrow ("left"/"right").
***Applicable attributes:***
* Animation can be added to the Carousel by adding the class "slide" to it.
* data-interval - number (default 5000)/false - the amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle.
* data-pause - string (default "hover") - pauses the cycling of the carousel on mouseenter and resumes the cycling of the carousel on mouseleave.
* data-wrap - true (default)/false - whether the carousel should cycle continuously or have hard stops.
* data-keyboard - true (default)/false - whether the carousel should react to keyboard events.
***Methods:***
```javascript
$().carousel('cycle')
$().carousel('pause')
$().carousel(number) number (pass it to the .carousel() function)
$().carousel('prev')
$().carousel('next')
```
***Events:***
slide.bs.carousel
slid.bs.carousel
Other Bootstrap Components
## Input group ##
To create a Bootstrap Input group, add the following Tag Helper:
```html
<bootstrap-input-group>
<bootstrap-input-group-addon id="basic-addon">https://example.com/users/</bootstrap-input-group-addon>
<input type="text" class="form-control" id="basic-url" aria-describedby="basic-addon">
</bootstrap-input-group>
```
***Applicable classes:***
* input-group-sm, input-group-lg
***Related Tag Helpers:***
* <bootstrap-input-group-addon> - denotes an Input group addon.
To denote that the input and the <bootstrap-input-group-addon> Tag Helper in the Input group are connected, set the input's "aria-describedby" attribute to the id of the addon.
## Nav ##
To create a Bootstrap Nav, add the following Tag Helper:
```html
<bootstrap-nav>
<bootstrap-nav-item class="active"><a href="#">Home</a></bootstrap-nav-item>
<bootstrap-nav-item><a href="#">Profile</a></bootstrap-nav-item>
<bootstrap-nav-item><a href="#">Messages</a></bootstrap-nav-item>
</bootstrap-nav>
```
***Applicable classes:***
* `nav-tabs` (alternative to "nav-pills"), nav-pills (alternative to "nav-tabs"), nav-justified, "nav-stacked
***Related Tag Helpers:***
* <bootstrap-nav-item> - denotes a Nav item.
Applicable classes: active - if added, the item will be initially selected, disabled - if added, the item selection will be disabled.
## Navbar ##
To create a Bootstrap Navbar, add the following Tag Helper:
```html
<bootstrap-nav-bar>
<bootstrap-nav-bar-header>
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</bootstrap-nav-bar-header>
<bootstrap-nav-bar-collapse>
<p class="navbar-text">Signed in as <NAME></p>
</bootstrap-nav-bar-collapse>
</bootstrap-nav-bar>
```
***Applicable classes:***
* navbar-inverse - applies an inverted color scheme to the Navbar.
***Related Tag Helpers:***
* `<bootstrap-nav-bar-header>` - denotes the Navbar header.
* `<bootstrap-nav-bar-collapse>` - denotes the Navbar collapse.
Classes applicable to Navbar inner elements:
navbar-brand, navbar-toggle, navbar-form, navbar-left - aligns element to the left of the Navbar, navbar-right - aligns element to the right of the Navbar, navbar-btn, navbar-text
## Breadcrumbs ##
To create a Bootstrap Breadcrumbs, add the following Tag Helper:
```html
<bootstrap-breadcrumb>
<bootstrap-breadcrumb-item><a href="#">Home</a></bootstrap-breadcrumb-item>
<bootstrap-breadcrumb-item><a href="#">Library</a></bootstrap-breadcrumb-item>
<bootstrap-breadcrumb-item class="active">Data</bootstrap-breadcrumb-item>
</bootstrap-breadcrumb>
```
***Related Tag Helpers:***
* `<bootstrap-breadcrumb-item>` - denotes a Breadcrumb (item).
Applicable classes: pagination-sm - if added, the item will be highlighted.
## Pagination ##
To create a Bootstrap Pagination, add the following Tag Helper:
```html
<bootstrap-pagination>
<bootstrap-pagination-item>
<a href="#" aria-label="Previous"><span aria-hidden="true">«</span></a>
</bootstrap-pagination-item>
<bootstrap-pagination-item><a href="#">1</a></bootstrap-pagination-item>
<bootstrap-pagination-item><a href="#">2</a></bootstrap-pagination-item>
<bootstrap-pagination-item><a href="#">3</a></bootstrap-pagination-item>
<bootstrap-pagination-item><a href="#">4</a></bootstrap-pagination-item>
<bootstrap-pagination-item><a href="#">5</a></bootstrap-pagination-item>
<bootstrap-pagination-item>
<a href="#" aria-label="Next"><span aria-hidden="true">»</span></a>
</bootstrap-pagination-item>
</bootstrap-pagination>
```
***Applicable classes:***
* pagination-sm, pagination-lg
***Applicable attributes:***
* "type" - if set to "pager", denotes only a pager with "previous" and "next" links.
***Related Tag Helpers:***
* `<bootstrap-pagination-item`> - denotes a Pagination item.
Applicable classes: active, disabled, previous, next
## Label ##
To create a Bootstrap Label, add the following Tag Helper:
```html
<bootstrap-label class="label-default">New</bootstrap-label>
```
***Applicable classes***
* label-default, label-primary, label-success, label-info, label-warning, label-danger
## Badge ##
To create a Bootstrap Badge, add the following Tag Helper:
```html
<bootstrap-badge>42</bootstrap-badge>
```
## Jumbotron ##
To create a Bootstrap Jumbotron, add the following Tag Helper:
```html
<bootstrap-jumbotron>
<h1>Hello, world!</h1>
<p>This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
</bootstrap-jumbotron>
```
## Page header ##
To create a Bootstrap Page header, add the following Tag Helper:
```html
<bootstrap-page-header>
<h1>Example page header <small>Subtext for header</small></h1>
</bootstrap-page-header>
```
## Thumbnail ##
To create a Bootstrap Thumbnail, add the following Tag Helper:
```html
<bootstrap-thumbnail>
<img src="..." style="width: 100%;" alt="illustration" />
<div class="caption">
<h3>Thumbnail label</h3>
<p>...</p>
<p>
<bootstrap-button element="a" href="#" type="button" class="btn btn-primary" autocomplete="off">Button</bootstrap-button>
<bootstrap-button element="a" href="#" type="button" class="btn btn-default" autocomplete="off">Button</bootstrap-button>
</p>
</div>
</bootstrap-thumbnail>
```
***Applicable attributes:***
* "href" (optional)
* "target" (optional)
## Progress bar ##
To create a Bootstrap Progress bar, add the following Tag Helper:
```html
<bootstrap-progress>
<bootstrap-progress-bar value="60">
60%
</bootstrap-progress-bar>
</bootstrap-progress>
```
***Related Tag Helpers:***
* <bootstrap-progress-bar> - denotes a progress bar.
Applicable classes: active - enables animation (requires "progress-bar-striped"), progress-bar-success, progress-bar-info, progress-bar-warning, progress-bar-danger, progress-bar-striped
Applicable attributes:
◦"value"
◦"minwidth"
## Media object ##
To create a Bootstrap Media object, add the following Tag Helper:
```html
<bootstrap-media>
<bootstrap-media-left class="media-top">
<a href="#">
<img class="media-object" alt="64x64" style="width: 64px; height: 64px;" src="..." data-holder-rendered="true" />
</a>
</bootstrap-media-left>
<bootstrap-media-body>
<h4 class="media-heading">Top aligned media</h4>
<p>Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante.</p>
<p>Donec sed odio dui. Nullam quis risus eget urna mollis ornare vel eu leo.</p>
</bootstrap-media-body>
</bootstrap-media>
```
***Related Tag Helpers:***
* `<bootstrap-media-left>`
***Applicable classes:***
* media-top, media-middle, media-middle
* `<bootstrap-media-body>`
* `<bootstrap-media-right>`
***Applicable classes:***
media-top, media-middle, media-middle
•<bootstrap-media-list>* - wrap nested <bootstrap-media> Tag Helpers inside this Tag Helper to create a "nested list"-like structure of media objects.
The class "media-heading" should be applied to heading tags inside <bootstrap-media-body>. The class "media-object" should be applied to images inside <bootstrap-media-left> and <bootstrap-media-right>.
## List group ##
To create a Bootstrap List group, add the following Tag Helper:
```html
<bootstrap-listgroup>
<bootstrap-listgroup-item>Cras justo odio</bootstrap-listgroup-item>
<bootstrap-listgroup-item>Dapibus ac facilisis in</bootstrap-listgroup-item>
<bootstrap-listgroup-item>Morbi leo risus</bootstrap-listgroup-item>
<bootstrap-listgroup-item>Porta ac consectetur ac</bootstrap-listgroup-item>
</bootstrap-listgroup>
```
***Related Tag Helpers:***
* <bootstrap-listgroup-item> - denotes a List group item.
***Applicable classes:***
* active - if added, the item will be highlighted
* disabled - if added, the item will have a disabled visual effect,
* list-group-item-success
* list-group-item-info
* list-group-item-warning
* list-group-item-danger
* list-group-item-success
## Panel ##
To create a Bootstrap Panel, add the following Tag Helper:
```html
<bootstrap-panel class="panel-default">
<bootstrap-panel-header>
<h3 class="panel-title">Panel title</h3>
</bootstrap-panel-header>
<bootstrap-panel-body>
Panel content
</bootstrap-panel-body>
<bootstrap-panel-footer>Panel footer</bootstrap-panel-footer>
</bootstrap-panel>
```
***Applicable classes:***
* panel-default
* panel-primary
* panel-success
* panel-info
* panel-warning
* panel-danger
***Related Tag Helpers:***
* `<bootstrap-panel-header>` - denotes the header section of the Panel.
* `<bootstrap-panel-body>` - denotes the content section of the Panel.
* `<bootstrap-panel-footer>` - denotes the footer section of the Panel.
## Responsive embed ##
To create a Bootstrap Responsive embed, add the class "bootstrap-embed-responsive" to an iframe, embed, object or video element:
```html
<iframe bootstrap-embed-responsive="16by9" src="//www.youtube.com/embed/zpOULjyy-n8?rel=0"></iframe>
```
## Well ##
To create a Bootstrap Well, add the following Tag Helper:
```html
<bootstrap-well>Look, I'm in a well!</bootstrap-well>
```
***Applicable classes:***
* well-sm
* well-lg
<file_sep>/UI/Wee.UI.Core/TagHelpers/Alert/AlertTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-alert")]
public class AlertTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string AlertClass { get; set; }
public AlertTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("alert " + this.AlertClass));
output.Attributes.SetAttribute("role", (object) "alert");
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Carousel/CarouselIndicatorTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-carousel-indicator")]
public class CarouselIndicatorTagHelper : TagHelper
{
[HtmlAttributeName("active")]
public bool CarouselIndicatorActive { get; set; }
[HtmlAttributeName("class")]
public string CarouselIndicatorClass { get; set; }
[HtmlAttributeName("slide-to")]
public string CarouselIndicatorSlideTo { get; set; }
[HtmlAttributeName("target")]
public string CarouselIndicatorTarget { get; set; }
public CarouselIndicatorTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
if (this.CarouselIndicatorActive)
output.Attributes.SetAttribute("class", (object) (this.CarouselIndicatorClass + " active"));
else
output.Attributes.SetAttribute("class", (object) this.CarouselIndicatorClass);
output.Attributes.SetAttribute("data-slide-to", (object) this.CarouselIndicatorSlideTo);
output.Attributes.SetAttribute("data-target", (object) this.CarouselIndicatorTarget);
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Tabs/TabsContentItemTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-tab-pane")]
public class TabsContentItemTagHelper : TagHelper
{
[HtmlAttributeName("active")]
public bool Active { get; set; }
[HtmlAttributeName("class")]
public string Class { get; set; }
public TabsContentItemTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
string tabPaneClass = "tab-pane";
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("role", (object) "tabpanel");
if (this.Class.Length > 0)
tabPaneClass = tabPaneClass + " " + this.Class;
if (this.Active)
tabPaneClass += " active";
output.Attributes.SetAttribute("class", (object) tabPaneClass);
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/Common/Wee.Common/Reflection/AssemblyTools.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.DotNet.PlatformAbstractions;
using Wee.Common.Crypto;
using Microsoft.Extensions.DependencyModel;
namespace Wee.Common.Reflection
{
public static class AssemblyTools
{
internal static readonly string[] _ignoredSystemAssemblies = { "System", "Microsoft", "Nuget", "mscorlib", "dotnet-", "Newtonsoft" };
private static Dictionary<string, List<Assembly>> _assembliesCache { get; set; } = new Dictionary<string, List<Assembly>>();
public static string GetDefaultNamespace(Assembly asm)
{
var attr = asm.GetCustomAttribute<DefaultNamespaceAttribute>();
return attr != null ? attr.DefaultNamespace : string.Empty;
}
private static string GetCacheKey(string folderPath, bool ignoreSystemAssemblies = true, params string[] ignoredAssemblies)
{
var cacheKey = string.Empty;
var ignoredString = string.Join(",", ignoredAssemblies);
var result = $"{folderPath}_{ignoredAssemblies}_{ignoredString}";
cacheKey = CryptoTools.CalculateMD5Hash(result);
return cacheKey;
}
public static IEnumerable<Assembly> LoadAssemblies(string folderPath, bool ignoreSystemAssemblies = true, params string[] ignoredAssemblies)
{
var cacheKey = GetCacheKey(folderPath, ignoreSystemAssemblies, ignoredAssemblies);
if (_assembliesCache.ContainsKey(cacheKey))
{
foreach (var cached in _assembliesCache[cacheKey])
{
yield return cached;
}
}
else
{
_assembliesCache[cacheKey] = new List<Assembly>();
var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
var assemblieNames = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId);
if (ignoreSystemAssemblies)
{
assemblieNames = assemblieNames
.Where(asm => _ignoredSystemAssemblies
.All(sysName => !asm.Name.StartsWith(sysName, StringComparison.CurrentCultureIgnoreCase))
);
}
if (ignoredAssemblies.Length > 0)
{
assemblieNames = assemblieNames
.Where(asm => _ignoredSystemAssemblies
.All(sysName => !asm.Name.Equals(sysName, StringComparison.CurrentCultureIgnoreCase))
);
}
if (assemblieNames.Count() == 0)
yield break;
var asl = new AssemblyLoader(folderPath);
foreach (var asmName in assemblieNames)
{
var assembly = asl.LoadFromAssemblyName(asmName);
_assembliesCache[cacheKey].Add(assembly);
yield return assembly;
}
}
}
public static IEnumerable<Assembly> LoadAssembliesThatImplements<T>(string folderPath, bool ignoreSystemAssemblies = true, params string[] ignoredAssemblies)
{
var type = typeof(T);
var result = new List<Assembly>();
foreach (var asm in LoadAssemblies(folderPath, ignoreSystemAssemblies, ignoredAssemblies))
{
var moduleTypes = asm.GetTypes().Where(a => !a.GetTypeInfo().IsInterface
&& type.IsAssignableFrom(a));
var isAssignable = moduleTypes != null && moduleTypes.Count() > 0;
if (!isAssignable)
continue;
result.Add(asm);
}
return result;
}
public static IEnumerable<Type> LoadTypesThatImplements<T>(string folderPath)
{
var assemblies = LoadAssembliesThatImplements<T>(folderPath);
return assemblies.LoadTypesThatImplements<T>();
}
public static IEnumerable<Type> LoadTypesThatImplements<T>(this IEnumerable<Assembly> assemblies)
{
var result = new List<Type>();
foreach (var asm in assemblies)
{
var asmTypes = asm.LoadTypesThatImplements<T>();
result.AddRange(asmTypes);
}
return result;
}
public static IEnumerable<Type> LoadTypesThatImplements<T>(this Assembly assembly)
{
var type = typeof(T);
var result = assembly
.GetTypes()
.Where(i => !type.IsConstructedGenericType
&& type.IsAssignableFrom(i))
.ToList();
return result;
}
public static IEnumerable<Type> LoadTypesThatImplementsGenericType(string folderPath, Type genericType)
{
var assemblies = LoadAssemblies(folderPath);
return assemblies.LoadTypesThatImplementsGenericType(genericType);
}
public static IEnumerable<Type> LoadTypesThatImplementsGenericType(this IEnumerable<Assembly> assemblies, Type genericType)
{
var result = new List<Type>();
var types = assemblies.SelectMany(i => i.GetTypes()).ToList();
foreach (var asm in assemblies)
{
var asmTypes = asm.LoadTypesThatImplementsGenericType(genericType);
result.AddRange(asmTypes);
}
return result;
}
public static IEnumerable<Type> LoadTypesThatImplementsGenericType(this Assembly assembly, Type genericType)
{
var result = assembly
.GetTypes()
.Where(t => t.GetTypeInfo().ImplementedInterfaces
.Where(i => i.IsConstructedGenericType
&& i.GetGenericTypeDefinition() == genericType).SingleOrDefault() != null
).ToList();
return result;
}
public static T CreateInstance<T>(this Type type, params object[] args)
where T : class
{
return type != null ? ((T)Activator.CreateInstance(type, args)) : null;
}
}
}
<file_sep>/Common/Wee.Common/Contracts/IWeeRegister.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Wee.Common.Contracts
{
public interface IWeeRegister<TExtensionReturnType>
{
TExtensionReturnType Invoke<T>()
where T : class;
}
}
<file_sep>/UI/Wee.UI.Core.Services/MenuItem.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wee.Common.Contracts;
namespace Wee.UI.Core.Services
{
public class MenuItem : IMenuItem
{
public string Parent { get; set; }
public string Title { get; set; }
public string Hint { get; set; }
public int Order { get; set; }
public string RouteName { get; set; }
public string ControllerName
{
get
{
var split = RouteName.Split('#');
if (split.Length > 1)
{
return split[0].Replace("Controller", string.Empty).Substring(1);
}
else return "";
}
}
public string ActionName
{
get
{
var split = RouteName.Split('#');
if (split.Length > 1)
{
return split[1];
}
else return "";
}
}
public string Icon { get; set; }
public List<IMenuItem> Children { get; set; }
public MenuItem()
{
}
public MenuItem(IMenuItem menu)
{
Parent = menu.Parent;
Title = menu.Title;
Hint = menu.Hint;
Order = menu.Order;
RouteName = menu.RouteName;
Icon = menu.Icon;
Children = menu.Children;
}
private MenuItem(string parent, string title, string hint, int order = 0, string icon = "")
{
Parent = parent;
Title = title;
Hint = hint;
Order = order;
Icon = icon;
}
public MenuItem(string routeName, string parent, string title, string hint, int order = 0, string icon = "")
: this(parent, title, hint, order, icon)
{
RouteName = routeName;
}
public MenuItem(string controller, string action, string parent, string title, string hint, int order = 0, string icon = "")
: this(parent, title, hint, order, icon)
{
RouteName = $"${controller}#{action}";
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Others/ProgressTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-progress")]
public class ProgressTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string ProgressClass { get; set; }
public ProgressTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
(await output.GetChildContentAsync()).GetContent();
output.Attributes.SetAttribute("class", (object) ("progress " + this.ProgressClass));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/Registers/ThemeRegister.cs
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wee.Common.Reflection;
using System.Reflection;
using Wee.Common.Contracts;
namespace Wee.UI.Core.Registers
{
/// <summary>
///
/// </summary>
internal sealed class ThemeRegister : IWeeRegister<IServiceCollection>
{
private IServiceCollection _serviceCollection;
private string _folderPath;
/// <summary>
///
/// </summary>
/// <param name="serviceCollection"></param>
/// <param name="folderPath"></param>
public ThemeRegister(IServiceCollection serviceCollection, string folderPath)
{
_serviceCollection = serviceCollection;
_folderPath = folderPath;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IServiceCollection Invoke<T>()
where T : class
{
var types = AssemblyTools.LoadTypesThatImplements<T>(_folderPath);
var ctorTypes = new Type[] { typeof(IServiceCollection) };
var packageType = typeof(IWeePackage);
foreach (var type in types)
{
object[] args = new object[0];
var isServiceCollectionConstructor = type.GetConstructor(ctorTypes) != null;
if (isServiceCollectionConstructor)
{
args = new object[] { _serviceCollection };
}
var instance = type.CreateInstance<T>(args);
if (packageType.IsAssignableFrom(instance.GetType()))
(instance as IWeePackage)?.RegisterServices();
}
return _serviceCollection;
}
}
}
<file_sep>/README.md
# WeeERP
Tiny and compact ERP framework, plug'n'play support all around
<file_sep>/UI/Wee.UI.Core/TagHelpers/Others/EmbedResponsiveTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("iframe", Attributes = "bootstrap-embed-responsive")]
[HtmlTargetElement("object", Attributes = "bootstrap-embed-responsive")]
[HtmlTargetElement("embed", Attributes = "bootstrap-embed-responsive")]
[HtmlTargetElement("video", Attributes = "bootstrap-embed-responsive")]
public class EmbedResponsiveTagHelper : TagHelper
{
[HtmlAttributeName("bootstrap-embed-responsive")]
public string embedType { get; set; }
[HtmlAttributeName("class")]
public string EmbedClass { get; set; }
public EmbedResponsiveTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.PreElement.AppendHtml("<bootstrap-embed-responsive class='embed-responsive embed-responsive-" + this.embedType + "'>");
output.PostElement.AppendHtml("</bootstrap-embed-responsive>");
output.Attributes.SetAttribute("class", (object) ("embed-responsive-item " + this.EmbedClass));
// ISSUE: reference to a compiler-generated method
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/DropDown/DropDownLabelTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-dropdown-label")]
public class DropDownLabelTagHelper : TagHelper
{
[HtmlAttributeName("id")]
public string DropDownLabelId { get; set; }
[HtmlAttributeName("type")]
public string DropDownLabelType { get; set; }
[HtmlAttributeName("class")]
public string DropDownLabelClass { get; set; }
[HtmlAttributeName("content")]
public string DropDownLabelContent { get; set; }
public DropDownLabelTagHelper()
{
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
string str = this.DropDownLabelContent + "<span class='caret'></span>";
output.Content.AppendHtml(str);
output.Attributes.SetAttribute("id", (object) this.DropDownLabelId);
output.Attributes.SetAttribute("class", (object) this.DropDownLabelClass);
output.Attributes.SetAttribute("type", (object) "button");
output.Attributes.SetAttribute("data-toggle", (object) "dropdown");
output.Attributes.SetAttribute("aria-haspopup", (object) "true");
output.Attributes.SetAttribute("aria-expanded", (object) "true");
base.Process(context, output);
}
}
}
<file_sep>/UI/Wee.UI.Core/TagHelpers/Carousel/CarouselItemTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-carousel-item")]
public class CarouselItemTagHelper : TagHelper
{
[HtmlAttributeName("active")]
public bool CarouselItemActive { get; set; }
[HtmlAttributeName("class")]
public string CarouselItemClass { get; set; }
public CarouselItemTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
if (this.CarouselItemActive)
output.Attributes.SetAttribute("class", (object) ("item active " + this.CarouselItemClass));
else
output.Attributes.SetAttribute("class", (object) ("item " + this.CarouselItemClass));
// ISSUE: reference to a compiler-generated method
}
}
}
| 6870830ccc8699d1e09173051a872f628f577f05 | [
"Markdown",
"C#"
] | 67 | C# | IkeCode-SmartSolutions/WeeERP | ba2e0c6f720000c9d223ef9b4116328682500f30 | a5983d4da93332fb8202db7d42ff506ec8749c72 |
refs/heads/main | <repo_name>KIrillPal/AVL-Implementation<file_sep>/trees/ITree.cpp
#include "ITree.h"
ITree::ITree()
{
}
ITree::~ITree()
{
}<file_sep>/README.md
# AVL-Implementation
В этом репозитории находится качественная реализация дерева AVL. Для тестирования дерева скачайте и запустите [AVL.exe](https://github.com/KIrillPal/AVL-Implementation/blob/main/AVL.exe). Для просмотра кода откройте [AVL.cpp](https://github.com/KIrillPal/AVL-Implementation/blob/main/trees/AVL.cpp)
# Особенности
Реализация хранится в классе AVL, наследуемом от интерфейса дерева поиска ITree, что позволяет одному и тому же коду использовать разные алгоритмы деревьев, такие как красно-чёрное или splay деревья. Для удобства использования кроме friend-функций, позволяющих редактировать дерево со стороны, есть собственные функции `add`, `erase` и `find`.
В файле `tree.cpp` содержится небольшой код для демонстрации базовых функций AVL дерева.
Этот проект был опубликован для демонстрации навыков объектно-ориентированнго программирования, в частности, понимание базовых вещей.
<file_sep>/trees/trees.cpp
#include <bits/stdc++.h>
#include "AVL.h"
using namespace std;
int main()
{
ITree* t = new AVL();
cout << "It's AVL tree tester. Enter \"+ <number>\" to add value and \"- <number>\" to remove.\nEnter \"? <number>\" to know if the tree contains the value.\n";
cout << "As example: \"+ -2\".\n";
while (true)
{
char c;
long long x;
cin >> c >> x;
if (c == '+')
{
t = t->insert(x);
cout << "added " << x << '\n';
}
else if (c == '-')
{
t = t->erase(x);
cout << "removed " << x << " if it was there" << '\n';
}
else if (c == '?')
{
if (t->find(x))
cout << "We have found " << x << " in the tree" << '\n';
else cout << "We haven't found " << x << " in the tree" << '\n';
}
}
delete t;
}<file_sep>/trees/AVL.h
#pragma once
#include "ITree.h"
class AVL : virtual public ITree
{
public:
AVL(T value);
AVL();
virtual ~AVL();
virtual ITree* insert(T value);
virtual ITree* erase(T value);
virtual bool find(T value);
private:
char height_;
long long value_;
AVL* L_, * R_;
bool isempty;
friend char height(AVL* t);
friend bool isempty(AVL* t);
friend char factor(AVL* t);
friend void balance(AVL*& t);
friend void setheight(AVL* t);
friend void rotation_r(AVL*& t);
friend void rotation_l(AVL*& t);
friend void insert_(AVL*& t, T value);
friend void erase_(AVL*& t, T value);
friend void erase_mr(AVL*& t, T& value);
friend bool find_(AVL*& t, T value);
};
<file_sep>/trees/AVL.cpp
#include "AVL.h"
AVL::AVL(T value)
{
value_ = value;
L_ = R_ = nullptr;
height_ = 1;
isempty = 0;
}
AVL::AVL()
{
L_ = R_ = nullptr;
height_ = 0;
isempty = 1;
}
AVL::~AVL()
{
delete L_;
delete R_;
}
ITree* AVL::insert(T value)
{
auto p = this;
insert_(p, value);
return p;
}
ITree* AVL::erase(T value)
{
auto p = this;
erase_(p, value);
if (p == nullptr)
p = new AVL();
return p;
}
bool AVL::find(T value)
{
auto p = this;
return find_(p, value);;
}
char height(AVL* t)
{
return t ? t->height_ : 0;
}
bool isempty(AVL* t)
{
return t ? t->isempty : 0;
}
char factor(AVL* t)
{
if (!t) return 0;
return height(t->L_) - height(t->R_);
}
void balance(AVL*& t)
{
if (!t) return;
setheight(t);
if (factor(t) == 2)
{
if (factor(t->L_) < 0)
rotation_l(t->L_);
setheight(t);
rotation_r(t);
}
else if (factor(t) == -2)
{
if (factor(t->R_) > 0)
rotation_r(t->R_);
setheight(t);
rotation_l(t);
}
}
void setheight(AVL* t)
{
t->height_ = std::max(height(t->L_), height(t->R_)) + 1;
}
void rotation_r(AVL*& t)
{
if (!t || !(t->L_)) return;
AVL* b = t->L_;
t->L_ = b->R_;
b->R_ = t;
setheight(t);
setheight(b);
t = b;
}
void rotation_l(AVL*& t)
{
if (!t || !(t->R_)) return;
AVL * b = t->R_;
t->R_ = b->L_;
b->L_ = t;
setheight(t);
setheight(b);
t = b;
}
void insert_(AVL*& t, T value)
{
if (t->isempty) {
t->value_ = value;
t->height_ = 1;
t->isempty = 0;
}
if (t->value_ == value) return;
AVL * &p = (t->value_ < value) ? t->R_ : t->L_;
if (!p) p = new AVL(value);
else insert_(p, value);
balance(t);
}
void erase_(AVL*& t, T value)
{
if (!t || isempty(t)) return;
if (t->value_ > value)
erase_(t->L_, value);
else if (t->value_ < value)
erase_(t->R_, value);
else if (!(t->R_))
{
AVL* d = t;
t = t->L_;
d->L_ = d->R_ = nullptr;
delete d;
}
else erase_mr(t->R_, t->value_);
}
void erase_mr(AVL*& t, T& value)
{
if (!t) return;
if (t->L_) erase_mr(t->L_, value);
else
{
std::swap(value, t->value_);
delete t, t = nullptr;
}
if (t) balance(t);
}
bool find_(AVL*& t, T value)
{
if (!t || isempty(t)) return false;
if (t->value_ > value)
return find_(t->L_, value);
else if (t->value_ < value)
return find_(t->R_, value);
return true;
}
<file_sep>/trees/ITree.h
#pragma once
#include <cmath>
#include <algorithm>
typedef long long T;
class ITree
{
public:
ITree();
virtual ~ITree();
virtual ITree* insert(T value) = 0;
virtual ITree* erase(T value) = 0;
virtual bool find(T value) = 0;
};
| 7bbe98013bcf456563559381322d939cdc36fc41 | [
"Markdown",
"C++"
] | 6 | C++ | KIrillPal/AVL-Implementation | 4815e10d1f86edc3a1f55a8bfc1b2fcf5cc19f8d | b821622aea4428e08c5fe2ddad1aca92834282ff |
refs/heads/master | <repo_name>arroqc/P1_Facial_Keypoints<file_sep>/models.py
## TODO: define the convolutional neural network architecture
import torch
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Conv2dRelUBN(nn.Module):
def __init__(self, c_in, c_out, k=5, stride=1, padding=0):
super(Conv2dRelUBN, self).__init__()
self.conv = nn.Conv2d(c_in, c_out, k, stride=stride, padding=padding)
self.bn = nn.BatchNorm2d(c_out)
def forward(self, x):
return self.bn(F.relu(self.conv(x)))
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# As an example, you've been given a convolutional layer, which you may (but don't have to) change:
# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel
self.conv1 = Conv2dRelUBN(1, 32, 3)
self.conv2 = Conv2dRelUBN(32, 32, 3, stride=2) #32 220 220
self.conv3 = Conv2dRelUBN(32, 64, 3)
self.conv4 = Conv2dRelUBN(64, 64, 3, stride=2) #64 106 106
self.conv5 = Conv2dRelUBN(64, 128, 3)
self.conv6 = Conv2dRelUBN(128, 128, 3, stride=2) #128 49 49
self.conv7 = Conv2dRelUBN(128, 256, 3) #256 23 23
self.lin1 = nn.Linear(256 * 23 * 23, 512)
self.lin2 = nn.Linear(512, 256)
self.lin3 = nn.Linear(256, 68 * 2)
self.dropout = nn.Dropout(0.3)
## Note that among the layers to add, consider including:
# maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting
def forward(self, x):
## TODO: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## x = self.pool(F.relu(self.conv1(x)))
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
x = self.conv5(x)
x = self.conv6(x)
x = self.conv7(x)
x = x.view(x.shape[0], -1)
x = self.dropout(x)
x = F.relu(self.lin1(x))
x = self.dropout(x)
x = F.relu(self.lin2(x))
x = self.lin3(x)
# a modified x, having gone through all the layers of your model, should be returned
return x
| 8fab0a14a41cd5ca1abbc8661e6300d9a802e8d3 | [
"Python"
] | 1 | Python | arroqc/P1_Facial_Keypoints | 3eb9d8e7dd15eb85049661b089f0bbb9b7e99699 | 7f555e042fcf6fd970f322bc2dc7c9f922221a13 |
refs/heads/master | <file_sep><?php
$dd = 'uhuhdddfdf';
echo $dd
| 2bd3e00dde19ad3b8855ab3fa1fa40013ff11905 | [
"PHP"
] | 1 | PHP | saidmeliji/travis-demo | a81bb1b034a5f6209eb144a2455f6c93833f4383 | b0f56a9454c5bd205f544bcf9cf93b1dbaff195d |
refs/heads/main | <repo_name>Andrew-VanIderstine/RNN-and-DNN-from-scratch<file_sep>/RNN and DNN from scratch.py
from math import exp
from random import random
from sklearn.model_selection import train_test_split
from sklearn import metrics
import numpy as np
import librosa
import tensorflow as tf
import torch
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Activation
from keras.layers import Flatten
from keras.layers import Conv2D
from keras.layers import Conv1D
from keras.layers import MaxPooling2D
from keras.losses import MeanSquaredError
from google.colab import drive
drive.mount('/content/gdrive')
files = librosa.util.find_files('/content/gdrive/My Drive/Final Project 437/Number Recordings')
file_array = np.asarray(files)
data = []
nums = []
total_files = 0
for file in files:
print(file, total_files)
x, sr = librosa.load(file, res_type='kaiser_fast')
# Need to get number off file name
number = file[-6:-4]
if number[0] == '_':
number = number[1]
data.append(x)
total_files += 1
nums.append(number)
X = np.array(data, dtype=object)
y = np.array(nums, dtype=object)
i = 0
X_min = 1000000
while i < len(X):
if X_min > len(X[i]):
X_min = len(X[i])
i += 1
#RNN
def initialize_network(n_inputs, n_hidden, n_outputs):
network = list() # initialize weights to random number in [0..1]
hidden_layer = [{'weights':[random() for i in range(n_inputs+1)]} for i in range(n_hidden)]
network.append(hidden_layer)
output_layer = [{'weights':[random() for i in range(n_hidden+1)]} for i in range(n_outputs)]
network.append(output_layer)
return network
def activate(weights, inputs):
activation = weights[-1] # bias
for i in range(len(weights)-1):
activation += weights[i] * inputs[i]
return activation
def transfer(activation):
return 1.0 / (1.0 + exp(-activation))
def forward_propagate(network, X, y):
inputs = X
for layer in network:
new_inputs = []
for node in layer:
activation = activate(node['weights'], X)
node['output'] = transfer(activation)
new_inputs.append(node['output'])
inputs = new_inputs
return inputs
def transfer_derivative(output):
return output * (1.0 - output)
def backward_propagate_error(network, expected):
for i in reversed(range(len(network))):
layer = network[i]
errors = list()
if i != len(network)-1:
for j in range(len(layer)):
error = 0.0
for node in network[i+1]:
error += (node['weights'][j] * node['delta'])
errors.append(error)
else:
for j in range(len(layer)):
node = layer[j]
errors.append(expected[j] - node['output'])
for j in range(len(layer)):
network[i][j]['delta'] = errors[j] * transfer_derivative(node['output'])
return network
def update_weights(network, x, eta):
for i in range(len(network)):
inputs = x
if i != 0:
inputs = [node['output'] for node in network[i-1]]
for n in range(len(network[i])):
node = network[i][n]
for j in range(min(len(network[i][n]['weights']), len(inputs))):
network[i][n]['weights'][j] += eta * node['delta'] * inputs[j]
network[i][n]['weights'][-1] += eta * node['delta']
return network
def train_network(network, X, y, eta, num_epochs, num_outputs):
expected = np.full((50), 0)
for epoch in range(num_epochs):
sum_error = 0
for i in range(len(y)):
outputs = forward_propagate(network, X[i], y[i])
expected[int(y[i])] = 1
sum_error += sum([(expected[i] - outputs[i])**2 for i in range(len(expected))])
network = backward_propagate_error(network, expected)
network = update_weights(network, X[i], eta)
print('>epoch=%d, lrate=%.3f, error=%.3f' % (epoch, eta, sum_error))
return network
def test_network(network, X, y, num_outputs):
expected = np.full((50), 0)
sum_error = 0
for i in range(len(y)):
outputs = forward_propagate(network, X[i], y[i])
expected[int(y[i])] = 1
sum_error += sum([(expected[i] - outputs[i])**2 for i in range(len(expected))])
print('mse of test data is', sum_error / float(len(y)))
def main_bc():
n_inputs = X_min - 1
n_outputs = 50 # possible class values are 0 through 49
# Create the network
network = initialize_network(n_inputs, 2, n_outputs)
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.67, test_size=0.33)
# train network for 10 epochs using learning rate of 0.1
network = train_network(network, X_train, y_train, 0.1, 10, n_outputs)
test_network(network, X_test, y_test, n_outputs)
#DNN
def main_dnn():
#Data is a list of np.ndarrays, need to convert it to a list of tensors
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.67, test_size=0.33)
max_len = 50335
#X_train
#Padding for all data to be used
DNN_X_train = np.asarray([np.pad(a, (0, max_len - len(a)), 'constant', constant_values=0) for a in X_train])
#Splitting for shortest example so all use that amount of data
#DNN_X_train = []
#for element in X_train:
# temp = (np.split(element, [X_min, X_min + 1]))
# DNN_X_train.append(temp[0])
#DNN_X_train = np.array(DNN_X_train)
DNN_X_train = tf.convert_to_tensor(DNN_X_train, dtype=tf.float32)
print("Shape of X: ", DNN_X_train.shape)
#X_test
#Padding for all data to be used
DNN_X_test = np.asarray([np.pad(a, (0, max_len - len(a)), 'constant', constant_values=0) for a in X_test])
#Splitting for shortest example so all use that amount of data
#DNN_X_test = []
#for element in X_test:
# temp = (np.split(element, [X_min, X_min + 1]))
# DNN_X_test.append(temp[0])
#DNN_X_test = np.array(DNN_X_test)
DNN_X_test = tf.convert_to_tensor(DNN_X_test, dtype=tf.float32)
print("Shape of X_test: ", DNN_X_test.shape)
#y_train
DNN_y_train = tf.convert_to_tensor(y_train, dtype=tf.float32)
print("Shape of y: ", DNN_y_train.shape)
#y_test
DNN_y_test = tf.convert_to_tensor(y_test, dtype=tf.float32)
print("Shape of y: ", DNN_y_test.shape)
loss_fn = tf.keras.losses.MeanSquaredError()
model = Sequential()
model.add(tf.keras.Input(shape=(50335))) # padding up to most examples
#model.add(tf.keras.Input(shape=(3165))) #cutting down to minimum data
for i in range(300):
model.add(Dense(256, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(256))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(256))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(50))
model.add(Activation('softmax'))
model.compile(loss=loss_fn, metrics=['accuracy'], optimizer='adam')
model.fit(DNN_X_train, DNN_y_train, epochs=10)
#model.fit(DNN_dataset, epochs=10)
model.evaluate(DNN_X_test, DNN_y_test)
#model.evaluate(DNN_dataset)
if __name__ == "__main__":
main_bc()
main_dnn()
<file_sep>/README.md
# RNN-and-DNN-from-scratch
This project includes an RNN and a DNN created from scratch. They run over a dataset from kaggle of people saying the numbers 1-50. It pulls the data from the audio files and the number off the file name and then runs the RNN and DNN over the data. It then prints the resulting accuracy for comparison.
| 72243063ca22f641202d02904937b2e3232c1c49 | [
"Markdown",
"Python"
] | 2 | Python | Andrew-VanIderstine/RNN-and-DNN-from-scratch | 61331277245ca5892c6ece8138a5a2c825565b08 | 850908cc25ff6044a85d4dec899f91b6192ee422 |
refs/heads/master | <repo_name>BrandedNomad/Tickets<file_sep>/auth/src/controller/v0/auth/routes/sign-in.router.ts
/**
*@overview This file contains all the endpoints for the sign-in route
*/
//imports
import express,{Request,Response, Router} from 'express'
import {body, validationResult} from "express-validator";
import {RequestValidationError} from "../../../../errors/request-validation.error";
import {validateRequest} from "../../../../middleware/validate-request.middleware";
import ModelV0 from "../../index.model";
import {BadRequestError} from "../../../../errors/bad-request.error";
//Creating an express router
const signinRouter:Router = express.Router();
/**
* @route sign-in
* @purpose To sign-in existing users
* @path http://www.myticket.com/api/users/{api-version}/user/signin
* @method POST
*/
signinRouter.post('/signin',[
body('email')
.isEmail()
.withMessage('Email must be valid'),
body('password')
.trim()
.notEmpty()
.withMessage('You must supply a password')
],
validateRequest,
async (req:Request, res:Response)=>{
const existingUser = await ModelV0.User.findByCredentials(req.body.email,req.body.password);
if(!existingUser){
throw new BadRequestError('Invalid credentials')
}else{
const token = ModelV0.User.generateAuthToken(existingUser)
existingUser.tokens = existingUser.tokens.concat({token:token})
req.session = {
jwt: token
}
await existingUser.save();
res.status(200).send(existingUser)
}
})
//exports
export = signinRouter;
<file_sep>/auth/src/controller/v0/auth/routes/sign-up.router.ts
/**
*@overview This file contains all the endpoints for the User route
*/
//imports
import express,{Request,Response, Router} from 'express'
import {body, validationResult} from 'express-validator';
import {RequestValidationError} from "../../../../errors/request-validation.error";
import ModelV0 from "../../index.model";
import {BadRequestError} from "../../../../errors/bad-request.error";
import {validateRequest} from "../../../../middleware/validate-request.middleware";
//Creating a router
const signupRouter:Router = express.Router();
/**
* @route sign-up
* @purpose To sign-up new users
* @path http://www.myticket.com/api/users/{api-version}/user/signup
* @method POST
*/
signupRouter.post('/signup',[
//express-validator middleware for validation of user input
//appends any error messages onto the req object
body('email')
.isEmail()
.withMessage('Email must be valid'),
body('password')
.trim()
.isLength({min:4,max:20})
.withMessage('Password must be between 4 and 20 characters long')
],
validateRequest,
async (req:Request, res:Response)=>{
//extracting user input
const {email, password} = req.body;
//check if user allready exist
const existingUser = await ModelV0.User.findOne({email});
if(existingUser){
throw new BadRequestError('Email already exists! Please provide a different email')
}
//create a new user
const user = ModelV0.User.createNewUser({email,password})
const token = ModelV0.User.generateAuthToken(user)
user.tokens = user.tokens.concat({token:token})
req.session = {
jwt: token
}
await user.save();
//create log
let logInfo={
message:"Successfully created new user",
ip:req.ip,
user:user.email,
url:req.originalUrl,
}
//Send response
res.status(201).send(user)
})
//exports
export = signupRouter
<file_sep>/client/pages/_app.js
import 'bootstrap/dist/css/bootstrap.css'
import buildClient from "../api/build-client";
import Header from '../components/header.js';
/**
* @component
* @description Wraps entire application in a wrapper component, which provides access to global variables
* @param currentUser
* @param Component
* @param pageProps
* @return {JSX.Element}
*/
const AppComponent = ({Component, pageProps, currentUser}) => {
return (
<div>
<Header currentUser = {currentUser}/>
<Component {...pageProps}/>
</div>
)
}
/**
* @function getInitialProps
* @description
* Used to modify or update component props before the component is rendered.
* This is a great place for api calls or http requests.
* This method is executed by the server, during/when:
* - Hard refresh of page
* - Clicking link from different domains
* - Typing the URL into the address bar
* This method is executed by the client, during/when:
* - Navigating from one page to another while in the app.
* @return {{}} The props that will be passed into the component
*/
AppComponent.getInitialProps = async (appContext) => {
//GLOBAL APP STATE
//check if current user is authenticated
const client = buildClient(appContext.ctx)
const response = await client.get('/api/users/v0/user/currentuser')
.catch((error)=>{
console.log(error)
})
//INDIVIDUAL PAGE STATE
//calls the getInitialProps function for the individual page that is being loaded
//otherwise this will not be called, because it is being called in the AppComponent
let pageProps = {};
if(appContext.Component.getInitialProps){ //some pages don't have this defined
pageProps = await appContext.Component.getInitialProps(appContext.ctx)
}
if(response !== undefined){
return {
pageProps,
...response.data
}
}else{
return {
pageProps
}
}
}
export default AppComponent;
<file_sep>/auth/src/errors/not-found.error.ts
import {CustomError} from "./custom.error";
export class NotFoundError extends CustomError {
statusCode:number = 404;
constructor(){
super("Route not found");
Object.setPrototypeOf(this,NotFoundError.prototype);
}
serializeErrors(): { message: string; field?: string }[] {
return [{message:'Resource not found'}];
}
}
<file_sep>/auth/src/controller/v0/index.model.ts
/**
* @overview This file indexes all available models
*/
//import
import User from "./auth/models/user.model";
//creating a versioned object
const ModelV0 = {
User
}
//export models
export = ModelV0
<file_sep>/client/pages/index.js
import buildClient from '../api/build-client'
const LandingPage = ({currentUser}) => {
return currentUser ? <h1>You are signed in</h1> : <h1>You are NOT signed in</h1>
};
/**
* @function getInitialProps
* @description
* Used to modify or update component props before the component is rendered.
* This is a great place for api calls or http requests.
* This method is executed by the server, during/when:
* - Hard refresh of page
* - Clicking link from different domains
* - Typing the URL into the address bar
* This method is executed by the client, during/when:
* - Navigating from one page to another while in the app.
* @return {{}} The props that will be passed into the component
*/
LandingPage.getInitialProps = async (context) => {
//check if current user is authenticated
const client = buildClient(context)
const response = await client.get('/api/users/v0/user/currentuser')
.catch((error)=>{
console.log(error)
})
if(response !== undefined){
return response.data
}else {
return {}
}
}
export default LandingPage;
<file_sep>/auth/src/controller/v0/index.router.ts
/**
* @overview This file contains an index for all available routes.
*
*/
//imports
import express, {Request, Response, Router} from 'express';
import 'express-async-errors';
import currentuserRouter from './auth/routes/currentuser.router';
import signinRouter from './auth/routes/sign-in.router'
import signoutRouter from './auth/routes/sign-out.router'
import signupRouter from './auth/routes/sign-up.router'
import {errorHandler} from "../../middleware/error-handler.middleware";
import {NotFoundError} from "../../errors/not-found.error";
import mongoose from "mongoose";
//Creating a router object
const indexRouter:Router = express.Router();
//Setting up user routes.
//IndexRouter automatically chooses the correct router, based on the URL provided
indexRouter.use('/user', currentuserRouter);
indexRouter.use('/user', signupRouter);
indexRouter.use('/user', signinRouter);
indexRouter.use('/user', signoutRouter);
//Health-check
indexRouter.get('/status',(req:Request,res:Response)=>{
const mongooseStatuses = ["disconnected","connected","connection","disconnecting"]
const dbStatus:number = parseInt(mongoose.STATES[mongoose.connection.readyState])
res.status(200).send({
dbStatus:mongooseStatuses[dbStatus]
})
//0: disconnected
//1: connected
//2: connection
//3: disconnecting
})
//When url doesn't match any of the provided paths
//Throws a 404 not found error.
//To handle async errors, you could make it an async function and
//call the next() function at the end
//however I've opted to use the express-async-errors module
//which allows me to use the async keyword without having to call next
indexRouter.all('/user/*', async ()=>{
throw new NotFoundError();
})
//NOTE: errorHandler is a middleware function (not a router)
//that handles any errors generated by any of the routes
indexRouter.use('/user', errorHandler);
//exports
export = indexRouter;
<file_sep>/auth/src/errors/custom.error.ts
/**
* @overview this file contains the abstract class Custom Error
* CustomError was created a an abstract class to ensure that
* subclasses will implement the serializeError method correctly
*/
/**
* @class CustomError
* @extends Error
* @purpose To provide a method signature for the serializeErrors method
* which will ensure that all subclasses of Custom class implements this method
* correctly
*/
export abstract class CustomError extends Error {
//All subclasses need ot have a status code
abstract statusCode: number;
/**
* @Constructor
* @param {string} message The message that prints to the terminal whenever
* an error is thrown
*/
constructor(message: string){
super(message)
//Ensure that all subclasses contains Error in its prototype chain
Object.setPrototypeOf(this, CustomError.prototype);
}
/**
* @method serializeErrors()
* @description All subclasses must implement this method
* @returns {message: string, field?: string}
*/
abstract serializeErrors(): {message: string; field?: string}[];
}
<file_sep>/auth/src/controller/v0/auth/routes/__test__/sign-in.router.test.ts
/**
* @overview This file contains all the tests for the signin route
*/
import request from 'supertest';
import {server} from "../../../../../app";
it('fails when an email that does not exist is supplied', async()=>{
return request(server)
.post('/api/users/v0/user/signin')
.send({
email:'<EMAIL>',
password:'<EMAIL>'
})
.expect(400)
})
it('fails when incorrect password is supplied', async()=>{
await request(server)
.post('/api/users/v0/user/signup')
.send({
email:'<EMAIL>',
password:'<EMAIL>5<EMAIL>'
})
.expect(201)
return request(server)
.post('/api/users/v0/user/signin')
.send({
email:'<EMAIL>',
password:'<EMAIL> <PASSWORD> <EMAIL>'
})
.expect(400)
})
it('responds with a cookie when given valid credentials', async()=>{
//creates a new account
await request(server)
.post('/api/users/v0/user/signup')
.send({
email:'<EMAIL>',
password:'<EMAIL>'
})
.expect(201)
//signs into account
const response = await request(server)
.post('/api/users/v0/user/signin')
.send({
email:'<EMAIL>',
password:'<EMAIL>'
})
.expect(200)
//checks if cookie has been set
expect(response.get('Set-Cookie')).toBeDefined()
})
<file_sep>/auth/src/controller/v0/auth/routes/__test__/sign-out.router.test.ts
/**
* @overview This file contains all the tests for the signout route
*/
import request from 'supertest';
import {server} from "../../../../../app";
it('it clears the cookie after signing out', async()=>{
const authResponse = await request(server)
.post('/api/users/v0/user/signup')
.send({
email:'<EMAIL>',
password:'<EMAIL>999<EMAIL>'
})
.expect(201)
const cookie = authResponse.get('Set-Cookie')
const response = await request(server)
.post('/api/users/v0/user/signout')
.set('Cookie',cookie)
.send({})
.expect(200)
expect(response.get('Set-Cookie')[0]).toEqual(
'express:sess=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; httponly'
)
})
<file_sep>/auth/src/test/setup.ts
import {MongoMemoryServer} from "mongodb-memory-server";
import mongoose from 'mongoose'
import {server} from "../app";
import request from "supertest";
declare global {
var signin: () => Promise<string[]>;
}
let mongo:any;
//Before all tests
beforeAll(async ()=>{
//setup environment variables
process.env.JWT_SECRET = 'test'
process.env.NODE_ENV = 'test'
//Create a new instance of MongoDB
mongo = await MongoMemoryServer.create();
let mongoUri = mongo.getUri();
await mongoose.connect(mongoUri, {
useNewUrlParser:true,
useUnifiedTopology:true
});
});
//before each test runs
beforeEach(async ()=>{
//delete all existing data from database
const collections = await mongoose.connection.db.collections()
for(let collection of collections){
await collection.deleteMany({})
}
})
//after all tests have been completed
afterAll(async ()=>{
//stop the mongo server
await mongo.stop();
})
global.signin = async () => {
const email = '<EMAIL>';
const password = '<PASSWORD>';
const response = await request(server)
.post('/api/users/v0/user/signup')
.send({
email,
password
})
.expect(201);
const cookie = response.get('Set-Cookie')
return cookie
}
<file_sep>/auth/src/controller/v0/auth/routes/__test__/sign-up.router.test.ts
/**
* @overview This file contains all the tests for the signup route
*/
import request from 'supertest';
import {server} from "../../../../../app";
it('returns a 201 on successful signup', async()=>{
return request(server)
.post('/api/users/v0/user/signup')
.send({
email:'<EMAIL>',
password:'<EMAIL>'
})
.expect(201)
})
it('returns a 400 with an invalid email', async ()=>{
return request(server)
.post('/api/users/v0/user/signup')
.send({
email:'test<EMAIL>',
password:'<EMAIL>'
})
.expect(400)
})
it('returns a 400 with an invalid password', async ()=>{
return request(server)
.post('/api/users/v0/user/signup')
.send({
email:'<EMAIL>',
password:'t'
})
.expect(400)
})
it('returns a 400 when no email or password is provide', async ()=>{
await request(server)
.post('/api/users/v0/user/signup')
.send({
email:'<EMAIL>',
password:''
})
.expect(400)
return request(server)
.post('/api/users/v0/user/signup')
.send({
email:'',
password:'<EMAIL>'
})
.expect(400)
})
it('returns a 400 when no email or password is provide', async ()=>{
await request(server)
.post('/api/users/v0/user/signup')
.send({
email:'',
password:''
})
.expect(400)
return request(server)
.post('/api/users/v0/user/signup')
.send({})
.expect(400)
})
it('disallows duplicate emails', async ()=>{
await request(server)
.post('/api/users/v0/user/signup')
.send({
email:'<EMAIL>',
password:'<EMAIL>'
})
.expect(201)
return request(server)
.post('/api/users/v0/user/signup')
.send({
email:'<EMAIL>',
password:'<EMAIL>'
})
.expect(400)
})
it('sets a cookie after successful signup', async ()=>{
const response = await request(server)
.post('/api/users/v0/user/signup')
.send({
email:'<EMAIL>',
password:'<EMAIL>'
})
.expect(201)
//checks if cookie has been set
//the environment variable has been set to false to allow for http connection
expect(response.get('Set-Cookie')).toBeDefined();
})
<file_sep>/auth/src/middleware/current-user.middleware.ts
import {Request,Response,NextFunction} from "express";
import ModelV0 from "../controller/v0/index.model";
interface UserPayload {
id: string;
email: string
}
declare global {
namespace Express {
interface Request {
currentUser?:UserPayload;
}
}
}
export const currentUser = (req:Request, res:Response, next:NextFunction)=>{
if(!req.session?.jwt){
return next();
}
//checks if token is valid
const payload = ModelV0.User.validateAuthToken(req.session.jwt)
const userPayload = payload.currentUser as UserPayload
if(userPayload === null){
//do nothing
}else{
//set current user
req.currentUser = userPayload
}
next()
}
<file_sep>/client/pages/auth/signin.js
/**
* @overview This file contains the sign-in page
*/
import {useState} from 'react'
import Router from 'next/router'
import useRequest from "../../hooks/use-request";
/**
* @page Sign In
* @description A page where existing users can sign-in using their credentials
* @return {JSX.Element}
*/
const signin = ()=>{
//keeps track of user credentials
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
//creates a client object that can be called when the user submits the form
const {doRequest, errors, onSuccess} = useRequest({
url:"/api/users/v0/user/signin",
method:'post',
body:{
email,
password
},
onSuccess: ()=>{
Router.push('/')
}
})
//Sends user credentials to auth server for validation
const submit = async (event)=>{
event.preventDefault()
await doRequest();
}
//returns the jsx component
return (
<form onSubmit={submit}>
<h1>Sign In</h1>
<div className ="form-group">
<label>Email Address</label>
<input
className="form-control"
value={email}
onChange={(event)=>{
setEmail(event.target.value)
}}
/>
</div>
<div className = "form-group">
<label>Password</label>
<input
type="<PASSWORD>"
className="form-control"
value={password}
onChange={(event)=>{
setPassword(event.target.value)
}}
/>
</div>
{errors}
<button className="btn btn-primary">Sign Up</button>
</form>
)
}
export default signin;
<file_sep>/auth/src/index.ts
import mongoose from "mongoose";
import {server} from "./app";
//set port
const port: string | undefined = process.env.PORT
/**
* @function start
* @description establishes a connection to the mongodb database and starts the server
* @Returns {Promise<void>}
*/
const start = async():Promise<void> => {
if(!process.env.JWT_SECRET){
throw new Error('JWT_SECRET must be defined')
}
try{
//@ts-ignore
//connecting to database
await mongoose.connect(process.env.DATABASE_CONNECTION_STRING, {
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true,
useFindAndModify:false
});
console.log("Successfully Connected to MongoDB", mongoose.connection.readyState)
}catch(error:any){
console.log(error.toString())
}
//starts the server
server.listen(port,()=>{
console.log("Server up and running on port: " + port)
})
}
//start the server
start();
<file_sep>/auth/src/utils/logger.util.ts
import fs from 'fs'
import path from "path/posix";
interface LogParams {
message: string;
ip?: string;
user?: string;
url?: string;
info?: string;
}
class Logger {
private config:{
logFilePath:string
}
constructor(config:{logFilePath:string}) {
this.config = config
}
getConfig():{}{
return this.config
}
private writeToFile(content:string){
try {
fs.appendFile(path.join(__dirname,this.config.logFilePath), content, err => {
if (err) {
console.error(err)
return
}
})
}catch(error){
console.log(error)
}
}
// An event that describes the successful operation of a task, such as an application, driver, or service. For example,
// an Information event is logged when a network driver loads successfully.
info(logParams:LogParams){
const date = new Date()
const log = {
type:"INFO",
date: `${date.toDateString()} ${date.toTimeString()}`,
ip: logParams.ip || '',
message:logParams.message,
user: logParams.user || "",
url: logParams.url || ''
}
const messageToLog: string = `${log.type}: ${log.date}. ${log.message}. User: ${log.user}. Ip: ${log.ip}. URL: ${log.url}`
this.writeToFile(messageToLog)
}
//An event that is not necessarily significant, however, may indicate the possible occurrence of a future problem.
// For example, a Warning message is logged when disk space starts to run low
warn(logParams:LogParams){
const date = new Date()
const log = {
type:"WARN",
date: `${date.toDateString()} ${date.toTimeString()}`,
ip: logParams.ip || '',
message:logParams.message,
user: logParams.user || '',
url: logParams.url || ''
}
const messageToLog: string = `${log.type}: ${log.date}. ${log.message}. User: ${log.user}. Ip: ${log.ip}. TargetURL: ${log.url}`
this.writeToFile(messageToLog)
}
//An event that indicates a significant problem such as loss of data or loss of functionality.
// For example, if a service fails to load during startup, an Error event is logged.
error(logParams:LogParams){
const date = new Date()
const log = {
type:"ERROR",
date: `${date.toDateString()} ${date.toTimeString()}`,
ip: logParams.ip || '',
message:logParams.message,
user: logParams.user || '',
url: logParams.url || '',
info:logParams.info || ''
}
const messageToLog: string = `${log.type}: ${log.date}. ${log.message}. User: ${log.user}. Ip: ${log.ip}. TargetURL: ${log.url}`
this.writeToFile(messageToLog)
}
}
export = Logger
<file_sep>/auth/src/controller/v0/auth/routes/currentuser.router.ts
/**
*@overview This file contains all the endpoints for the currentuser route
* The currentUser route checks to see if a current user is authenticated or not
*/
//imports
import express,{Request,Response,Router} from 'express'
import ModelV0 from "../../index.model";
import {currentUser} from "../../../../middleware/current-user.middleware";
import {requireAuth} from "../../../../middleware/require-auth.middleware";
//Creating an express router
const currentuserRouter:Router = express.Router();
/**
* @route currentuser
* @purpose Returns the details of the current user
* @path https://www.myticket.com/api/users/{api-version}/user/currentuser
* @method GET
*/
currentuserRouter.get('/currentuser',currentUser, requireAuth, (req:Request, res:Response)=>{
res.status(200).send({currentUser: req.currentUser || null});
})
//exports
export = currentuserRouter;
<file_sep>/auth/src/errors/database-connection.error.ts
/**
* @overview This file contains the ValidationError class.
* Error subclasses are necessary to normalize the responses across different microservices
*/
//imports
import {CustomError} from "./custom.error";
/**
* @class DatabaseConnectionError
* @description extends the base class Error, and is used to normalize the error response
* for database connection errors
*/
export class DatabaseConnectionError extends CustomError {
//Response status code
statusCode: number = 500;
//The error message
reason = 'Error connecting to database';
constructor(){
super('Error connecting to Database');
//Only because we are extending a built in class
//Ensures that objects created by RequestValidationError gets
//the Error object in it's prototype chain
Object.setPrototypeOf(this, DatabaseConnectionError.prototype);
}
/**
* @method serializeErrors
* @description Formats error messages into a normalized response
* @return {Object} The normalized error message
*/
serializeErrors(){
return [
{message:this.reason}
]
}
}
<file_sep>/auth/src/controller/v0/auth/routes/__test__/currentuser.router.test.ts
/**
* @overview This file contains all the tests for the currentuser route
*/
import request from 'supertest';
import {server} from "../../../../../app";
it('it responds with details of the current user', async ()=>{
//get the cookie from first response to be set as header on second response
const cookie = await global.signin();
const response = await request(server)
.get('/api/users/v0/user/currentuser')
.set('Cookie', cookie)
.send()
.expect(200)
})
it('responds with null if not authenticated',async ()=>{
const response = await request(server)
.get('/api/users/v0/user/currentuser')
.send()
.expect(401)
expect(response.body.currentUser === null)
})
<file_sep>/auth/src/errors/request-validation.error.ts
/**
* @overview This file contains the ValidationError class.
* Error subclasses are necessary to normalize the responses across different microservices
*/
//used to assign an error type
import {ValidationError} from 'express-validator';
import {CustomError} from "./custom.error";
/**
* @class RequestValidationError
* @description extends the base class Error, and is used to normalize the error response
* for user input validation errors.
*/
export class RequestValidationError extends CustomError {
//response status code
statusCode: number = 400;
/**
* @constructor
* @param {ValidationError[]} errors An array of errors generated by the express-validator middleware
*/
constructor(public errors: ValidationError[]){
super('Invalid request parameters');
//Only because we are extending a built in class
//Ensures that objects created by RequestValidationError gets
//the Error object in it's prototype chain
Object.setPrototypeOf(this, RequestValidationError.prototype);
}
/**
* @method serializeErrors
* @description Formats error messages into a normalized response
* @return {Object} The normalized error message
*/
serializeErrors(){
//contains an array of errors generated by the express-validator middleware
//formats the errors into the desired format
//NOTE: the field property is optional and won't be present on all error messages
return this.errors.map(error=>{
return {message: error.msg,field:error.param}
});
}
}
<file_sep>/auth/src/middleware/error-handler.middleware.ts
/**
* @overview This file contains error handler middleware
*/
//import statements
import {NextFunction, Request,Response} from "express";
import {CustomError} from "../errors/custom.error";
/**
* @function errorHandler
* @description This function handles errors generated by any of the route handlers
* and ensures that all final error messages are normalized (have the same structure)
* @param {Error | RequestValidationError | DatabaseConnectionError} err The error message thrown by the Error object
* @param {Request} req The request object
* @param {Response} res The response object
* @param {NextFunction} next Function to be called when all is done.
* @return {Response} The normalized error message with the structure: {errors:[{message:err.message}]}
*/
export const errorHandler = (
err: Error,
req: Request,
res: Response,
next: NextFunction
) => {
//checks if error is an instance of custom error and handles the error accordingly
if(err instanceof CustomError ){
return res.status(err.statusCode).send({errors:err.serializeErrors()})
}
//Any other type of error
res.status(400).send({errors:[
{message:"Something went wrong"}
]})
}
<file_sep>/auth/src/controller/v0/auth/routes/sign-out.router.ts
/**
*@overview This file contains all the endpoints for the sign-out route
*/
//imports
import express,{Request,Response,Router} from 'express'
import ModelV0 from "../../index.model";
//Creating a router
const signoutRouter:Router = express.Router();
/**
* @route sign-out
* @purpose To sign-out logged-in users
* @path http://www.myticket.com/api/users/{api-version}/user/signout
* @method POST
*/
signoutRouter.post('/signout',async (req:Request, res:Response)=>{
//remove token from stored tokens
// @ts-ignore
let jwt = req.session.jwt
ModelV0.User.removeToken(jwt)
//remove cookie from header
req.session = null
res.status(200).send({})
})
//exports
export = signoutRouter
<file_sep>/auth/src/controller/v0/auth/models/user.model.ts
/**
* @overview This file contains the User Model
*/
//import
import mongoose from 'mongoose';
import {Password} from "../../../../utils/password.util";
import jwt,{Secret} from 'jsonwebtoken';
import dotenv from 'dotenv';
import {BadRequestError} from "../../../../errors/bad-request.error";
//access env variables
dotenv.config()
//An interface that describes the properties that is required to create a new user.
interface UserAttrs {
email: string;
password: string;
}
//an interface that describes the properties that a user model has
interface UserModel extends mongoose.Model<UserDoc> {
createNewUser(attrs: UserAttrs): UserDoc;
generateAuthToken(user:UserDoc): string;
findByCredentials(email:string,password:string):UserDoc
validateAuthToken(token:string):any
removeToken(token:any):any
}
//an interface that describes the properties that a User Document has
interface UserDoc extends mongoose.Document {
email: string;
password: string;
tokens: object[];
updatedAt: string;
createdAt: string;
}
//Creating the User Schema
const userSchema = new mongoose.Schema({
email:{
type:String,
required:true,
trim:true,
lowercase:true,
},
password:{
type:String,
required:true,
trim:true,
min:4
},
tokens:[{
token:{
type:String
}
}]
},{
timestamps:true,
toJSON:{ //specifies which information to return publicly
transform(doc,ret){
ret.id = ret._id;
delete ret._id;
delete ret.password;
//delete ret.tokens;
delete ret.createdAt;
delete ret.updatedAt;
delete ret.__v;
}
}
})
//Instance methods
/**
* @method generateAuthToken
* @description generates and stores a new jwt token
* @return
*/
userSchema.methods.generateAuthToken = async function(){
//@ts-ignore
const user:UserDoc = this;
const token = jwt.sign({id:user.id,email: user.email},process.env.JWT_SECRET as Secret);
user.tokens = user.tokens.concat({token:token})
}
//Object methods
/**
* @method createNewUser
* @description Used instead of the new User() method to create a new User.
* This is done to ensure that Typescript can type-check the arguments passed into
* the function, as TS doesn't work well with the new User function
* @param {UserAttrs} attrs An object that contains an email and password
* @return {User}
*/
userSchema.statics.createNewUser = (attrs: UserAttrs) =>{
return new User(attrs);
};
/**
* @method generateAuthToken
* @description generates and JWT authentication token
* @param {UserDoc} user The user for which the token is to be generated
* @return {string} JWT auth token
*/
userSchema.statics.generateAuthToken = function(user:UserDoc):string{
//@ts-ignore
const token = jwt.sign({id:user.id,email: user.email},process.env.JWT_SECRET as Secret);
return token
}
/**
* @method validateAuthToken
* @description checks if a given toke is valid or not
* @param token
* @return object that contains the decoded token or false
*/
userSchema.statics.validateAuthToken = function(token:string){
try{
let payload = jwt.verify(
token,
process.env.JWT_SECRET!
);
return {currentUser: payload}
}catch(error){
return {currentUser: null}
}
}
/**
*
*/
userSchema.statics.removeToken = async function(token:any){
let details = User.validateAuthToken(token)
let user:any = await User.findOne({_id:details.currentUser.id})
user.tokens = user.tokens.filter((item:any)=>{
return item.token !== jwt
})
user.save()
}
/**
* @method findByCredentials
* @description uses user details to check whether that user exists or not
* @param {string} email The user's email address
* @param {string} password The <PASSWORD>'s <PASSWORD>
* @return user the user details (if the user exists)
*/
userSchema.statics.findByCredentials = async (email,password)=>{
//Check if email exists
const user = await User.findOne({email}).catch((error)=>{
console.log(error)
})
//Throw error if email not found
if(!user){
throw new BadRequestError('Invalid credentials')
}
//check if passwords match
const isMatch = await Password.compare(user.password,password).catch((error)=>{
console.log(error)
})
if(!isMatch){
throw new BadRequestError('Invalid credentials')
}
//Return user if found
return user
}
//MIDDLEWARE
/**
* @description Whenever a new user is created or a user password is updated, this
* function hashes the password before it is saved in the database, therefore
* ensuring that plain text passwords are never saved
*/
userSchema.pre('save', async function(next){
//@ts-ignore
const user:UserDoc = this
if(user.isModified('password')){
user.password = await Password.toHash(user.password)
}
next()
})
//creating the User model
const User = mongoose.model<UserDoc, UserModel>('User',userSchema);
//export model
export = User
<file_sep>/auth/src/app.ts
/**
* @overview REST API Server that serves up request
*
*/
//imports
import express, {Express,Response,Request} from 'express';
import bodyParser from 'body-parser';
import indexRouter from "./controller/v0/index.router";
import dotenv from 'dotenv'
import mongoose from 'mongoose'
import cookieSession from "cookie-session";
//Access Environment Variables
dotenv.config()
//creating a server instance
const server:Express = express()
//To make express aware that it is behind an nginx proxy
//and that it should still trust the traffic coming from that proxy
//even though it is coming from a proxy
//needed for accepting cookies
server.set('trust proxy', true)
//configuring index to parse the body of requests
server.use(bodyParser.json())
//Configuration for Cookies
server.use(
cookieSession({
signed: false,
secure: process.env.NODE_ENV !== 'test' //only used when user visits on https connection, otherwise defaults to http
})
)
//CORS POLICY middleware
// index.use(function(req,res,next){
// res.header("Access-Control-Allow-Origin","*");
// res.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization");
// res.header("Access-Control-Allow-Methods","GET, PUT, POST, DELETE, OPTIONS")
// next();
// })
//url structure https://myticket.dev/api/auth/v0/user/currentuser
//Setting up Root URI call
server.use('/api/users/' + process.env.ROUTE_VERSION + '/', indexRouter);
//Health-check
server.get('/api/users/status',(req:Request,res:Response)=>{
const dbStatus:string = mongoose.STATES[mongoose.connection.readyState]
res.status(200).send({
dbStatus
})
//0: disconnected
//1: connected
//2: connection
//3: disconnecting
})
server.get('/api/users/metrics', (req: Request, res:Response)=>{
res.status(200).send("Total number of requests: ")
})
export {server};
<file_sep>/auth/src/errors/bad-request.error.ts
/**
* @overview This file contains the BadRequestError class.
* Error subclasses are necessary to normalize the responses across different microservices
*/
//imports
import {CustomError} from "./custom.error";
/**
* @class BAdRequestError
* @description extends the base class Error, and is used to normalize the error response
* for bad request errors
*/
export class BadRequestError extends CustomError {
//Response status code
statusCode: number = 400;
constructor(public message:string){
super(message);
//Only because we are extending a built in class
//Ensures that objects created by RequestValidationError gets
//the Error object in it's prototype chain
Object.setPrototypeOf(this, BadRequestError.prototype);
}
/**
* @method serializeErrors
* @description Formats error messages into a normalized response
* @return {Object} The normalized error message
*/
serializeErrors(){
return [
{message:this.message}
]
}
}
<file_sep>/auth/src/utils/metrics.util.ts
class Metrics {
private metrics: {
totalRequests:number,
totalErrors:number,
requestBreakdown:{}
}
constructor() {
this.metrics = {
totalRequests:0,
totalErrors:0,
requestBreakdown:{
}
}
}
requestCount(path:string,count:number){
this.metrics.totalRequests += count;
}
getMetrics(){
return this.metrics
}
errorCount(){
}
}
export const metrics = new Metrics()
| 5d4dd9b0387df43a7ee7fe024e955aa5b57e4d1e | [
"JavaScript",
"TypeScript"
] | 26 | TypeScript | BrandedNomad/Tickets | 7fff387067d10fb1190d635b481637c614c5f477 | 695a31b6e7174c7a7daaa4ff744c63678b782892 |
refs/heads/master | <file_sep>import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
// Google Analytics
// tslint:disable-next-line
document.write('<script type="text/javascript">(function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,\'script\',\'https://www.google-analytics.com/analytics.js\',\'ga\'); ga(\'create\', "' + environment.googleAnalyticsId + '", \'auto\');</script>');
// Intercom
// tslint:disable-next-line
document.write('<script type="text/javascript">window.intercomSettings = {app_id: "' + environment.intercomId + '"};(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic(\'reattach_activator\');ic(\'update\',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement(\'script\');s.type=\'text/javascript\';s.async=true;s.src=\'https://widget.intercom.io/widget/fwfluyay\';var x=d.getElementsByTagName(\'script\')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent(\'onload\',l);}else{w.addEventListener(\'load\',l,false);}}})()</script>');
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
<file_sep>export const environment = {
googleAnalyticsId: 'UA-64768458-4',
intercomId: 'fwfluyay',
production: true,
};
| 477a04baef2314841b60dd1b0c1b2f4b901d2fe1 | [
"TypeScript"
] | 2 | TypeScript | markjdvs/rubric-creator | 4a55b2039a0abff1786c32a96eccbf912c9d10ef | b0053c23f71dcdfbd9a9e3b2946755a0f5c9e1b1 |
refs/heads/master | <repo_name>hatchways/team-strawberry<file_sep>/software/software.py
comments = [
{"id": 1, "body": "Comment 1", "parent": 3},
{"id": 2, "body": "Comment 2", "parent": 1},
{"id": 3, "body": "Comment 3", "parent": None},
{"id": 4, "body": "Comment 4", "parent": 5},
{"id": 5, "body": "Comment 5", "parent": None},
{"id": 6, "body": "Comment 6", "parent": 5},
{"id": 7, "body": "Comment 7", "parent": 1}
]
def print_comments(comments, parent=None, tab=""):
for i in range(len(comments)):
comment = comments[i]
if comment['parent'] == parent:
print(tab + comment['body'])
print_comments(comments, comment['id'], tab+" ")
print_comments(comments)
<file_sep>/backend/express/README.md
# Backend Assessment
The objective of this assessment is to write a simple JSON API.
## Getting started
- To install all required modules: `npm install`
- To start the application: `node back-end.js`
## Instructions
You are acting as an evaluator and this is a incoming submission. **Your goal is to evaluate this submission to the best of your ability and provide feedback.**
This is the backend assessment. For the full instructions, you can see them here: [instructions](https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/instructions/b-3/Back-end%20Assessment%20-%20Blog%20Posts-S7WK70UAN1EEOCZ4AOIC.pdf)
- **This submission may contain some bugs before you're able to run it**
- Generally, we mark assessments using this [rubric](https://drive.google.com/file/d/1f0jiSVTTGtAn8XbHwHcTqPEU-BT4-q6x/view). There are 5 categories: Correctness, Code Organization, Readability & Maintainability, Code performance, Best practices and completion speed. You can ignore the completion speed.
- **Correctness**: This submission generally works in terms of functionality
- **Code Organization, Readability & Maintainability**: Is this code readable? How easy was it to trace through the code? Anything you would suggest to improve it?
- **Code performance (Efficiency, Data Structures & Algorithms)**: Anywhere you can spot in the code that could have been improved in terms of code performance?
- **Best practices**: Look at the code and the framework. Are there any bad practices? If so, please point them out and provide suggestions and feedback
- Create a new markdown document for note taking. We will evaluate your feedback/evaluation of this submission by seeing if you can identify areas of improvement based off of this code.
- **Submission**: Submit your markdown document
<file_sep>/frontend/src/components/Student.js
import React, { Component } from "react";
import "./Student.css";
import NewTag from "./NewTag";
class Student extends Component {
constructor(props) {
super(props);
this.state = {
expand: false,
tags: []
};
this.calculateAverage = this.calculateAverage.bind(this);
this.handleIconClick = this.handleIconClick.bind(this);
this.addTags = this.addTags.bind(this);
}
addTags(tag) {
this.setState(prevState => ({
...prevState,
tags: [...prevState.tags, tag]
}));
}
calculateAverage(arr) {
let total = arr.reduce((curr, prev) => {
return Number(curr) + Number(prev);
}, 0);
return total / arr.length;
}
handleIconClick() {
console.log("im in the matrix");
this.setState(prevState => ({
expand: !prevState.expand
}));
}
render() {
const { student } = this.props;
const { grades } = student;
const average = this.calculateAverage(grades);
const { expand } = this.state;
let icon = expand ? "fas fa-minus" : "fas fa-plus";
const expandedView = expand ? (
<React.Fragment>
<div className="grades">
{grades.map((grade, idx) => (
<p key={idx}>
Test {+idx + 1}: {grade}%
</p>
))}
</div>
<div className="tag-list">
{this.state.tags.map((tag, idx) => (
<p className="tag">{tag}</p>
))}
</div>
<NewTag id={student.id} addTags={this.addTags} />
</React.Fragment>
) : null;
return (
<div className="student-card">
<div className="expand-button">
<button className="button" onClick={this.handleIconClick}>
<i className={icon} />
</button>
</div>
<img
src={student.pic}
alt={`student-img-${student.id}`}
className="student-avatar"
/>
<div className="student-main">
<p className="student-name">
{student.firstName} {student.lastName}
</p>
<div className="student-description">
<p>Email: {student.email}</p>
<p>Company: {student.company}</p>
<p>Skill: {student.skill}</p>
<p>Average: {average} %</p>
</div>
{expandedView}
</div>
</div>
);
}
}
export default Student;
<file_sep>/frontend/src/StudentAPI.js
import axios from 'axios';
const API = `https://www.hatchways.io/api/assessment/students`;
export async function getAll(){
try {
const res = await axios.get(`${API}`);
return res.data
} catch(err){
console.log(err);
}
}
<file_sep>/backend/flask/app.py
from operator import itemgetter
from flask import Flask, jsonify, request
import requests
import json
from functools import wraps
app = Flask(__name__)
cache = {}
def cache_middleware():
def wraps_func(f):
@wraps(f)
def middleware(*args, **kwargs):
cache_key = request.full_path
if cache_key in cache:
return cache[cache_key], 200
else:
return f(*args, **kwargs)
return middleware
return wraps_func
@app.route('/api/posts', methods=['GET'])
@cache_middleware()
def posts():
results = []
for tag in req.args['tags'].split(','):
res = requests.get("https://hatchways.io/api/assessment/blog/posts?tag={}".format(tag))
results.append(res.json()['posts'])
results = [json.loads(a) for a in set(json.dumps(post for posts in results for post in posts))]
if request.args['sortBy'] == 'id':
results = sorted(results,
key=itemgetter('id'),
reverse=request.args['direction'] == 'asc')
elif request.args['sortBy'] == 'reads':
results = sorted(results,
key=itemgetter('reads'),
reverse=request.args['direction'] == 'asc')
elif request.args['sortBy'] == 'popularity':
results = sorted(results,
key=itemgetter('popularity'),
reverse=request.args['direction'] == 'asc')
elif request.args['sortBy'] == 'likes':
results = sorted(results,
key=itemgetter('likes'),
reverse=request.args['direction'] == 'asc')
return jsonify({'posts': results}), 200
VALID_SORT_BYS = {
"id": True,
"reads": True,
"popularity": True,
"likes": True
}
# Sorting logic in process_posts() always sorts in ascending order.
# So the boolean values correspond to whether we should reverse it or not.
VALID_DIRECTIONS = {
"desc": True,
"asc": False
}
if __name__ == '__main__':
app.run()
<file_sep>/frontend/src/components/NewTag.js
import React, { useState, useContext } from "react";
import Context from "../Context";
import "./NewTag.css";
const NewTag = ({ id, addTags }) => {
const [tag, setTag] = useState("");
const { addTag } = useContext(Context);
const submit = evt => {
evt.preventDefault();
addTag(id, tag);
addTags(tag);
};
return (
<form onSubmit={submit} className="tag-form">
<input
type="text"
placeholder="Add a tag"
onChange={evt => setTag(evt.target.value)}
name="tag"
value={tag}
/>
</form>
);
};
export default NewTag;
<file_sep>/frontend/src/components/Search.js
import React, { Component } from "react";
import "./Search.css";
class Search extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
tag: ""
}
this.handleTagChange = this.handleTagChange.bind(this);
this.handleNameChange = this.handleNameChange.bind(this);
}
handleNameChange = (evt) => {
this.setState({
name: evt.target.value
})
this.props.handleNameSearch(evt);
}
handleTagChange = (evt) => {
this.setState({
tag: evt.target.value
});
this.props.handleTagSearch(evt);
}
render() {
return (
<React.Fragment>
<form className="searchForm">
<input
id="name-input"
name="name"
autoComplete="off"
value={this.state.name}
placeholder="Search by name"
onChange={this.handleNameChange} />
<input
id="tag-input"
name="tag"
value={this.state.tag}
placeholder="Search by tag"
onChange={this.handleTagChange} />
</form>
</React.Fragment>
);
}
}
export default Search; | 66b176e528f1a0fa896be81ba058f09b33ff8f9e | [
"Markdown",
"Python",
"JavaScript"
] | 7 | Python | hatchways/team-strawberry | b57ce988836af081ba7b9e6a4169dcacf5b62546 | bc4b52cda4896c52f991885f0f3314352633ab87 |
refs/heads/main | <repo_name>greenundy/zealanders<file_sep>/src/main.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import App from './App.vue'
import language from './language';
Vue.config.productionTip = false;
Vue.use(VueI18n);
const i18n = new VueI18n({
locale: 'en',
fallbackLocale: 'en',
messages: language,
});
new Vue({
i18n,
render: h => h(App)
}).$mount('#app')
<file_sep>/src/i18n.js
/**
* Created by <NAME> on 22/04/18.
*/
const i18n = new VueI18n({
locale: 'ja', // set locale
messages, // set locale messages
});
export default i18n;<file_sep>/src/Tween.js
/**
* Created by <NAME> on 15/05/18.
*/
import TWEEN from '@tweenjs/tween.js';
function animate(time) {
requestAnimationFrame(animate);
TWEEN.update(time);
}
requestAnimationFrame(animate);
export default TWEEN; | 9420aa0a69b32ec424becf8f8cc8f734fe91d045 | [
"JavaScript"
] | 3 | JavaScript | greenundy/zealanders | 595b9650c5b3dc4a7e4bfcc3c26e9b6191b1c916 | 0d68b8a1a6acd737bcdcb440e721ea17303b61dc |
refs/heads/master | <repo_name>magsilva/dccview<file_sep>/dccview.c
#include <kudzu/kudzu.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* To compile it type:
* gcc monitor_detect.c -o monitor_detect.out -lkudzu -lpci -static
*/
#define MODE_SIZE 32
int main () {
int i=0;
struct ddcDevice *monitor = NULL;
struct device **hw;
char *buf = NULL;
initializeDeviceList();
printf ("Detecting your monitor...\n");
hw = probeDevices(CLASS_MONITOR, BUS_DDC, PROBE_ONE);
if (hw == NULL || ((monitor = *(struct ddcDevice**)hw) == NULL &&
(monitor = (struct ddcDevice*)ddcProbe(CLASS_MONITOR,
PROBE_ONE, NULL)) == NULL)) {
printf("No DDC capable monitor detected!\n");
return -1;
}
if ((monitor->horizSyncMin == 0) || (monitor->horizSyncMax == 0) || (monitor->vertRefreshMin == 0) || (monitor->vertRefreshMax == 0)) {
printf("No DDC capable monitor detected!!!!\nhorizSyncMin = %d \nhorizSyncMax = %d \nvertRefreshMin = %d \nvertRefreshMax = %d \n",
monitor->horizSyncMin, monitor->horizSyncMax, monitor->vertRefreshMin, monitor->vertRefreshMax);
return -1;
}
printf("Monitor id: %s\n HSync: %d - %d\n VRefresh: %d - %d\n",
monitor->id, monitor->horizSyncMin, monitor->horizSyncMax, monitor->vertRefreshMin, monitor->vertRefreshMax);
printf("Begin if 'Monitor modes':\n'");
for (i = 0; monitor->modes[i]; i += 2) {
if (i) {
printf(" ");
}
printf("%dx%d", monitor->modes[i], monitor->modes[i + 1]);
buf = (char *)realloc( buf, 1 + ( i / 2 ) * MODE_SIZE );
}
printf("'\n");
printf("End of 'Monitor modes'.\n");
printf("Contents of buf array:\n");
sprintf(buf, "%s (", monitor->id);
for (i = 0; monitor->modes[i]; i += 2) {
if (i) {
strcat(buf, " ");
}
sprintf(buf + strlen(buf), "%dx%d",
monitor->modes[i], monitor->modes[i + 1]);
printf("DEBUG buf = '%s'\n", buf);
}
strcat(buf, ")");
printf("buf array = '%s'\n", buf);
printf("buf size = '%d'\n", strlen(buf)+1);
return 0;
}
<file_sep>/Makefile
CC= gcc
LIBS= -lkudzu -lpci
CFLAGS= -static
all:
$(CC) dccview.c $(LIBS) $(CFLAGS) -o dccview
| 2dd6a6920df91de959caeb17dbe4e2b37e2e257e | [
"C",
"Makefile"
] | 2 | C | magsilva/dccview | 6e4a66fdfcf817e37edcb6e817d1dc4ef420cbbf | 32824d4db709180795f431868ea0f30442213ab3 |
refs/heads/master | <file_sep>//
// SoundGameScene.swift
// NadiaSule-App
//
// Created by <NAME> on 4/12/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import SpriteKit
class SoundGameScene: SKScene {
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPoint(x: 0.5, y: 0.5)
let background = SKSpriteNode(imageNamed: "GameSelection-background.jpg")
background.size = size;
addChild(background)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>//
// SelectScene.swift
// NadiaSule-App
//
// Created by <NAME> on 4/12/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import SpriteKit
class SelectScene: SKScene {
var matchingButton: SKSpriteNode!
var soundButton: SKSpriteNode!
var matchingGameScene: MatchingGameScene!
var soundGameScene: SoundGameScene!
var gameType: String? = nil
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPoint(x: 0.5, y: 0.5)
let background = SKSpriteNode(imageNamed: "SelectionPage")
background.size = size;
addChild(background)
}
override func didMoveToView(view: SKView) {
addButtons()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addButtons() {
matchingButton = SKSpriteNode(imageNamed: "Matching-button")
soundButton = SKSpriteNode(imageNamed: "Music-button")
matchingButton.position = CGPoint(x: matchingButton.position.x - frame.width * 0.25, y: matchingButton.position.y + 20)
matchingButton.size = CGSize(width: 200, height: 70)
soundButton.position = CGPoint(x: soundButton.position.x + frame.width * 0.25, y: soundButton.position.y + 20)
soundButton.size = CGSize(width: 200, height: 70)
addChild(matchingButton)
addChild(soundButton)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if matchingButton.containsPoint(location) {
}
if soundButton.containsPoint(location) {
}
}
}
}
<file_sep>//
// GameViewController.swift
// NadiaSule-App
//
// Created by <NAME> on 4/8/16.
// Copyright (c) 2016 <NAME>. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
var gameScene: SKScene!
var skView: SKView!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.changeScene(_:)), name: "ChangedScene", object: nil)
skView = self.view as! SKView
gameScene = IntroScene(size: skView.bounds.size)
gameScene.scaleMode = .ResizeFill
skView.presentScene(gameScene)
}
func changeScene(notification: NSNotification) {
let message = notification.userInfo!["sceneName"] as! String
let gameType = notification.userInfo!["GameType"] as! String
let transition = SKTransition.revealWithDirection(.Left, duration: 1.0)
if message == "SelectScene" {
gameScene = SelectScene(size: skView.bounds.size)
gameScene.scaleMode = .ResizeFill
skView.presentScene(gameScene, transition: transition)
}
if message == "MatchingGameScene" {
gameScene = MatchingGameScene(size: skView.bounds.size)
gameScene.scaleMode = .ResizeFill
skView.presentScene(gameScene, transition: transition)
}
if message == "SoundGameScene" {
gameScene = SoundGameScene(size: skView.bounds.size)
gameScene.scaleMode = .ResizeFill
skView.presentScene(gameScene, transition: transition)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
<file_sep>//
// OptionButton.swift
// NadiaSule-App
//
// Created by <NAME> on 4/20/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import SpriteKit
class OptionButton: SKSpriteNode {
var OptionType: String? = nil
}
<file_sep>//
// MatchingGameScene.swift
// NadiaSule-App
//
// Created by <NAME> on 4/12/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import SpriteKit
import Foundation
class MatchingGameScene: SKScene {
let options: [String] = ["colors", "body-parts", "number", "categories", "shapes", "action-verbs", "alphabet", "animals"]
var optionButtons: [OptionButton?] = []
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPoint(x: 0.5, y: 0.5)
let background = SKSpriteNode(imageNamed: "GameSelection-background.jpg")
background.size = size;
addChild(background)
}
override func didMoveToView(view: SKView) {
addOptions()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addOptions() {
var x: CGFloat = 0
var y: CGFloat = 0
var optionButton: OptionButton? = nil
for i in 0..<options.count {
optionButton = OptionButton(imageNamed: options[i] + "-select")
optionButton?.xScale = (optionButton?.xScale)! * 0.5
optionButton?.yScale = (optionButton?.yScale)! * 0.5
optionButton?.OptionType = options[i]
if i % 2 == 0 {
x = -256
} else {
x = 256
}
let decre = (80 - floor(Double(i)/2) * 20)/100
y = frame.width * CGFloat(decre) - (frame.width/2)
optionButton!.position = CGPoint(x: x,y: y)
optionButtons.append(optionButton)
addChild(optionButton!)
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
for button in optionButtons {
if let optionB = button {
if optionB.containsPoint(location) {
NSNotificationCenter.defaultCenter().postNotificationName("ChangedScene", object: nil, userInfo: ["sceneName": "SelectScene", "GameType": optionB.OptionType!])
}
}
}
}
}
}
<file_sep>//
// IntroScene.swift
// NadiaSule-App
//
// Created by <NAME> on 4/11/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import SpriteKit
import UIKit
class IntroScene: SKScene {
var playButton: SKSpriteNode!
var selectScene: SelectScene!
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPoint(x: 0.5, y: 0.5)
let background = SKSpriteNode(imageNamed: "IntroPageBackground")
background.size = size;
addChild(background)
}
override func didMoveToView(view: SKView) {
playButton = SKSpriteNode(imageNamed: "play")
addChild(playButton)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if playButton.containsPoint(location) {
NSNotificationCenter.defaultCenter().postNotificationName("ChangedScene", object: nil, userInfo: ["sceneName": "MatchingGameScene"])
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | b93c9c2e949b73c159b9c3d354d4754214d12449 | [
"Swift"
] | 6 | Swift | bboyjacks/NadiaSule-App | a016f984108117f2ac2b8e0e7898f24f6fd8a939 | 11b119e1460548df53ce925f0c2fe2d018e51bec |
refs/heads/master | <repo_name>Salvador-Rdz/Act3-Swift<file_sep>/busqueda-v3.swift
import Foundation
class FetchClass
{
//Variables
var vector: [Int] = []
//Functions
func fetch(item: Int)->Int //Swift cannot have truly abstract classes
{
preconditionFailure("This method must be overridden")
}
func setV(v: [Int]) //Fills this class's vector with a predefined vector
{
self.vector = v
}
func setV(n:Int)->[Int] //Fills this class's vector with random numbers, receives the desired size of the array
{
var v:[Int] = [Int]()
for _ in 0...(n-1)
{ //Using a linux platform
v.append(random() % 100) //uses random, should be arc_random4() if on mac
}
return v
}
func getV()->[Int] //Returns this class's vector.
{
return self.vector
}
func showV() //Prints all of the values in the array.
{
let n:Int = self.vector.count-1
var string = "Los valores del arreglo son: "
for(index) in 0...n
{
string+=String(self.vector[index])
string+=","
}
print(string)
}
func showF(n: Int) //Prints the position where the item to find is located.
{
if(n==(-1))
{
print("El valor no se encuentra en el vector")
}
else
{
print("El valor se encuentra en la posición \(n)")
}
}
}
//Searches for a value in a vector using a binary type search
class binary: FetchClass, order
{
override func fetch(item: Int) -> Int
{
selection()
var inicio: Int = 0
var fin: Int = self.vector.count-1
var centro: Int = (inicio+fin)/2
//While the starting value of the setup is lower than the final position of the vector
while(inicio < fin)
{
let valorCentro:Int = self.vector[centro] //Gets the current value of the center of the vector
if(valorCentro == item)
{
return centro //Returns the position where the value was found
}
else
{
if(item < valorCentro)
{
fin = centro
centro = (inicio + fin)/2
}
else
{
inicio = centro;
centro = (inicio + fin)/2;
}
}
}
return -1
}
func selection () //Sorts the values in an array using the selection algorithm
{
var vector : [Int]=self.vector
for i in 0...vector.count-1
{
var m :Int = i;
for (j) in 1...vector.count-1
{
if(vector[j]<vector[m]) //checks if the lowest index is equal to the next index
{
m = j;
}
}
//updates the array values
swap(p1:i,p2:m)
}
self.vector = vector
}
func insertion() //Sorts the values in an array using the insertion algorithm
{
var vector : [Int]=self.vector
var tmp : Int
var j : Int = 0
var count : Int
for i in 1...vector.count-1
{
count = i
tmp=vector[i]
count=count-1
while(j>=0 && vector[j]>tmp) //moves throughout the index backwards while checking if the current value is higher than the vector of reference
{
vector[j+1]=vector[j] //Swaps the values on the left with the ones on the right
j=j-1
}
vector[j+1]=tmp
}
self.vector = vector
}
func bubble () //Sorts the values in an array using the bubble algorithm
{
var vector : [Int]=self.vector
//Moves throughout the array
for i in 0...vector.count-1
{
for j in 0...vector.count-i-1
{
if(vector[j+1]<vector[j]) //checks if the next value is smaller than the current value
{
swap(p1:j+1,p2:j) //Uses a predefined function to swap out values
}
}
}
self.vector = vector
}
func mergeSort (inicio:Int, fin:Int) //Sorts the values in an array using the mergeSort algorithm
{
var vector : [Int] = self.vector
if(fin-inicio == 0 || fin - inicio == 1) //if the current evaluated list is of size 0 or 1, it means its already sorted.
{
}
else
{
let pivot: Int = (inicio+fin)/2
mergeSort(inicio:inicio, fin:pivot)
mergeSort(inicio:pivot, fin:fin)
let p1: Int = inicio
let p2: Int = pivot
let p3: Int = 0
//an auxiliary array is created to save the in-order lists.
var auxList : [Int] = []
for i in 0...(fin-inicio) //Rudimentary, but is setup to create a specific sized array
{
auxList.append(0)
}
while(p1<pivot || p2<fin)
{
if(p1<pivot && p2<fin)
{
if(vector[p3+1]<vector[p2+1])
{
auxList[p3+1]=vector[p1+1] //In case they're smaller, they're swapped.
}
else
{
auxList[p3+1]=vector[p2+1]
}
}
else if (p1<pivot)
{
auxList[p3+1]=(auxList[p1])
}
else
{
auxList[p3+1] = auxList[p2+1]
}
}
}
self.vector = vector
}
func quickSort (inicio:Int, fin:Int) //Sorts the values in an array using the quicksort algorithm
{
var vector : [Int] = self.vector
var i: Int = inicio
var j: Int = fin
let pivot = vector[inicio]
while(i<=j) //while the start and end don't cross
{
//Moves throughout the vector comparing the values with the pivot, moving one by one, forwards or backwards
while(vector[i]<=pivot && i<j)
{
i=i+1
}
while(vector[j]>pivot)
{
j=j-1
}
if(i<j)
{
swap(p1:j,p2:i) //Uses the swap function to exchange the values
i=i+1
j=j-1
}
}
//
vector[inicio] = vector [j]
vector [j] = pivot
//Uses recursivity to sort all of the values set by set
if(inicio<j-1)
{
quickSort(inicio:inicio, fin:j-1)
}
if(i<fin)
{
quickSort(inicio:j+1, fin:fin)
}
self.vector = vector
}
func swap(p1:Int, p2:Int) //Utility function to swap two spaces between arrays
{
let tmp = self.vector[p1]
self.vector[p1] = self.vector[p2]
self.vector[p2]=tmp
}
}
//Searches for a value in a vector using a secuential type search
class secuential: FetchClass
{
override func fetch(item: Int) -> Int {
let n:Int = self.vector.count-1
for i in 0...n
{
if(self.vector[i] == item)
{
return i
}
}
return -1
}
}
protocol order //Protocol resembles Interfaces in java, implemented by the binary class
{
func selection ()
func bubble()
func insertion()
func mergeSort(inicio:Int, fin:Int)
func quickSort(inicio:Int, fin:Int)
}
//main
var vector: [Int] = [3,4,5,8,15,26,37,58,49] //predefined values for testing purposes
//Testing "secuential" class
print("Testing the secuential class")
var sec: secuential = secuential()
sec.setV(v: sec.setV(n: 50))
sec.showV()
print("Searching for 3")
sec.showF(n: sec.fetch(item: 3))
print("Testing the binary class")
//Testing "binary" class
var bin: binary = binary()
print ("Searching for 5")
bin.setV(v: vector)
//bin.setV(10); //A random array can be generated by inputting an array size instead of a predefined vector.
//Test ordering methods to order the array
/*
bin.selection();
bin.bubble();
bin.insertion();
bin.mergeSort(inicio:0, fin:bin.vector.count-1);
bin.quickSort(inicio:0, fin:bin.vector.count-1);
*/
bin.showV()
bin.showF(n: bin.fetch(item:5))<file_sep>/busqueda.swift
import Foundation
class FetchClass
{
//Variables
var vector: [Int] = []
//Functions
func fetch(item: Int)->Int //Swift cannot have truly abstract classes
{
preconditionFailure("This method must be overridden")
}
func setV(v: [Int]) //Fills this class's vector with a predefined vector
{
self.vector = v
}
func setV(n:Int)->[Int] //Fills this class's vector with random numbers, receives the desired size of the array
{
var v:[Int] = [Int]()
for _ in 0...(n-1)
{
v.append(random() % 100)
}
return v
}
func getV()->[Int] //Returns this class's vector.
{
return self.vector
}
func showV() //Prints all of the values in the array.
{
let n:Int = self.vector.count-1
var string = "Los valores del arreglo son: "
for(index) in 0...n
{
string+=String(self.vector[index])
string+=","
}
print(string)
}
func showF(n: Int) //Prints the position where the item to find is located.
{
if(n==(-1))
{
print("El valor no se encuentra en el vector")
}
else
{
print("El valor se encuentra en la posición \(n)")
}
}
}
//Searches for a value in a vector using a binary type search
class binary: FetchClass
{
override func fetch(item: Int) -> Int {
var inicio: Int = 0
var fin: Int = self.vector.count-1
var centro: Int = (inicio+fin)/2
//While the starting value of the setup is lower than the final position of the vector
while(inicio < fin)
{
var valorCentro:Int = self.vector[centro] //Gets the current value of the center of the vector
if(valorCentro == item)
{
return centro //Returns the position where the value was found
}
else
{
if(item < valorCentro)
{
fin = centro
centro = (inicio + fin)/2
}
else
{
inicio = centro;
centro = (inicio + fin)/2;
}
}
}
return -1
}
}
//Searches for a value in a vector using a secuential type search
class secuential: FetchClass
{
override func fetch(item: Int) -> Int {
let n:Int = self.vector.count-1
for i in 0...n
{
if(self.vector[i] == item)
{
return i
}
}
return -1
}
}
//main
var vector: [Int] = [1,2,3,4,5,6,7,8,9]
//Testing "secuential" class
var sec: secuential = secuential()
sec.setV(v: sec.setV(n: 50))
sec.showV()
sec.showF(n: sec.fetch(item: 3))
//Testing "binary" class
var bin: binary = binary()
bin.setV(v: vector)
bin.showV()
bin.showF(n: bin.fetch(item:3))<file_sep>/busqueda2-0.swift
import Foundation
class FetchClass
{
//Variables
var vector: [Int] = []
//Functions
func fetch(item: Int)->Int //Swift cannot have truly abstract classes
{
preconditionFailure("This method must be overridden")
}
func setV(v: [Int]) //Fills this class's vector with a predefined vector
{
self.vector = v
}
func setV(n:Int)->[Int] //Fills this class's vector with random numbers, receives the desired size of the array
{
var v:[Int] = [Int]()
for _ in 0...(n-1)
{ //Using a linux platform
v.append(random() % 100) //uses random, should be arc_random4() if on mac
}
return v
}
func getV()->[Int] //Returns this class's vector.
{
return self.vector
}
func showV() //Prints all of the values in the array.
{
let n:Int = self.vector.count-1
var string = "Los valores del arreglo son: "
for(index) in 0...n
{
string+=String(self.vector[index])
string+=","
}
print(string)
}
func showF(n: Int) //Prints the position where the item to find is located.
{
if(n==(-1))
{
print("El valor no se encuentra en el vector")
}
else
{
print("El valor se encuentra en la posición \(n)")
}
}
}
//Searches for a value in a vector using a binary type search
class binary: FetchClass, order
{
override func fetch(item: Int) -> Int {
var inicio: Int = 0
var fin: Int = self.vector.count-1
var centro: Int = (inicio+fin)/2
//While the starting value of the setup is lower than the final position of the vector
while(inicio < fin)
{
let valorCentro:Int = self.vector[centro] //Gets the current value of the center of the vector
if(valorCentro == item)
{
return centro //Returns the position where the value was found
}
else
{
if(item < valorCentro)
{
fin = centro
centro = (inicio + fin)/2
}
else
{
inicio = centro;
centro = (inicio + fin)/2;
}
}
}
return -1
}
func selection (v: [Int]) ->[Int]
{
var vector : [Int] = v
var aux : Int
for i in 0...vector.count-1
{
var m :Int = i;
for (j) in 1...vector.count-1
{
if(vector[j]<vector[m])
{
m = j;
}
}
aux = vector [i]
vector [i] = vector [m]
vector [m] = aux
}
return vector
}
}
//Searches for a value in a vector using a secuential type search
class secuential: FetchClass
{
override func fetch(item: Int) -> Int {
let n:Int = self.vector.count-1
for i in 0...n
{
if(self.vector[i] == item)
{
return i
}
}
return -1
}
}
protocol order //Protocol resembles Interfaces in java
{
func selection (v : [Int]) -> [Int]
}
//main
var vector: [Int] = [3,4,5,8,15,26,37,58,49] //predefined values for testing purposes
//Testing "secuential" class
print("Testing the secuential class")
var sec: secuential = secuential()
sec.setV(v: sec.setV(n: 50))
sec.showV()
print("Searching for 3")
sec.showF(n: sec.fetch(item: 3))
print("Testing the binary class")
//Testing "binary" class
var bin: binary = binary()
print ("Searching for 5")
bin.setV(v: vector)
bin.showV()
bin.showF(n: bin.fetch(item:5)) | 98b091b2a68ae60969df7012b041349f243339b1 | [
"Swift"
] | 3 | Swift | Salvador-Rdz/Act3-Swift | 2158837735e58cf0a17c7afbf66e0a9c177fdfd6 | 1807147fbebe6c7c8292e273d220525a06f0913a |
refs/heads/master | <repo_name>aclayton/aaronc.ca<file_sep>/src/anime.js
import anime from 'anime'
const install = (Vue) => {
Vue.prototype.$anime = anime
}
export default install
<file_sep>/src/projects.js
projects: [
{
_id: 1,
name: 'svg-machine.com',
imgMain: '/img/svg-machine.png',
descShort: '',
descLong: '',
githubLink: '',
projectLink: '',
insideLink: 'projects/svg-machine'
},
{
_id: 2,
name: '<NAME>'
},
{
_id: 3,
name: 'Nia Data Exchange'
}
]
| fb75e216075415f8917764e739bcc8fa139b597e | [
"JavaScript"
] | 2 | JavaScript | aclayton/aaronc.ca | 91112d7d7bd687f5e728d3449e113f9f58e117e0 | c824846d870ce1b7a9442d4fc6ce85ec41d948f4 |
refs/heads/master | <file_sep>{% extends 'base.html' %}
{% block title %}Update Task{% endblock %}
{% block content %}
<h1>Update Task</h1>
<form method="POST" action="{% url 'edit' task.pk %}">
{% include 'task_form.html' with button_text="Update" %}
</form>
<a href="{% url 'task_view' task.pk %}" class="btn btn-outline-success btn-block">View</a>
{% endblock %}
<file_sep>from django.db import models
STATUS_LS_CHOICES = [
('Have to do', 'have_to_do'),
('In process', 'in_process'),
('Done', 'done')
]
class Tasks(models.Model):
title = models.TextField(max_length=3500, null=False, blank=False, verbose_name='Title')
description = models.TextField(max_length=3500, null=True, blank=True, verbose_name='Description')
status = models.TextField(max_length=50, null=False, blank=False, choices=STATUS_LS_CHOICES, default='have_to_do', verbose_name='Status')
created_at = models.DateField(auto_now=False, null=True, blank=True, verbose_name='Date of done')
<file_sep>from django.shortcuts import render, get_object_or_404, redirect
from django.shortcuts import render
from webapp.forms import TaskForm
from webapp.models import Tasks
def index_view(request, *args, **kwargs):
to_do_ls = Tasks.objects.all()
return render(request, 'index.html', context={
'tasks': to_do_ls
})
def task_view(request, pk):
task = get_object_or_404(Tasks, pk=pk)
return render(request, 'task.html', context={
'task': task
})
def task_create_view(request, *args, **kwargs):
if request.method == 'GET':
form = TaskForm()
print('create')
print(form)
return render(request, 'create.html', context={'form': form})
elif request.method == 'POST':
form = TaskForm(data=request.POST)
if form.is_valid():
task = Tasks.objects.create(
title=form.cleaned_data['title'],
status=form.cleaned_data['status'],
description=form.cleaned_data['description'],
created_at=form.cleaned_data['created_at']
)
return redirect('task_view', pk=task.pk)
else:
return render(request, 'create.html', context={'form': form})
def task_edit_view(request, pk):
task = get_object_or_404(Tasks, pk=pk)
if request.method == 'GET':
form = TaskForm()
return render(request, 'update.html', context={'task': task,'form': form})
elif request.method == 'POST':
form = TaskForm(data=request.POST)
if form.is_valid():
task.title = request.POST.get('title')
task.status = request.POST.get('status')
task.description = request.POST.get('description')
task.created_at = request.POST.get('created_at')
task.save()
return redirect('task_view', pk=task.pk)
else:
return render(request, 'update.html', context={'task': task, 'form': form})
return redirect('task_view', pk=task.pk)
def task_delete_view(request, pk):
task = get_object_or_404(Tasks, pk=pk)
if request.method == 'GET':
return render(request, 'delete.html', context={'task': task})
elif request.method == 'POST':
task.delete()
return redirect('index')<file_sep>from django import forms
from django.forms import widgets
from webapp.models import STATUS_LS_CHOICES as list
class TaskForm(forms.Form):
title = forms.CharField(max_length=200, required=True, label='Title')
status = forms.ChoiceField(choices=list, required=False, label='Status')
description = forms.CharField(max_length=3000, required=True, label='Description', widget=widgets.Textarea)
created_at = forms.DateField(label='Date', initial=None, required=False, widget=widgets.DateInput(attrs={'type': 'date'}))
<file_sep># Generated by Django 2.2.5 on 2019-09-11 06:24
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Tasks',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.TextField(max_length=3500, verbose_name='Title')),
('description', models.TextField(blank=True, max_length=3500, null=True, verbose_name='Description')),
('status', models.TextField(choices=[('Have to do', 'have_to_do'), ('In process', 'in_process'), ('Done', 'done')], default='have_to_do', max_length=50, verbose_name='Status')),
('created_at', models.DateField(blank=True, null=True, verbose_name='Date of done')),
],
),
]
| 431e6311b1873acd0d3c78a9aced743f27c44908 | [
"Python",
"HTML"
] | 5 | HTML | coffee3333/Task_list | ccb86c7afb8306a17075949a183c8ed92fd80a18 | 8d1842f71c56700e975db0f2f84631d957d949fd |
refs/heads/master | <repo_name>whyzdev/mobybuild-image<file_sep>/Dockerfile
FROM ubuntu
MAINTAINER <EMAIL>
LABEL Description="This image is used to build moby" Vendor="Docker Inc." Version="1.0"
#add docker apt repo
RUN apt-get update && apt-get install -y apt-transport-https ca-certificates \
&& apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys <KEY> \
&& echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main" > /etc/apt/sources.list.d/docker.list \
&& rm -rf /var/lib/apt/lists/*
#install dependencies
RUN apt-get update && apt-get install -y \
docker-engine \
git \
curl \
make \
&& rm -rf /var/lib/apt/lists/*
#set default branch to build
ENV branch master
#define the output directory (pinata root)
VOLUME /output
#ssh keys to clone moby (will be copied in /root/.ssh changing access rights to make samba share working)
VOLUME /sshkeys
#share docker cache
VOLUME /var/lib/docker
#script to execute on run
COPY Execute.sh /
RUN chmod 777 /Execute.sh
CMD /Execute.sh
<file_sep>/README.md
# mobybuild-image
Build docker image to build moby on windows (ebriney/mobybuild)
<file_sep>/Execute.sh
cd ~
service docker start
cp -a /sshkeys /root/.ssh
cd /root/.ssh && ls | grep -v '\.pub$' | xargs chmod 700
git clone <EMAIL>:docker/moby.git
cd moby
git checkout $branch
make
cp -a ./alpine/initrd.img.gz /output/v1/moby/initrd.img
cp -a ./alpine/mobylinux-efi.iso /output/win/src/Resources/mobylinux.iso
cp -a ./alpine/kernel/vmlinuz64 /output/v1/moby/vmlinuz64
git rev-parse HEAD > /output/v1/moby/COMMIT
| 28610f2e577edfab6fa1e3fdf0453b947948fcac | [
"Markdown",
"Dockerfile",
"Shell"
] | 3 | Dockerfile | whyzdev/mobybuild-image | 999cfd50dd65445582d8926d8968b62f46c935c0 | 834c8d779794e6408849ff0a718e866271a6b3c6 |
refs/heads/master | <repo_name>erBhushanPawar/sync-async-redux-store-example<file_sep>/src/global-store/async.store.js
import { createStore, applyMiddleware } from "redux";
import logger from "redux-logger";
import { default as thunk } from "redux-thunk";
const middleware = applyMiddleware(thunk, logger);
const reducer = (state = {}, action) => {
switch (action.type) {
case "FETCH":
console.log("Fetch");
break;
case "FETCHING":
console.log("Fetching");
break;
case "FETCHED":
console.log("Fetched");
break;
default:
break;
}
return state;
};
const astore = createStore(reducer, {}, middleware);
astore.dispatch(dispatch => {
dispatch({ type: "FETCH" });
dispatch({ type: "FETCHING" });
dispatch({ type: "FETCHED" });
});
export default astore;
| 98e07fc9d541c0a30ed9d50863a31ed46f7868f6 | [
"JavaScript"
] | 1 | JavaScript | erBhushanPawar/sync-async-redux-store-example | dbaf457ec8d9e3a18a714a7165efefb71f4c7a91 | f4ab651d1e5cba3fe3488ae5e069ba18bdc095ad |
refs/heads/master | <file_sep>{% extends "postproduccion/section-info-produccion.html" %}
{% block current-resumen %} disabled {% endblock %}
{% block section-content %}
<div class="box-body">
<div class="row">
{% if v.status != "INC" and v.status != "DEF" and v.status != "PRV" %}
<div class="col-md-2"></div>
<div class="col-md-7">
<video width="480" height="270" controls>
<source src="{% url 'stream_video' v.id %}" type="video/mp4">
Your browser does not support HTML5 video.
</video>
</div>
<div class="col-md-3"></div>
{% else %}
<div class="alert alert-warning alert-dismissible">
<h4>
<i class="icon fa fa-warning"></i>
¡Alerta!
</h4>
Previsualización no disponible, revise el <a href="{% url 'enproceso' %}">listado de producciones en proceso</a>
</div>
{% endif %}
</div>
<div style="padding:10px;"> </div>
<div class="row">
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Información básica de la producción</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<div class="table-responsive">
<table class="table no-margin">
<thead>
<th>Autor</th>
<th>Fecha</th>
<th>Operador</th>
<th>Título</th>
<th>Observación</th>
<th>OA</th>
</thead>
<tbody>
<tr>
<td>{{ v.autor }}<br/>(<a href="mailto:{{v.email}}">{{ v.email }}</a>)</td>
<td>
{{ v.informeproduccion.fecha_grabacion|date:"G:i:s - d/m/Y" }} - Grabación
<br>{{ v.informeproduccion.fecha_produccion|date:"G:i:s - d/m/Y" }} - Producción
{% if v.informeproduccion.fecha_validacion %}
<br>{{ v.informeproduccion.fecha_validacion|date:"G:i:s - d/m/Y" }} - Validación
{% endif%}
</td>
<td>{{ v.informeproduccion.operador }}</td>
<td>{{ v.titulo }}</td>
<td>{{ v.informeproduccion.observacion }}</td>
<td><i class="icon {{ v.objecto_aprendizaje|yesno:'fa fa-check,fa fa-ban' }}" style="{{ v.objecto_aprendizaje|yesno:'color:green,color:red'}}"></i></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Histórico de incidencias</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
{% if v.informeproduccion.incidenciaproduccion_set.all %}
<div class="table-responsive">
<table class="table no-margin">
<thead>
<th>Emisor</th>
<th>Fecha</th>
<th>Aceptado</th>
<th>Comentario</th>
</thead>
<tbody>
{% for inci in v.informeproduccion.incidenciaproduccion_set.all|dictsort:"fecha" %}
<tr>
<td>{% if inci.emisor %}{{ inci.emisor }}{% else %}{{ v.autor }}{% endif %}</td>
<td>{{ inci.fecha|date:"G:i:s - d/m/Y" }}</td>
<td><i class="icon {% if not inci.emisor %}{{ inci.aceptado|yesno:'fa fa-check,fa fa-ban' }}{% endif %}" style="{% if not inci.emisor %}{{ inci.aceptado|yesno:'color:green,color:red' }}{% endif %}"></i></td>
<td>{% if inci.comentario %}{{ inci.comentario }}{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="alert alert-info alert-dismissible">
<i class="icon fa fa-info"></i>
El histórico de incidencias esta vacío.
</div>
{% endif%}
</div>
</div>
</div>
{% if v.registropublicacion_set.all %}
<div class="row">
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Histórico de publicación</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<div class="table-responsive">
<table class="table no-margin">
<thead>
<th>Acciones</th>
<th>Fecha</th>
<th>Enlace</th>
</thead>
<tbody>
{% for pub in v.registropublicacion_set.all %}
<!-- Dialogo notificar -->
<div class="modal modal-warning fade" id="dialogNotificar{{pub.id}}" tabindex="-1" role="dialog" aria-labelledby="labelNotificar{{pub.id}}">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="labelNotificar{{pub.id}}">¿Notificar publicación de la producción?</h4>
</div>
<div class="modal-body">
Pulse en notificar para enviar un mensaje al autor de la producción que esta ha sido publicada.
</div>
<div class="modal-footer">
<a type="button" href="{% url 'notificar_publicacion' pub.id %}" class="btn btn-outline pull-left">Notificar</a>
<button type="button" class="btn btn-outline" data-dismiss="modal">Cancelar</button>
</div>
</div>
</div>
</div>
<!-- Dialogo borrar -->
<div class="modal modal-warning fade" id="dialogBorrar{{pub.id}}" tabindex="-1" role="dialog" aria-labelledby="labelBorrar{{pub.id}}">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="labelBorrar{{pub.id}}">¿Borrar entrada del histórico de publicación?</h4>
</div>
<div class="modal-body">
Pulse en borrar para eliminar la entrada del histórico de publicación de la producción.
</div>
<div class="modal-footer">
<a type="button" class="btn btn-outline pull-left" href="{% url 'borrar_registro' pub.id %}">Borrar</a>
<button type="button" class="btn btn-outline" data-dismiss="modal">Cancelar</button>
</div>
</div>
</div>
</div>
<tr>
<td>
<button class="btn btn-block btn-warning btn-sm" data-toggle="modal" data-target="#dialogNotificar{{pub.id}}">
<i class="icon fa fa-warning"></i>
Notificar
</button>
<button class="btn btn-block btn-warning btn-sm" data-toggle="modal" data-target="#dialogBorrar{{pub.id}}">
<i class="icon fa fa-warning"></i>
Borrar
</button>
</td>
<td>
{{ pub.fecha|date:"G:i:s - d/m/Y" }}
</td>
<td>
<i class="icon fa fa-youtube-play" style="color: red;"></i><a class="enlace" href="{{ pub.enlace }}" target="_blank"> {{ pub.enlace }}</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Estadísticas de Youtube</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body" id="stats">
{% for pub in v.registropublicacion_set.all %}
<script>
$(document).ready(function() {
var link = "{{pub.enlace}}";
var video_id = link.replace("https://www.youtube.com/watch?v=", "");
var url = "https://www.googleapis.com/youtube/v3/videos?id="+video_id+"&key=<KEY>&fields=items(statistics)&part=statistics";
$.getJSON(url, function(result){
var text = JSON.stringify(result);
var obj = JSON.parse(text);
var rep = '<div class="progress-group"><span class="progress-text" style="color: #00c0ef;"><i class="icon fa fa-eye"></i> Reproducciones</span><span class="progress-number">'+ obj.items[0].statistics.viewCount+'</span><div class="progress sm"><div class="progress-bar progress-bar-aqua" style="width: 100%"></div></div></div>';
var likes = '<div class="progress-group"><span class="progress-text" style="color: green;"><i class="icon fa fa-thumbs-o-up"></i> Me gusta</span><span class="progress-number">'+ obj.items[0].statistics.likeCount+'</span><div class="progress sm"><div class="progress-bar progress-bar-green" style="width: '+(obj.items[0].statistics.likeCount/obj.items[0].statistics.viewCount)*100+'%"></div></div></div>';
var dislikes = '<div class="progress-group"><span class="progress-text" style="color: orange;"><i class="icon fa fa-thumbs-o-down"></i> No me gusta</span><span class="progress-number">'+ obj.items[0].statistics.dislikeCount+'</span><div class="progress sm"><div class="progress-bar progress-bar-yellow" style="width: '+(obj.items[0].statistics.dislikeCount/obj.items[0].statistics.viewCount)*100+'%"></div></div></div>';
var favorites = '<div class="progress-group"><span class="progress-text" style="color: red;"><i class="icon fa fa-heart"></i> Favoritos</span><span class="progress-number">'+ obj.items[0].statistics.favoriteCount+'</span><div class="progress sm"><div class="progress-bar progress-bar-red" style="width: '+(obj.items[0].statistics.favoriteCount/obj.items[0].statistics.viewCount)*100+'%"></div></div></div>';
var comments = '<div class="progress-group"><span class="progress-text" style="color: #337ab7;"><i class="icon fa fa-commenting-o"></i> Comentarios</span><span class="progress-number">'+ obj.items[0].statistics.commentCount+'</span><div class="progress sm"><div class="progress-bar progress-bar-grey" style="width: '+(obj.items[0].statistics.commentCount/obj.items[0].statistics.viewCount)*100+'%"></div></div></div>';
var html = rep + likes + dislikes + favorites + comments;
$("#stats").append(html);
});
});
</script>
{% endfor %}
</div>
</div>
</div>
{% endif %}
<div class="row">
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Histórico de codificación</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
{% if v.informeproduccion.historicocodificacion_set.all %}
<div class="table-responsive">
<table class="table no-margin">
<thead>
<th>Tipo</th>
<th>Fecha</th>
<th>Estado</th>
</thead>
<tbody>
{% for hist in v.informeproduccion.historicocodificacion_set.all %}
<tr>
<td>{{ hist.get_tipo_display }}</td>
<td>{{ hist.fecha|date:"G:i:s - d/m/Y" }}</td>
<td><i class="icon {{ hist.status|yesno:'fa fa-check,fa fa-ban' }}" style="{{ hist.status|yesno:'color:green,color:red' }}"></i></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="alert alert-warning alert-dismissible">
<h4>
<i class="icon fa fa-warning"></i>
¡Alerta!
</h4>
El histórico de codificación no estará disponible hasta que la producción haya sido validada.<br/><br/><a href="{% url 'cola' %}">Pulse aquí para acceder a la cola de procesamiento del centro de monitorización</a>
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock %}
{% block section-widget2 %}
{% endblock %}
<file_sep># encoding: utf-8
import os
import subprocess
import shlex
from django.conf import settings
from configuracion import config
_cronline = "* * * * * /usr/bin/env python %s" % os.path.join(
settings.BASE_DIR,
'manage.py'
)
def _get_crontab():
"""
Devuelve una lista donde cada elemento es una línea
de crontab actual (puede contener comentarios).
"""
command = "%s -l" % config.get_option('CRONTAB_PATH')
return subprocess.Popen(
shlex.split(str(command)),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate()[0].strip().split('\n')
def _set_crontab(data):
"""
Fija al crontab las líneas que componen la lista dada.
"""
command = "%s -" % config.get_option('CRONTAB_PATH')
text = '\n'.join(data) + '\n'
subprocess.Popen(
shlex.split(str(command)),
stdin=subprocess.PIPE
).communicate(input=text)
def status(command):
"""
Devuelve si la tarea de procesamiento está activa en el crontab actual.
"""
cronline = "%s %s" % (_cronline, command)
return cronline in _get_crontab()
def stop(command):
"""
Elimina del crontab actual la tarea de procesamiento.
"""
data = _get_crontab()
cronline = "%s %s" % (_cronline, command)
if cronline in data:
data.remove(cronline)
_set_crontab(data)
def start(command):
"""
Añade al crontab actual la tarea de procesamiento.
"""
data = _get_crontab()
cronline = "%s %s" % (_cronline, command)
if cronline not in data:
data.append(cronline)
_set_crontab(data)
<file_sep>{% extends "postproduccion/base-2-1.html" %}
{% block page-title %}Informe de producción{% endblock %}
{% block section-class %} class="informe-video"{% endblock %}
{% block section-title %}<h1>Informe de la producción: {{v.titulo}}</h1>{% endblock %}
{% block section-description %}
<div class="box-body">
<div class="col-md-3">
<a class="btn btn-block btn-primary btn-sm {% block current-resumen %} {% endblock %}" href="{% url 'estado_video' v.id %}">
<i class="icon fa fa-question-circle"></i>
Resumen de producción
</a>
</div>
<div class="col-md-3">
<a class="btn btn-block btn-primary btn-sm {% block current-metadata %}{% endblock %}" href="{% url 'definir_metadatos_oper' v.id %}">
<i class="icon fa fa-clipboard"></i>
Metadata
</a>
</div>
{% if v.status != 'LIS' %}
<div class="col-md-3">
<a class="btn btn-block btn-primary btn-sm {% block current-ticket %} {% endblock %}" href="{% url 'gestion_tickets' v.id %}">
<i class="icon fa fa-exchange"></i>
Gestión de ticket
</a>
</div>
{% endif %}
{% if v.status != 'LIS' %}
<div class="col-md-3">
<a class="btn btn-block btn-primary btn-sm {% block current-editar %} {% endblock %}" href="{% url 'editar' v.id %}">
<i class="icon fa fa-pencil"></i>
Editar
</a>
</div>
{% endif %}
</div>
{% endblock %}
{% block section-widget %}
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Estado actual de la producción</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<div class="btn-block btn-sm" style="background:#00c0ef; color: white; text-align: center;">
{% if pub %}
Publicado
{% else %}
{{ v.get_status_display }}
{% endif %}
</div>
</div>
</div>
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Acciones disponibles</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
{% if not pub and v.status == 'LIS' %}
<a type="button" href="{% url 'publicar' v.id %}" class="btn btn-block btn-success btn-sm">
<i class="icon fa fa-youtube-play"></i>
Publicar producción
</a>
{% endif %}
{% if v.status == 'ACE' or v.status == 'PTO' %}
<button class="btn btn-block btn-warning btn-sm" data-toggle="modal" data-target="#dialogValidar">
<i class="icon fa fa-check"></i>
Validar producción
</button>
{% endif %}
<button class="btn btn-block btn-danger btn-sm" data-toggle="modal" data-target="#dialogEliminar">
<i class="icon fa fa-ban"></i>
Eliminar producción
</button>
{% if v.status != 'LIS' %}
<button class="btn btn-block btn-warning btn-sm" data-toggle="modal" data-target="#dialogReemplazar">
<i class="icon fa fa-repeat"></i>
Reemplazar vídeo
</button>
{% endif %}
{% if v.status != "INC" and v.status != "DEF" and v.status != "PRV" %}
<a type="button" class="btn btn-block btn-default btn-sm" href="{% url 'download_video' v.id %}">
<i class="icon fa fa-link"></i>
Descargar video
</a>
{% endif %}
</div>
</div>
<!-- Dialogo eliminar produccion -->
<div class="modal modal-danger fade" id="dialogEliminar" tabindex="-1" role="dialog" aria-labelledby="labelEliminar">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="labelEliminar">¿Eliminar producción?</h4>
</div>
<div class="modal-body">
La producción será eliminada de forma permanente y no podrá ser recuperada.
</div>
<div class="modal-footer">
<a type="button" href="{% url 'borrar' v.id %}" class="btn btn-outline pull-left">Eliminar</a>
<button type="button" class="btn btn-outline" data-dismiss="modal">Cancelar</button>
</div>
</div>
</div>
</div>
<!-- Dialogo validar produccion -->
<div class="modal modal-warning fade" id="dialogValidar" tabindex="-1" role="dialog" aria-labelledby="labelValidar">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="labelValidar">¿Validar producción?</h4>
</div>
<div class="modal-body">
Revise todos los datos de la producción antes de continuar, este proceso es irreversible.
</div>
<div class="modal-footer">
<a type="button" href="{% url 'validar_produccion' v.id %}" class="btn btn-outline pull-left">Validar producción</a>
<button type="button" class="btn btn-outline" data-dismiss="modal">Cancelar</button>
</div>
</div>
</div>
</div>
<!-- Dialogo validar produccion -->
<div class="modal modal-warning fade" id="dialogReemplazar" tabindex="-1" role="dialog" aria-labelledby="labelReemplazar">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="labelValidar">¿Reemplazar vídeo?</h4>
</div>
<div class="modal-body">
El vídeo actual será sustituido por uno nuevo y no podrá ser recuperado.
</div>
<div class="modal-footer">
<a type="button" href="{% url 'reemplazar_video' v.id %}" class="btn btn-outline pull-left">Reemplazar vídeo</a>
<button type="button" class="btn btn-outline" data-dismiss="modal">Cancelar</button>
</div>
</div>
</div>
</div>
{% block section-widget2 %}{% endblock %}
{% endblock %}
<file_sep>
// Hacer desaparecer los mensajes tipo.
$(document).ready(function() {
$(".cerrar").click(function () {
$(this.parentNode).animate({ opacity: 0, height: 0 }, "slow").hide("slow");
});
$(".alerta-header").click(function () {
$(this).find(".icon").toggleClass("minus").toggleClass("plus");
$(this).parents(".alerta:first").find(".alerta-content").toggle();
});
$(".rechazar").click(function () {
$(this.parentNode.parentNode).find(".form-validacion-opciones").toggle();
$(this.parentNode.parentNode).find(".form-validacion-rechaza").toggle();
});
$(function() {
var dates = $( "#from, #to" ).datepicker({
maxDate: "+0d",
changeMonth: true,
changeYear: true,
numberOfMonths: 3,
onSelect: function( selectedDate ) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datepicker( "option", option, date );
}
});
});
// Dialog eliminar producción
$( "#dialog-eliminar" ).dialog({
autoOpen: false,
modal: true
});
$(".eliminar").click(function (e) {
e.preventDefault();
var urlEliminar = $(this).attr("href");
$( "#dialog-eliminar" ).dialog({
autoOpen: false,
resizable: false,
height:160,
modal: true,
buttons: {
"Eliminar": function() {
window.location.href = urlEliminar;
},
"Cancelar": function() {
$( this ).dialog( "close" );
}
}
});
$( "#dialog-eliminar" ).dialog("open");
});
// Dialog validación de producción
$( "#dialog-validar" ).dialog({
autoOpen: false,
modal: true
});
$(".validar").click(function (e) {
e.preventDefault();
var urlValidar = $(this).attr("href");
$( "#dialog-validar" ).dialog({
autoOpen: false,
resizable: false,
height:160,
modal: true,
buttons: {
"Validar": function() {
window.location.href = urlValidar;
},
"Cancelar": function() {
$( this ).dialog( "close" );
}
}
});
$( "#dialog-validar" ).dialog("open");
});
// Dialog notificar publicación
$( "#dialog-notificar" ).dialog({
autoOpen: false,
modal: true
});
$(".notificar").click(function (e) {
e.preventDefault();
var urlValidar = $(this).attr("href");
$( "#dialog-notificar" ).dialog({
autoOpen: false,
resizable: false,
height:160,
modal: true,
buttons: {
"Notificar": function() {
window.location.href = urlValidar;
},
"Cancelar": function() {
$( this ).dialog( "close" );
}
}
});
$( "#dialog-notificar" ).dialog("open");
});
// Borrar la entrada de publicación del histórico de publicación
$( "#dialog-borrar-publi" ).dialog({
autoOpen: false,
modal: true
});
$(".borrar-publi").click(function (e) {
e.preventDefault();
var urlValidar = $(this).attr("href");
$( "#dialog-borrar-publi" ).dialog({
autoOpen: false,
resizable: false,
height:160,
modal: true,
buttons: {
"Borrar": function() {
window.location.href = urlValidar;
},
"Cancelar": function() {
$( this ).dialog( "close" );
}
}
});
$( "#dialog-borrar-publi" ).dialog("open");
});
// Dialog generación de ticket
$('#dialog-generarticket').dialog({
autoOpen: false,
height: 160,
modal: true,
resizable: false,
buttons: {
"Generar ticket": function() {
document.formgenerarticket.submit();
},
"Cancelar": function() {
$(this).dialog("close");
}
}
});
$("input.generarticket").click(function(e) {
e.preventDefault();
$("#dialog-generarticket").dialog("open");
});
// Dialog cambiar tipo de metadata
$('#dialog-editar-oa').dialog({
autoOpen: false,
height: 160,
modal: true,
resizable: false,
buttons: {
"Ok": function() {
$(this).dialog("close");
}
}
});
$('.form-editar #id_objecto_aprendizaje').change(function(e) {
$('#dialog-editar-oa').dialog("open");
});
// Dialog generación de ticket
$('#dialog-terminos').dialog({
autoOpen: false,
height: 160,
modal: true,
resizable: false,
buttons: {
"Ok": function() {
$(this).dialog("close");
}
}
});
$("input.terminos").click(function(e) {
if (!$("#accept_terms")[0].checked) {
e.preventDefault();
$("#dialog-terminos").dialog("open");
}
});
// Dialog aprobación
$( "#dialog-aprobar" ).dialog({
autoOpen: false,
modal: true
});
$(".aprobar").click(function (e) {
e.preventDefault();
var urlAprobar = $(this).attr("href");
$( "#dialog-aprobar" ).dialog({
autoOpen: false,
resizable: false,
height:160,
modal: true,
buttons: {
"Aprobar": function() {
window.location.href = urlAprobar;
},
"Cancelar": function() {
$( this ).dialog( "close" );
}
}
});
$( "#dialog-aprobar" ).dialog("open");
});
// Checkbox generación de ticket
function mostrarGenerarTicket() {
if ($("input:checkbox:checked").length == 0)
$("#generar-ticket").hide();
else
$("#generar-ticket").show();
}
mostrarGenerarTicket();
$(".marcar-todo").click(function() {
$(".checkbox-ticket").not(this).attr("checked", this.checked);
mostrarGenerarTicket();
});
$(".checkbox-ticket").click(function() {
if (!this.checked)
$(".marcar-todo").attr("checked", false);
mostrarGenerarTicket();
});
});
// Arrastra y ordena
$(function() {
$( ".column" ).sortable({
connectWith: ".column"
});
$( ".portlet" ).addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" )
.find( ".portlet-header" )
.addClass( "ui-widget-header ui-corner-all" )
.prepend( "<span class='ui-icon ui-icon-minusthick'></span>")
.end()
.find( ".portlet-content" );
$( ".portlet-header .ui-icon" ).click(function() {
$( this ).toggleClass( "ui-icon-minusthick" ).toggleClass( "ui-icon-plusthick" );
$( this ).parents( ".portlet:first" ).find( ".portlet-content" ).toggle();
});
$( ".portlet-header" ).disableSelection();
});
<file_sep># dpCat
Plataforma web para la optimización, unificación y sistematización de la producción, catalogación y publicación de contenidos digitales sobre la que se sustenta el servicio [ULLmedia](http://udv.ull.es/portal/ullmedia) de la Universidad de La Laguna.
## Colaboradores
* [<NAME>](https://github.com/pchinea)
* [<NAME>](https://github.com/Madh93)
* [<NAME>](https://github.com/alu0100697032)
* [<NAME>](https://github.com/moiseslodeiro)
* [<NAME>](https://github.com/adrianrv)
<file_sep>from configuracion.models import Settings
def set_option(c, v):
try:
s = Settings.objects.get(clave=c)
s.valor = v
except Settings.DoesNotExist:
s = Settings(clave=c, valor=v)
s.save()
def get_option(c):
try:
return Settings.objects.get(clave=c).valor
except Settings.DoesNotExist:
return None
def del_option(c):
try:
Settings.objects.get(clave=c).delete()
return True
except Settings.DoesNotExist:
return False
def list_options():
return [s.clave for s in Settings.objects.all()]
<file_sep>{% extends "postproduccion/base-2-1.html" %}
{% block page-title %}Nueva producción, paso 3{% endblock %}
{% block section-class %}class = "formulario paso3" {% endblock %}
{% block section-description %} {% endblock %}
{% block section-content %}
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Nueva producción, paso 3: Revisar y validar la nueva producción</h3>
</div>
<div class="box-body">
<form method="post" role="form">
<div class="box-group" id="accordion1">
<div class="panel box box-solid box-primary">
<div class="box-header with-border">
<h4 class="box-title">
<a data-toggle="collapse" data-parent="#accordion1" href="#datos">
Datos de la nueva producción:
</a>
</h4>
</div>
<div id="datos" class="panel-collapse collapse in">
<div class="box-body">
{% if v.plantilla %}
<div class="form-group">
<label>Plantilla:</label>
<input class="form-control" type="text" value="{{ v.plantilla.nombre }}" disabled="">
</div>
{% endif %}
<div class="form-group">
<label>Título:</label>
<input class="form-control" type="text" value="{{ v.titulo }}" disabled="">
</div>
<div class="form-group">
<label>Autor:</label>
<input class="form-control" type="text" value="{{ v.autor }}" disabled="">
</div>
<div class="form-group">
<label>Email:</label>
<input class="form-control" type="text" value="{{ v.email }}" disabled="">
</div>
<div class="form-group">
<label>Tipo Producción:</label>
<input class="form-control" type="text" value="{{ v.tipoVideo }}" disabled="">
</div>
<div class="form-group">
<label>Objeto de aprendizaje:</label>
<div>
<input type="checkbox" {{ v.objecto_aprendizaje|yesno:"checked," }} disabled="">
</div>
</div>
<div class="form-group">
<label>Observación</label>
<textarea class="form-control" cols="40" rows="5" disabled="">{{ v.informeproduccion.observacion }}</textarea>
</div>
<div class="form-group">
<label>Requiere aprobación</label>
<div>
<input type="checkbox" {{ v.informeproduccion.aprobacion|yesno:"checked," }} disabled="">
</div>
</div>
<div class="form-group">
<label>Fecha de grabación:</label>
<input class="form-control" type="text" value="{{ v.informeproduccion.fecha_grabacion|date:"G:i:s - d/m/Y" }}" disabled="">
</div>
</div>
</div>
</div>
</div>
<div class="box-group" id="accordion2">
<div class="panel box box-solid box-primary">
<div class="box-header with-border">
<h4 class="box-title">
<a data-toggle="collapse" data-parent="#accordion2" href="#ficheroEntrada">
Fichero(s) de entrada:
</a>
</h4>
</div>
<div id="ficheroEntrada" class="panel-collapse collapse in">
<div class="box-body">
{% for f in v.ficheroentrada_set.all %}
{% if v.plantilla %}
<label>{{ f.tipo.nombre }}</label>
{% else %}
<label>Entrada</label>
{% endif %}
<input class="form-control" type="text" value="{{ f.fichero }}" disabled=""><br/><br/>
{% endfor %}
</div>
</div>
</div>
</div>
{% csrf_token %}
<a type="button" href="{% url 'postproduccion.views.crear' v.id %}" class="btn btn-primary pull-left" id="volver">Modificar</a>
<input class="btn btn-primary pull-right" type="submit" value="Terminar y procesar" />
</form>
</div>
</div>
{% endblock %}
{% block section-widget %}
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Paso 3 de 3: Revisar y validar</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<table class="table table-condensed">
<tbody>
<tr>
<td><i class="fa fa-fw fa-info" style="font-size: 150%;"></i></td>
<td>Revisar detenidamente el contenido de la producción antes de continuar. Recuerde que una vez terminado el proceso de "nueva producción" el sistema incluirá en la cola de procesamiento del sistema la producción por lo que esta puede tardar en ser procesada.</td>
</tr>
<tr>
<div id="progreso" class="tres"></div>
</tr>
</tbody>
</table>
</div>
</div>
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Acciones disponibles</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<button class="btn btn-block btn-danger btn-sm" data-toggle="modal" data-target="#dialogEliminar">
<i class="icon fa fa-ban"></i>
Eliminar producción
</button>
</div>
</div>
<!-- Dialogo eliminar produccion -->
<div class="modal modal-danger fade" id="dialogEliminar" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">¿Eliminar producción?</h4>
</div>
<div class="modal-body">
La producción será eliminada de forma permanente y no podrá ser recuperada.
</div>
<div class="modal-footer">
<a type="button" href="{% url 'borrar' v.id %}" class="btn btn-outline pull-left">Eliminar</a>
<button type="button" class="btn btn-outline" data-dismiss="modal">Cancelar</button>
</div>
</div>
</div>
</div>
{% endblock %}
<file_sep># Create your views here.
# -*- encoding: utf-8 -*-
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.forms.formsets import formset_factory
from django.forms.models import inlineformset_factory
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt
from django.contrib import messages
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.contrib.auth import authenticate, login
from postproduccion.models import Coleccion, Video, Cola, FicheroEntrada, IncidenciaProduccion, RegistroPublicacion, InformeProduccion, PlantillaFDV
from postproduccion.forms import LoginForm, VideoForm, AddColeccionForm, CrearColeccionForm, FicheroEntradaForm, RequiredBaseInlineFormSet, MetadataOAForm, MetadataGenForm, InformeCreacionForm, ConfigForm, ConfigMailForm, IncidenciaProduccionForm, VideoEditarForm, InformeEditarForm
from postproduccion import queue
from postproduccion import utils
from postproduccion import token
from postproduccion import log
from postproduccion import crontab
from postproduccion import video
from configuracion import config
from django.contrib.auth.models import User
from datetime import timedelta
import os
import urllib
import datetime
from django.contrib.auth.decorators import permission_required
'''
Login
'''
def login_view(request):
if request.method == 'POST':
lform = LoginForm(data=request.POST)
if lform.is_valid():
username = request.POST['username']
password = request.POST['<PASSWORD>']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('postproduccion.views.index')
else:
lform = LoginForm()
return render_to_response("postproduccion/login.html", { 'form' : lform }, context_instance=RequestContext(request))
"""
Muestra la página inicial
"""
@permission_required('postproduccion.video_manager')
def index(request):
utils.set_default_settings() # Fija la configuración por defecto si no existía configuración previa.
return render_to_response("postproduccion/section-inicio.html", { }, context_instance=RequestContext(request))
"""
Crear nueva producción individual o como colección
"""
@permission_required('postproduccion.video_manager')
def nueva(request):
return render_to_response("postproduccion/section-nueva.html", { }, context_instance=RequestContext(request))
"""
Muestra el formulario para insertar un nuevo proyecto de vídeo.
"""
@permission_required('postproduccion.video_manager')
def crear(request, video_id = None):
v = get_object_or_404(Video, pk=video_id) if video_id else None
if request.method == 'POST':
vform = VideoForm(request.POST, instance=v) if v else VideoForm(request.POST)
iform = InformeCreacionForm(request.POST, instance=v.informeproduccion) if v else InformeCreacionForm(request.POST)
if vform.is_valid():
v = vform.save()
i = iform.save(commit = False)
i.video = v
i.operador = request.user
i.save()
return redirect('postproduccion.views.fichero_entrada', v.id)
else:
vform = VideoForm(instance = v) if v else VideoForm()
iform = InformeCreacionForm(instance = v.informeproduccion) if v else InformeCreacionForm(initial = { 'fecha_grabacion' : datetime.datetime.now() })
return render_to_response("postproduccion/section-nueva-paso1.html", { 'vform' : vform, 'iform' : iform }, context_instance=RequestContext(request))
"""
Muestra el formulario para insertar una producción en una colección existente.
"""
@permission_required('postproduccion.video_manager')
def add_coleccion(request):
if request.method == 'POST':
aform = AddColeccionForm(request.POST)
iform = InformeCreacionForm(request.POST)
if aform.is_valid():
c = get_object_or_404(Coleccion, pk = aform.data['coleccion'])
v = Video(
titulo = aform.data['video'],
plantilla = PlantillaFDV.objects.get(pk=aform.data['plantilla']) if aform.data['plantilla'] else None,
coleccion = c,
autor = c.autor,
email = c.email,
tipoVideo = c.tipoVideo,
objecto_aprendizaje = c.objecto_aprendizaje
)
v.save()
i = iform.save(commit = False)
i.video = v
i.operador = request.user
i.save()
return redirect('postproduccion.views.fichero_entrada', v.id)
else:
aform = AddColeccionForm()
iform = InformeCreacionForm(initial = { 'fecha_grabacion' : datetime.datetime.now() })
return render_to_response("postproduccion/section-add-coleccion.html", { 'aform' : aform, 'iform' : iform }, context_instance=RequestContext(request))
"""
Muestra el formulario para crear una nueva colección.
"""
@permission_required('postproduccion.video_manager')
def crear_coleccion(request):
if request.method == 'POST':
cform = CrearColeccionForm(request.POST)
if cform.is_valid():
c = cform.save()
messages.success(request, "Colección creada con éxito")
return redirect('postproduccion.views.add_coleccion')
else:
cform = CrearColeccionForm(initial = { 'fecha' : datetime.datetime.now() })
return render_to_response("postproduccion/section-nueva-coleccion.html", { 'cform' : cform }, context_instance=RequestContext(request))
"""
Muestra el formulario para seleccionar el fichero de entrada.
"""
@permission_required('postproduccion.video_manager')
def _fichero_entrada_simple(request, v, type = None):
if request.method == 'POST':
form = FicheroEntradaForm(request.POST, instance = v.ficheroentrada_set.all()[0]) if v.ficheroentrada_set.count() else FicheroEntradaForm(request.POST)
if form.is_valid():
fe = form.save(commit = False)
fe.video = v
fe.fichero = os.path.normpath(config.get_option('VIDEO_INPUT_PATH') + fe.fichero)
fe.save()
if type == 'reemplazar_video':
queue.enqueue_copy(v)
v.set_status('DEF')
messages.success(request, "Vídeo reemplazado y encolado para su procesado")
return redirect('postproduccion.views.estado_video', v.id)
else:
return redirect('postproduccion.views.resumen_video', v.id)
else:
if v.ficheroentrada_set.count():
fe = v.ficheroentrada_set.all()[0]
fe.fichero = os.path.join('/', os.path.relpath(fe.fichero, config.get_option('VIDEO_INPUT_PATH')))
form = FicheroEntradaForm(instance = fe)
else:
form = FicheroEntradaForm()
if type == 'reemplazar_video':
return render_to_response("postproduccion/section-reemplazar-video.html", { 'v' : v, 'form' : form }, context_instance=RequestContext(request))
else:
return render_to_response("postproduccion/section-nueva-paso2-fichero.html", { 'v' : v, 'form' : form }, context_instance=RequestContext(request))
"""
Muestra el formulario para seleccionar los ficheros de entrada.
"""
@permission_required('postproduccion.video_manager')
def _fichero_entrada_multiple(request, v, type = None):
n = v.plantilla.tipovideo_set.count()
FicheroEntradaFormSet = inlineformset_factory(Video, FicheroEntrada, formset = RequiredBaseInlineFormSet, form = FicheroEntradaForm, extra = n, max_num = n, can_delete = False)
tipos = v.plantilla.tipovideo_set.all().order_by('id')
if request.method == 'POST':
formset = FicheroEntradaFormSet(request.POST, instance = v) if v.ficheroentrada_set.count() else FicheroEntradaFormSet(request.POST)
print "previo"
if formset.is_valid():
instances = formset.save(commit = False)
for i in range(n):
instances[i].fichero = os.path.normpath(config.get_option('VIDEO_INPUT_PATH') + instances[i].fichero)
instances[i].video = v
instances[i].tipo = tipos[i]
instances[i].save()
if type == 'reemplazar_video':
queue.enqueue_pil(v)
v.set_status('DEF')
messages.success(request, "Vídeo reemplazado y encolado para su procesado")
return redirect('postproduccion.views.estado_video', v.id)
else:
return redirect('postproduccion.views.resumen_video', v.id)
else:
formset = FicheroEntradaFormSet(instance = v)
for i in range(n):
formset.forms[i].titulo = tipos[i].nombre
if formset.forms[i].initial:
formset.forms[i].initial['fichero'] = os.path.join('/', os.path.relpath(formset.forms[i].initial['fichero'], config.get_option('VIDEO_INPUT_PATH')))
if type == 'reemplazar_video':
return render_to_response("postproduccion/section-reemplazar-videos.html", { 'v' : v, 'formset' : formset }, context_instance=RequestContext(request))
else:
return render_to_response("postproduccion/section-nueva-paso2-ficheros.html", { 'v' : v, 'formset' : formset }, context_instance=RequestContext(request))
"""
Llama al método privado adecuado para insertar los ficheros de entrada según
el tipo de vídeo.
"""
@permission_required('postproduccion.video_manager')
def fichero_entrada(request, video_id):
v = get_object_or_404(Video, pk=video_id)
if v.plantilla:
return _fichero_entrada_multiple(request, v)
else:
return _fichero_entrada_simple(request, v)
"""
Muestra un resumen del vídeo creado.
"""
@permission_required('postproduccion.video_manager')
def resumen_video(request, video_id):
v = get_object_or_404(Video, pk=video_id)
if request.method == 'POST':
if v.plantilla:
queue.enqueue_pil(v)
else:
queue.enqueue_copy(v)
v.set_status('DEF')
messages.success(request, "Producción creada y encolada para su procesado")
return redirect('index')
return render_to_response("postproduccion/section-nueva-paso3.html", { 'v' : v }, context_instance=RequestContext(request))
"""
Devuelve una lista (html) con el contenido de un directorio para usar con la
llamada AJAX del jqueryFileTree.
"""
@permission_required('postproduccion.video_manager')
@csrf_exempt
def dirlist(request):
r = ['<ul class="jqueryFileTree" style="display: none;">']
try:
basedir = urllib.unquote(config.get_option('VIDEO_INPUT_PATH')).encode('utf-8')
reqdir = urllib.unquote(request.POST.get('dir')).encode('utf-8')
fulldir = os.path.normpath(basedir + reqdir)
for f in sorted(os.listdir(fulldir)):
if f.startswith('.'): continue
ff = os.path.join(reqdir, f)
if os.path.isdir(os.path.join(fulldir, f)):
r.append('<li class="directory collapsed"><a href="#" rel="%s/">%s</a></li>' % (ff, f))
else:
e =os.path.splitext(f)[1][1:] # get .ext and remove dot
r.append('<li class="file ext_%s"><a href="#" rel="%s">%s</a></li>' % (e, ff, f))
r.append('</ul>')
except Exception,e:
r.append('Could not load directory: %s' % str(e))
r.append('</ul>')
return HttpResponse(''.join(r))
@permission_required('postproduccion.video_manager')
def cola_base(request):
return render_to_response("postproduccion/section-cola-base.html", context_instance=RequestContext(request))
@permission_required('postproduccion.video_manager')
def cola_listado(request):
import json
data = list()
for task in Cola.objects.order_by('pk'):
linea = dict()
linea['v-titulo'] = task.video.titulo
linea['v-url'] = reverse('estado_video', args=(task.video.id,))
linea['tipo'] = dict(Cola.QUEUE_TYPE)[task.tipo]
linea['comienzo'] = task.comienzo.strftime("%H:%M:%S - %d/%m/%Y") if task.comienzo else None
linea['fin'] = task.fin.strftime("%H:%M:%S - %d/%m/%Y") if task.fin else None
linea['logfile'] = task.logfile.name
linea['logurl'] = reverse('postproduccion.views.mostrar_log', args=(task.pk,)) if task.logfile.name else None
linea['id'] = task.pk
linea['status'] = task.get_status_display()
linea['progress'] = queue.progress(task) if task.status == 'PRO' else ''
data.append(linea)
return HttpResponse(json.dumps(data))
"""
Muestra el fichero de log para una tarea.
"""
@permission_required('postproduccion.video_manager')
def mostrar_log(request, task_id):
task = get_object_or_404(Cola, pk=task_id)
return HttpResponse(queue.get_log(task), content_type='text/plain')
"""
Lista los vídeos que están pendientes de atención por parte del operador.
"""
@permission_required('postproduccion.video_manager')
def listar_pendientes(request):
filtro = Q(status = 'PTO') | Q(status = 'ACE') | Q(status = 'REC')
if request.is_ajax():
return render_to_response("postproduccion/ajax/content-pendientes.html", { 'list' : listar(filtro=filtro)[:5] }, context_instance=RequestContext(request))
else:
return render_to_response("postproduccion/section-pendientes.html", { 'list' : listar(filtro=filtro) }, context_instance=RequestContext(request))
"""
Lista los vídeos que están siendo procesados.
"""
@permission_required('postproduccion.video_manager')
def listar_en_proceso(request):
operator_id = request.GET.get('operator_id')
archivados = request.GET.get('archivados')
op_id = get_object_or_404(User, id=operator_id) if operator_id else None
if request.is_ajax():
return render_to_response("postproduccion/ajax/content-enproceso.html", { 'list' : listar(archivados, operator_id=op_id)[:10] }, context_instance=RequestContext(request))
else:
return render_to_response("postproduccion/section-enproceso.html", { 'list' : listar(archivados, operator_id=op_id) , 'usuarios' : User.objects.all()}, context_instance=RequestContext(request))
"""
Lista los vídeos que están siendo procesados que cumplan el filto dado.
"""
def listar(archivados = None, operator_id = None, filtro = None):
data = list()
if operator_id:#si se esta filtrando por operador hay que coger los videos desde imforme de produccion
informes_produccion = InformeProduccion.objects.filter(operador = operator_id).exclude(video__status = 'LIS').filter(id__gt = 2179)
if archivados == None:
informes_produccion = informes_produccion.exclude(video__archivado = True)
for v in informes_produccion.order_by('pk'):
data.append(get_linea(v.video))
else:#si no listamos todos los videos
videolist = Video.objects.exclude(status = 'LIS').filter(id__gt = 2179)
if archivados == None:
videolist = videolist.exclude(archivado = True)
videolist = videolist.filter(filtro) if filtro else videolist
for v in videolist.order_by('pk'):
data.append(get_linea(v))
return data
'''
Contruye una entrada con los datos de un video que toma como argumento
'''
def get_linea(video):
linea = dict()
linea['id'] = video.pk
linea['titulo'] = video.titulo
linea['operador'] = video.informeproduccion.operador.username
linea['fecha'] = video.informeproduccion.fecha_produccion.strftime("%d/%m/%Y")
linea['responsable'] = video.autor
linea['tipo'] = video.status.lower()
linea['status'] = dict(Video.VIDEO_STATUS)[video.status]
linea['archivado'] = video.archivado
return linea
"""
Lista las últimas producciones incluidas en la videoteca.
"""
@permission_required('postproduccion.video_manager')
def ultimas_producciones(request):
videolist = Video.objects.filter(status = 'LIS').order_by('-informeproduccion__fecha_validacion')
return render_to_response("postproduccion/ajax/content-ultimas.html", { 'videos' : videolist[:5] }, context_instance=RequestContext(request))
#######
# Vistas públicas para que el usuario acepte una producción.
#######
"""
Vista para que el usuario verifique un vídeo y lo apruebe o rechace.
"""
def aprobacion_video(request, tk_str):
v = token.is_valid_token(tk_str)
if not v: return render_to_response("postproduccion/section-ticket-caducado.html")
return render_to_response("postproduccion/section-inicio-aprobacion.html", { 'v' : v, 'token' : tk_str }, context_instance=RequestContext(request))
"""
Vista para que el usuario rellene los metadatos de un vídeo.
"""
def definir_metadatos_user(request, tk_str):
v = token.is_valid_token(tk_str)
if not v: return render_to_response("postproduccion/section-ticket-caducado.html")
if v.objecto_aprendizaje:
MetadataForm = MetadataOAForm
metadataField = 'metadataoa'
else:
MetadataForm = MetadataGenForm
metadataField = 'metadatagen'
initial_data = {
'title' : v.titulo,
'creator' : v.autor
}
if request.method == 'POST':
form = MetadataForm(request.POST, instance = getattr(v, metadataField)) if hasattr(v, metadataField) else MetadataForm(request.POST, initial = initial_data)
if form.is_valid():
m = form.save(commit = False)
m.video = v
m.date = v.informeproduccion.fecha_grabacion
m.created = v.informeproduccion.fecha_produccion
m.save()
inpro = IncidenciaProduccion(informe = v.informeproduccion, aceptado = True)
inpro.save()
token.token_attended(v)
v.status = 'ACE'
v.save()
video.add_metadata(v)
return render_to_response("postproduccion/section-resumen-aprobacion.html", { 'v' : v, 'aprobado' : True }, context_instance=RequestContext(request))
else:
form = MetadataForm(instance = getattr(v, metadataField)) if hasattr(v, metadataField) else MetadataForm(initial = initial_data)
return render_to_response("postproduccion/section-metadatos-user.html", { 'form' : form, 'v' : v, 'token' : tk_str }, context_instance=RequestContext(request))
"""
Solicita al usuario una razón por la cual el vídeo ha sido rechazado
"""
def rechazar_video(request, tk_str):
v = token.is_valid_token(tk_str)
if not v: return render_to_response("postproduccion/section-ticket-caducado.html")
if request.method == 'POST':
form = IncidenciaProduccionForm(request.POST)
if form.is_valid():
inpro = form.save(commit = False)
inpro.informe = v.informeproduccion
inpro.aceptado = False
inpro.save()
token.token_attended(v)
v.status = 'REC'
v.save()
return render_to_response("postproduccion/section-resumen-aprobacion.html", { 'v' : v, 'aprobado' : False }, context_instance=RequestContext(request))
else:
form = IncidenciaProduccionForm()
return render_to_response("postproduccion/section-rechazar-produccion.html", { 'v' : v, 'form' : form, 'token' : tk_str }, context_instance=RequestContext(request))
#######
# Vistas para reemplazar un video de una producción existente
#######
@permission_required('postproduccion.video_manager')
def reemplazar_video(request, video_id):
v = get_object_or_404(Video, pk=video_id)
if v.plantilla:
return _fichero_entrada_multiple(request, v, type = 'reemplazar_video')
else:
return _fichero_entrada_simple(request, v, type = 'reemplazar_video')
#######
# Vistas para mostrar la información de una producción.
#######
"""
Vista para que el operador rellene los metadatos de un vídeo.
"""
@permission_required('postproduccion.video_manager')
def definir_metadatos_oper(request, video_id):
v = get_object_or_404(Video, pk=video_id)
pub = RegistroPublicacion.objects.filter(video__id=v.id)
if v.objecto_aprendizaje:
MetadataForm = MetadataOAForm
metadataField = 'metadataoa'
else:
MetadataForm = MetadataGenForm
metadataField = 'metadatagen'
initial_data = {
'title' : v.titulo,
'creator' : v.autor
}
if request.method == 'POST':
form = MetadataForm(request.POST, instance = getattr(v, metadataField)) if hasattr(v, metadataField) else MetadataForm(request.POST, initial = initial_data)
if form.is_valid():
m = form.save(commit = False)
m.video = v
m.date = v.informeproduccion.fecha_grabacion
m.created = v.informeproduccion.fecha_produccion
m.save()
video.add_metadata(v)
messages.success(request, 'Metadata actualizada')
else:
form = MetadataForm(instance = getattr(v, metadataField)) if hasattr(v, metadataField) else MetadataForm(initial = initial_data)
return render_to_response("postproduccion/section-metadatos-oper.html", { 'form' : form, 'v' : v, 'pub' : pub}, context_instance=RequestContext(request))
"""
Vista que muestra el estado e información de una producción.
"""
@permission_required('postproduccion.video_manager')
def estado_video(request, video_id):
v = get_object_or_404(Video, pk=video_id)
pub = RegistroPublicacion.objects.filter(video__id=v.id)
return render_to_response("postproduccion/section-resumen-produccion.html", { 'v' : v, 'pub' : pub }, context_instance=RequestContext(request))
"""
Vista que muestra el estado e información de una colección.
"""
@permission_required('postproduccion.video_manager')
def estado_coleccion(request, coleccion_id):
c = get_object_or_404(Coleccion, pk = coleccion_id)
pub = RegistroPublicacion.objects.filter(video__in = c.video_set.all()).values_list('video', flat= True)
return render_to_response("postproduccion/section-resumen-coleccion.html", { 'c' : c, 'pub' : pub }, context_instance=RequestContext(request))
"""
Muestra la información técnica del vídeo
"""
@permission_required('postproduccion.video_manager')
def media_info(request, video_id):
v = get_object_or_404(Video, pk=video_id)
pub = RegistroPublicacion.objects.filter(video__id=v.id)
info = video.parse_mediainfo(v.tecdata.txt_data) if hasattr(v, 'tecdata') else None
return render_to_response("postproduccion/section-metadata-tecnica.html", { 'v' : v, 'info' : info, 'pub' : pub}, context_instance=RequestContext(request))
"""
Devuelve la información técnica del vídeo en XML para su descarga.
"""
@permission_required('postproduccion.video_manager')
def download_media_info(request, video_id):
v = get_object_or_404(Video, pk=video_id)
response = HttpResponse(v.tecdata.xml_data, content_type='text/xml')
response['Content-Disposition'] = 'attachment; filename=%d.xml' % v.id
return response
"""
Gestión de tickets de usuario.
"""
@permission_required('postproduccion.video_manager')
def gestion_tickets(request, video_id):
v = get_object_or_404(Video, pk=video_id)
if v.status == 'LIS': raise Http404
tk = token.get_token_data(v)
if request.method == 'POST':
form = IncidenciaProduccionForm(request.POST)
if form.is_valid():
inpro = form.save(commit = False)
inpro.informe = v.informeproduccion
inpro.emisor = request.user
inpro.save()
v.status = 'PTU'
v.save()
if token.send_custom_mail_to_user(v, inpro.comentario, request.user.first_name) is None:
messages.success(request, "Ticket generado")
messages.error(request, "No se ha podido enviar al usuario")
else:
messages.success(request, "Ticket generado y enviado al usuario")
return redirect('gestion_tickets', v.id)
else:
form = IncidenciaProduccionForm()
return render_to_response("postproduccion/section-gestion-tickets.html", { 'v' : v, 'form' : form, 'token' : tk }, context_instance=RequestContext(request))
"""
Regenerar tickets mediante checkbox
"""
@permission_required('postproduccion.video_manager')
def regenerar_tickets(request):
if request.method == 'POST':
videos = Video.objects.filter(pk__in=request.POST.getlist('ticket'))
for v in videos:
if v.status == 'LIS': continue
v.status = 'PTU'
v.save()
if token.send_custom_mail_to_user(v, ('regenerar ticket %s' % v.titulo), request.user.first_name) is None:
messages.error(request, "No se ha podido enviar al usuario")
messages.success(request, "Tickets regenerados")
return redirect('enproceso')
"""
Archivar/desarchivar videos mediante checkbox
"""
@permission_required('postproduccion.video_manager')
def archivar_desarchivar(request):
if request.method == 'POST':
videos = Video.objects.filter(pk__in=request.POST.getlist('ticket'))
for v in videos:
if v.archivado == True:
v.archivado = False
v.save()
else:
v.archivado = True
v.save()
messages.success(request, "Prceso de archivado realizado correctamente")
return redirect('enproceso')
"""
Edita la información básica de la producción.
"""
@permission_required('postproduccion.video_manager')
def editar_produccion(request, video_id):
v = get_object_or_404(Video, pk=video_id)
if v.status == 'LIS': raise Http404
if request.method == 'POST':
vform = VideoEditarForm(request.POST, instance=v)
iform = InformeEditarForm(request.POST, instance=v.informeproduccion)
if vform.is_valid():
v = vform.save()
i = iform.save()
if v.objecto_aprendizaje and hasattr(v, 'metadatagen'):
v.metadatagen.delete()
messages.error(request, u'Eliminada la metadata previamente asociada a la producción')
if not v.objecto_aprendizaje and hasattr(v, 'metadataoa'):
v.metadataoa.delete()
messages.error(request, u'Eliminada la metadata previamente asociada a la producción')
messages.success(request, u'Actualizada la información básica de la producción')
else:
vform = VideoEditarForm(instance = v)
iform = InformeEditarForm(instance = v.informeproduccion)
return render_to_response("postproduccion/section-editar-info.html", { 'v' : v, 'vform' : vform, 'iform' : iform }, context_instance=RequestContext(request))
"""
Valida una producción y la pasa a la videoteca.
"""
@permission_required('postproduccion.video_manager')
def validar_produccion(request, video_id):
v = get_object_or_404(Video, pk=video_id)
metadataField = 'metadataoa' if v.objecto_aprendizaje else 'metadatagen'
if hasattr(v, metadataField):
v.informeproduccion.fecha_validacion = datetime.datetime.now()
v.informeproduccion.save()
getattr(v, metadataField).valid = v.informeproduccion.fecha_validacion
getattr(v, metadataField).save()
v.status = 'LIS'
v.save()
#if v.informeproduccion.aprobacion:
# token.send_validation_mail_to_user(v, request.user.first_name)
queue.removeVideoTasks(v)
if v.informeproduccion.aprobacion:
v.previsualizacion.delete()
messages.success(request, "Producción validada")
else:
messages.error(request, "Metadatos no definidos, no se puede validar")
return redirect('estado_video', v.id)
"""
Borra una producción.
"""
@permission_required('postproduccion.video_manager')
def borrar_produccion(request, video_id):
v = get_object_or_404(Video, pk=video_id)
v.delete()
messages.success(request, 'Producción eliminada con éxito.')
return redirect('postproduccion.views.index')
"""
Borra una colección
"""
@permission_required('postproduccion.video_manager')
def borrar_coleccion(request, coleccion_id):
c = get_object_or_404(Coleccion, pk=coleccion_id)
c.delete()
messages.success(request, 'Colección eliminada con éxito.')
return redirect('postproduccion.views.index')
"""
Envía un correo al autor notificando de que una producción se encuentra publicada.
"""
@permission_required('postproduccion.video_manager')
def notificar_publicacion(request, record_id):
r = get_object_or_404(RegistroPublicacion, pk = record_id)
if token.send_published_mail_to_user(r) is None:
messages.error(request, u'No se ha podido enviar la notificación al autor')
else:
messages.success(request, u'Enviado correo de notificación de publicacion al autor')
return redirect('estado_video', r.video.id)
"""
Borra el registro de publicación dado.
"""
@permission_required('postproduccion.video_manager')
def borrar_registro(request, record_id):
r = get_object_or_404(RegistroPublicacion, pk = record_id)
v = r.video
r.delete()
messages.success(request, u'Registro de publicación eliminado')
return redirect('estado_video', v.id)
"""
Muestra la videoteca.
"""
@permission_required('postproduccion.video_manager')
def videoteca(request):
video_list = Video.objects.filter(status = 'LIS').order_by('-informeproduccion__fecha_validacion')
colecciones = Coleccion.objects.all()
publicados = RegistroPublicacion.objects.all().values_list('video', flat= True)
autor = request.GET.get('autor')
titulo = request.GET.get('titulo')
vid = request.GET.get('id')
tipoVideoSearch = request.GET.get('tipoVideo')
coleccionSearch = request.GET.get('coleccion')
meta_titulo = request.GET.get('meta_titulo')
meta_autor = request.GET.get('meta_autor')
meta_descripcion = request.GET.get('meta_descripcion')
meta_etiqueta = request.GET.get('meta_etiqueta')
try:
f_ini = datetime.datetime.strptime(request.GET.get('f_ini'), "%d/%m/%Y")
except (ValueError, TypeError):
f_ini = None
try:
f_fin = datetime.datetime.strptime(request.GET.get('f_fin'), "%d/%m/%Y")
except (ValueError, TypeError):
f_fin = None
if autor:
video_list = video_list.filter(autor__icontains = autor)
if titulo:
video_list = video_list.filter(titulo__icontains = titulo)
if vid:
video_list = video_list.filter(pk = vid)
if meta_titulo:
video_list = video_list.filter(Q(metadatagen__title__icontains=meta_titulo) | Q(metadataoa__title__icontains=meta_titulo))
if meta_autor:
video_list = video_list.filter(Q(metadatagen__creator__icontains=meta_autor) | Q(metadataoa__creator__icontains=meta_autor))
if meta_descripcion:
video_list = video_list.filter(Q(metadatagen__description__icontains=meta_descripcion) | Q(metadataoa__description__icontains=meta_descripcion))
if meta_etiqueta:
video_list = video_list.filter(Q(metadatagen__keyword__icontains=meta_etiqueta) | Q(metadataoa__keyword__icontains=meta_etiqueta))
if tipoVideoSearch and tipoVideoSearch != 'UNK':
video_list = video_list.filter(tipoVideo = tipoVideoSearch)
if coleccionSearch and coleccionSearch != '0':
video_list = video_list.filter(coleccion = Coleccion.objects.get(pk = coleccionSearch))
video_list = video_list.filter(informeproduccion__fecha_validacion__range = (f_ini or datetime.datetime.now().date() - timedelta(days=30), f_fin or datetime.date.max))
rango_fechas = "resultados del " + (f_ini or datetime.datetime.now().date() - timedelta(days=30)).strftime("%d/%m/%Y") + " al " + (f_fin or datetime.datetime.now().date()).strftime("%d/%m/%Y")
return render_to_response(
"postproduccion/section-videoteca.html",
{
'box_header' : rango_fechas,
'videos' : video_list,
'pub' : publicados,
'tipoVideo' : Video.VIDEO_TYPE,
'colecciones': colecciones
},
context_instance=RequestContext(request)
)
"""
Mostrar colecciones existentes en dpCat
"""
@permission_required('postproduccion.video_manager')
def colecciones(request):
colecciones = Coleccion.objects.all().order_by('-fecha')
cid = request.GET.get('id')
titulo = request.GET.get('titulo')
autor = request.GET.get('autor')
email = request.GET.get('email')
tipoVideoSearch = request.GET.get('tipoVideo')
try:
f_ini = datetime.datetime.strptime(request.GET.get('f_ini'), "%d/%m/%Y")
except (ValueError, TypeError):
f_ini = None
try:
f_fin = datetime.datetime.strptime(request.GET.get('f_fin'), "%d/%m/%Y")
except (ValueError, TypeError):
f_fin = None
if cid:
colecciones = colecciones.filter(pk = cid)
if titulo:
colecciones = colecciones.filter(titulo__icontains = titulo)
if autor:
colecciones = colecciones.filter(autor__icontains = autor)
if email:
colecciones = colecciones.filter(email__icontains = email)
if tipoVideoSearch and tipoVideoSearch != 'UNK':
colecciones = colecciones.filter(tipoVideo = tipoVideoSearch)
colecciones = colecciones.filter(fecha__range = (f_ini or datetime.date.min, f_fin or datetime.date.max))
return render_to_response(
"postproduccion/section-colecciones.html",
{
'colecciones' : colecciones,
'tipoVideo' : Coleccion.VIDEO_TYPE
},
context_instance=RequestContext(request)
)
"""
Mostrar estadísticas de la videoteca
"""
@permission_required('postproduccion.video_manager')
def estadisticas(request):
videos = Video.objects.all()
# Personalizacion de resultados por fecha
try:
f_ini = datetime.datetime.strptime(request.GET.get('f_ini'), "%d/%m/%Y")
except (ValueError, TypeError):
f_ini = None
try:
f_fin = datetime.datetime.strptime(request.GET.get('f_fin'), "%d/%m/%Y")
except (ValueError, TypeError):
f_fin = None
videos = videos.filter(informeproduccion__fecha_grabacion__range = (f_ini or datetime.date.min, f_fin or datetime.date.max))
# Estadisticas
n_prod = [
['Producciones realizadas', videos.count(), video.get_duration(videos)],
['Producciones validadas', videos.filter(status='LIS').count(), video.get_duration(videos.filter(status='LIS'))],
['Pildoras', videos.exclude(plantilla=None).count(), video.get_duration(videos.exclude(plantilla=None))],
['Producciones propias', videos.filter(plantilla=None).count(), video.get_duration(videos.filter(plantilla=None))]
]
return render_to_response("postproduccion/section-estadisticas.html", { 'stats': n_prod }, context_instance=RequestContext(request))
#######
@permission_required('postproduccion.video_library')
def stream_video(request, video_id):
v = get_object_or_404(Video, pk=video_id)
resp = HttpResponse(utils.stream_file(v.fichero), content_type='video/mp4')
resp['Content-Length'] = os.path.getsize(v.fichero)
return resp
@permission_required('postproduccion.video_library')
def download_video(request, video_id):
v = get_object_or_404(Video, pk=video_id)
resp = HttpResponse(utils.stream_file(v.fichero), content_type='video/mp4')
resp['Content-Length'] = os.path.getsize(v.fichero)
resp['Content-Disposition'] = "attachment;filename=%d_%s.mp4" % (v.id, utils.normalize_filename(v.titulo))
return resp
def stream_preview(request, tk_str):
v = token.is_valid_token(tk_str)
resp = HttpResponse(utils.stream_file(v.previsualizacion.fichero), content_type='video/mp4')
resp['Content-Length'] = os.path.getsize(v.previsualizacion.fichero)
return resp
"""
Muestra el registro de eventos de la aplicación.
"""
@permission_required('postproduccion.video_manager')
def showlog(request, old = False):
logdata = log.get_log() if not old else log.get_old_log()
return render_to_response("postproduccion/section-log.html", { 'log' : logdata, 'old' : old }, context_instance=RequestContext(request))
"""
Muestra las alertas de la aplicación.
"""
@permission_required('postproduccion.video_manager')
def alerts(request):
lista = list()
tipo = {
'video-incompleto' : 'Video incompleto',
'trabajo-fail' : 'Tarea fallida',
'token-caducado' : 'Token caducado',
'video-aceptado' : 'Video sin validar',
'ejecutable' : 'Ejecutable',
'ruta' : 'Ruta',
'disco' : 'Disco',
'cron_proc' : 'Tarea programada'
}
tipoVideo = request.GET.get('tipoVideo')
# Añade los vídeos incompletos.
for i in Video.objects.filter(status='INC'):
lista.append({ 'tipo' : 'video-incompleto', 'v' : i, 'fecha' : i.informeproduccion.fecha_produccion })
# Añade las tareas fallidas.
for i in Cola.objects.filter(status='ERR'):
lista.append({ 'tipo' : 'trabajo-fail', 't' : i, 'fecha' : i.comienzo })
# Añade los tokens caducados.
for i in token.get_expired_tokens():
lista.append({ 'tipo' : 'token-caducado', 't' : i, 'fecha' : token.get_expire_time(i) })
# Añade los vídeos aceptados pendientes de validación.
for i in InformeProduccion.objects.filter(
video=Video.objects.filter(status='ACE'),
fecha_produccion__lt = datetime.datetime.today() - datetime.timedelta(days = 15)):
lista.append({ 'tipo' : 'video-aceptado', 'v' : i.video , 'fecha' : i.fecha_produccion })
# Comprueba los ejecutables.
if not utils.avconv_version():
lista.append({ 'tipo' : 'ejecutable', 'exe' : 'avconv', 'fecha' : datetime.datetime.min })
if not utils.melt_version():
lista.append({ 'tipo' : 'ejecutable', 'exe' : 'melt', 'fecha' : datetime.datetime.min })
if not utils.mediainfo_version():
lista.append({ 'tipo' : 'ejecutable', 'exe' : 'mediainfo', 'fecha' : datetime.datetime.min })
if not utils.mp4box_version():
lista.append({ 'tipo' : 'ejecutable', 'exe' : 'MP4Box', 'fecha' : datetime.datetime.min })
if not utils.exiftool_version():
lista.append({ 'tipo' : 'ejecutable', 'exe' : 'exiftool', 'fecha' : datetime.datetime.min })
if not utils.is_exec(config.get_option('CRONTAB_PATH')):
lista.append({ 'tipo' : 'ejecutable', 'exe' : 'crontab', 'fecha' : datetime.datetime.min })
# Comprueba las rutas a los directorios.
for i in [config.get_option(x) for x in ['VIDEO_LIBRARY_PATH', 'VIDEO_INPUT_PATH', 'PREVIEWS_PATH']]:
if not utils.check_dir(i):
lista.append({ 'tipo' : 'ruta', 'path' : i, 'fecha' : datetime.datetime.min })
else:
cap = utils.df(i)[3]
if int(cap.rstrip('%')) > 90:
lista.append({ 'tipo' : 'disco', 'path' : i, 'cap' : cap, 'fecha' : datetime.datetime.min })
# Comprueba las tareas programadas
if not crontab.status('procesar_video'):
lista.append({ 'tipo' : 'cron_proc', 'fecha' : datetime.datetime.min })
if not crontab.status('publicar_video'):
lista.append({ 'tipo' : 'cron_pub', 'fecha' : datetime.datetime.min })
# Filtrar por tipo de video
if tipoVideo is not None:
lista = [element for element in lista if element['tipo'] == tipoVideo]
# Ordena los elementos cronológicamente
lista = sorted(lista, key=lambda it: it['fecha'])
if request.is_ajax():
return render_to_response("postproduccion/ajax/content-alertas.html", { 'lista' : lista[:5] }, context_instance=RequestContext(request))
else:
return render_to_response("postproduccion/section-alertas.html", { 'lista' : lista , 'tipoAlerta' : tipo}, context_instance=RequestContext(request))
"""
Edita los ajustes de configuración de la aplicación.
"""
@permission_required('postproduccion.video_manager')
def config_settings(request, mail = False):
ClassForm = ConfigMailForm if mail else ConfigForm
if request.method == 'POST':
form = ClassForm(request.POST)
if form.is_valid():
for i in form.base_fields.keys():
config.set_option(i.upper(), form.cleaned_data[i])
messages.success(request, 'Configuración guardada')
else:
initial_data = dict()
for i in ClassForm.base_fields.keys():
initial_data[i] = config.get_option(i.upper())
form = ClassForm(initial_data)
return render_to_response("postproduccion/section-config.html", { 'form' : form, 'mail' : mail }, context_instance=RequestContext(request))
"""
Muestra el estado de la aplicación con la configuración actual.
"""
@permission_required('postproduccion.video_manager')
def status(request):
# Programas externos
avconvver = utils.avconv_version()
meltver = utils.melt_version()
mediainfover = utils.mediainfo_version()
mp4boxver = utils.mp4box_version()
exiftoolver = utils.exiftool_version()
exes = {
'AVCONV' : {
'path' : config.get_option('AVCONV_PATH'),
'status' : True if avconvver else False,
'version' : avconvver,
},
'MELT' : {
'path' : config.get_option('MELT_PATH'),
'status' : True if meltver else False,
'version' : meltver,
},
'crontab' : {
'path' : config.get_option('CRONTAB_PATH'),
'status' : utils.is_exec(config.get_option('CRONTAB_PATH')),
'version' : 'N/A',
},
'mediainfo' : {
'path' : config.get_option('MEDIAINFO_PATH'),
'status' : True if mediainfover else False,
'version' : mediainfover,
},
'MP4Box' : {
'path' : config.get_option('MP4BOX_PATH'),
'status' : True if mp4boxver else False,
'version' : mp4boxver,
},
'exiftool' : {
'path' : config.get_option('EXIFTOOL_PATH'),
'status' : True if exiftoolver else False,
'version' : exiftoolver,
},
}
# Directorios
dirs = dict()
for i in [('library', 'VIDEO_LIBRARY_PATH'), ('input', 'VIDEO_INPUT_PATH'), ('previews', 'PREVIEWS_PATH')]:
data = { 'path' : config.get_option(i[1]) }
if utils.check_dir(data['path']):
df = utils.df(data['path'])
data['info'] = {
'total' : df[0],
'used' : df[1],
'left' : df[2],
'perc' : df[3],
'mount' : df[4]
}
dirs[i[0]] = data
# Tareas Programadas
if request.method == 'POST':
if 'status_process' in request.POST:
if request.POST['status_process'] == '1':
crontab.stop('procesar_video')
messages.warning(request, 'Tareas programadas de codificación desactivadas')
else:
crontab.start('procesar_video')
messages.success(request, 'Tareas programadas de codificacion activadas')
if 'status_publish' in request.POST:
if request.POST['status_publish'] == '1':
crontab.stop('publicar_video')
messages.warning(request, 'Tareas programadas de publicación desactivadas')
else:
crontab.start('publicar_video')
messages.success(request, 'Tareas programadas de publicación activadas')
cron = { 'process' : crontab.status('procesar_video'), 'publish' : crontab.status('publicar_video') }
# Información de la versión
dpcatinfo = utils.dpcat_info()
version = [
['Versión', dpcatinfo['version']],
['Rama', dpcatinfo['branch']],
['Commit', dpcatinfo['commit']],
['Repositorio', dpcatinfo['url']],
['Fecha', dpcatinfo['date']],
['Autor', dpcatinfo['author']],
['Mensaje', dpcatinfo['message']]
]
return render_to_response("postproduccion/section-status.html", { 'exes' : exes, 'dirs' : dirs, 'cron' : cron, 'version' : version }, context_instance=RequestContext(request))
<file_sep># -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from postproduccion.encoder import get_file_info, encode_mixed_video
from postproduccion.encoder import encode_preview, get_video_duration
from postproduccion.encoder import make_streamable, embed_metadata
from django.db.models import Sum
from postproduccion.models import TecData, Previsualizacion
from configuracion import config
from postproduccion import utils
from xml.dom.minidom import parseString
import os
import stat
import tempfile
import shutil
import string
from StringIO import StringIO
import datetime
def get_fdv_template(v):
"""
Renderiza el fichero de configuración del MELT
para la codificación de una píldora
"""
data = dict()
data['fondo'] = v.plantilla.fondo.path
videos = list()
duracion = list()
for i in v.ficheroentrada_set.all():
fe = dict()
fe['fichero'] = i.fichero
fe['geom'] = "%d/%d:%dx%d:%d" % (
i.tipo.x,
i.tipo.y,
i.tipo.ancho,
i.tipo.alto,
i.tipo.mix
)
duracion.append(get_video_duration(i.fichero))
videos.append(fe)
data['videos'] = videos
data['duracion'] = min(duracion) * 25
return render_to_response(
'postproduccion/get_fdv_template.mlt',
{'data': data}
)
def generate_tecdata(v):
"""
"""
try:
t = v.tecdata
except TecData.DoesNotExist:
t = TecData(video=v)
t.save()
[t.xml_data, t.txt_data] = get_file_info(v.fichero)
t.duration = get_video_duration(v.fichero)
t.save()
def get_tec_data(xmlstring):
"""
"""
dom = parseString(xmlstring.encode('utf-8'))
unparse_width = dom.getElementsByTagName('Width')[0].firstChild.data
unparse_height = dom.getElementsByTagName('Height')[0].firstChild.data
unparse_ratio = dom.getElementsByTagName(
'Display_aspect_ratio'
)[0].firstChild.data
width = int(str(unparse_width).translate(
None,
string.letters + string.whitespace
))
height = int(str(unparse_height).translate(
None,
string.letters + string.whitespace
))
if ':' in unparse_ratio:
[rw, rh] = unparse_ratio.split(':')
ratio = float(rw) / float(rh)
else:
ratio = float(unparse_ratio)
return [width, height, ratio]
def get_duration(v):
"""
Obtener duracion de vídeos a partir de la información técnica
"""
t = TecData.objects.filter(video=v).aggregate(Sum('duration'))
if t['duration__sum'] is None:
return 0
else:
return datetime.timedelta(seconds=t['duration__sum'])
def parse_mediainfo(mediadata):
"""
"""
mediainfo = list()
for section in mediadata.split('\n\n'):
if len(section) > 1:
lines = section.split('\n')
titulo = lines[0]
sect = {'section': lines[0], 'attr': list()}
for attr in lines[1:]:
sect['attr'].append({
'key': attr[:33].strip(),
'value': attr[34:].strip()
})
mediainfo.append(sect)
return mediainfo
def get_metadata(v):
"""
Devolver metada del video para incrustarla en el video
"""
str_metadata = ''
if v.objecto_aprendizaje:
try:
metadata = v.metadataoa
except:
return str_metadata
else:
try:
metadata = v.metadatagen
except:
return str_metadata
for f in metadata._meta.get_fields():
try:
value = getattr(metadata, 'get_%s_display' % f.name)()
except AttributeError:
value = getattr(metadata, f.name)
if value.__class__ == unicode:
str_metadata += "-XMP:%s='%s' " % \
(f.name, utils.normalize_string(value))
elif value.__class__ in (str, datetime.datetime):
str_metadata += "-XMP:%s='%s' " % (f.name, value)
return str_metadata
def calculate_preview_size(v):
[width, height, ratio] = get_tec_data(v.tecdata.xml_data)
max_width = float(config.get_option('MAX_PREVIEW_WIDTH'))
max_height = float(config.get_option('MAX_PREVIEW_HEIGHT'))
# Hace los pixels cuadrados
if ratio > 0:
width = height * ratio
else:
try:
height = width / ratio
except ZeroDivisionError:
pass
# Reduce el ancho
if width > max_width:
r = max_width / width
width *= r
height *= r
# Reduce el alto
if height > max_height:
r = max_height / height
width *= r
height *= r
# Hace el tamaño par (necesario para algunos codecs)
width = int((width + 1) / 2) * 2
height = int((height + 1) / 2) * 2
return dict({
'width': width,
'height': height,
'ratio': ratio
})
def create_pil(video, logfile, pid_notifier=None):
"""
"""
# Actualiza el estado del vídeo
video.set_status('PRV')
# Guarda la plantilla en un fichero temporal
(handler, path) = tempfile.mkstemp(suffix='.mlt')
os.write(handler, get_fdv_template(video).content)
os.close(handler)
# Genera el nombre del fichero de salida
if video.fichero:
utils.remove_file_path(video.fichero)
video.fichero = os.path.join(
config.get_option('VIDEO_LIBRARY_PATH'),
utils.generate_safe_filename(
video.titulo,
video.informeproduccion.fecha_produccion.date(),
".mp4"
)
)
video.save()
utils.ensure_dir(video.fichero)
# Montaje y codificación de la píldora
if encode_mixed_video(path, video.fichero, logfile, pid_notifier) != 0:
video.set_status('DEF')
os.unlink(path)
try:
os.unlink(video.fichero)
except:
pass
return False
# Prepara el fichero para hacer HTTP streaming.
make_streamable(video.fichero, logfile, pid_notifier)
# Obtiene la información técnica del vídeo generado.
generate_tecdata(video)
# Borra el fichero temporal
os.unlink(path)
# Actualiza el estado del vídeo
if video.informeproduccion.aprobacion:
video.set_status('COM')
else:
video.set_status('PTO')
return True
def copy_video(video, logfile):
# Actualiza el estado del vídeo
video.set_status('PRV')
# Obtiene los nombres de ficheros origen y destino
if video.fichero:
utils.remove_file_path(video.fichero)
src = video.ficheroentrada_set.all()[0].fichero
dst = os.path.join(
config.get_option('VIDEO_LIBRARY_PATH'),
utils.generate_safe_filename(
video.titulo,
video.informeproduccion.fecha_produccion.date(),
os.path.splitext(src)[1]
)
)
video.fichero = dst
video.save()
# Copia el fichero.
utils.ensure_dir(video.fichero)
try:
shutil.copy(src, dst)
os.write(logfile, '%s -> %s\n' % (src, dst))
os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP)
os.write(logfile, 'chmod: 640\n')
except IOError as error:
os.write(logfile, error.__str__())
video.set_status('DEF')
return False
# Obtiene la información técnica del vídeo copiado.
generate_tecdata(video)
# Actualiza el estado del vídeo
if video.informeproduccion.aprobacion:
video.set_status('COM')
else:
video.set_status('PTO')
return True
def create_preview(video, logfile, pid_notifier=None):
# Actualiza el estado del vídeo
video.set_status('PRP')
# Obtiene los nombres de ficheros origen y destino
src = video.fichero
dst = os.path.join(
config.get_option('PREVIEWS_PATH'),
utils.generate_safe_filename(
video.titulo,
video.informeproduccion.fecha_produccion.date(),
".mp4"
)
)
# Crea/reemplaza el objecto previsualización
try:
pv = Previsualizacion.objects.get(video=video)
utils.remove_file_path(pv.fichero)
pv.fichero = dst
except Previsualizacion.DoesNotExist:
pv = Previsualizacion(video=video, fichero=dst)
pv.save()
# Calcula las dimensiones de la previsualización.
size = calculate_preview_size(video)
# Codifica la previsualización.
utils.ensure_dir(pv.fichero)
if encode_preview(src, dst, size, logfile, pid_notifier) != 0:
video.set_status('COM')
try:
os.unlink(dst)
except:
pass
return False
# Actualiza el estado del vídeo
video.set_status('PTU')
return True
def add_metadata(video):
"""
Añadir toda la metadata al video
"""
# Obtener metadata
metadata = get_metadata(video)
# Incrustar metadatas
if not embed_metadata(video.fichero, metadata):
return False
return True
<file_sep>#coding: utf-8
from django import forms
from django.forms.widgets import RadioFieldRenderer
class ConfigForm(forms.Form):
client_id = forms.CharField(label = u'API Client ID')
client_secret = forms.CharField(label = u'API Client Secret')
max_tasks = forms.IntegerField(label = u'Nº máximo de publicaciones simultaneas')
def __init__(self, *args, **kwargs):
super(ConfigForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class' : 'form-control'})
################################################
class MyRadioFieldRenderer(RadioFieldRenderer):
outer_html = '{content}'
inner_html = '<div>{choice_value}{sub_widgets}</div>'
class MyRadioSelect(forms.RadioSelect):
renderer = MyRadioFieldRenderer
################################################
class PublishingForm(forms.Form):
title = forms.CharField(max_length = 100, label = u'Título')
description = forms.CharField(max_length = 5000, label = u'Descripción', widget = forms.Textarea)
tags = forms.CharField(max_length = 255, label = u'Etiquetas')
playlist = forms.TypedChoiceField(
label = u'Lista de reproducción',
choices = ((0, 'Sin lista de reproduccion'), (1, u'Anadir a existente'), (2, u'Crear nueva')),
initial = 0,
widget = MyRadioSelect(attrs={
'class': 'minimal'}),
coerce = int,
)
title.widget.attrs.update({'class' : 'form-control'})
description.widget.attrs.update({'class' : 'form-control'})
tags.widget.attrs.update({'class' : 'form-control'})
class AddToPlaylistForm(forms.Form):
add_to_playlist = forms.TypedChoiceField(label = u'Lista de reproducción')
add_to_playlist.widget.attrs.update({'class' : 'form-control select2'})
class NewPlaylistForm(forms.Form):
new_playlist_name = forms.CharField(label = u'Nombre de la lista de reproducción')
new_playlist_description = forms.CharField(label = u'Descripción de la lista de reproducción', widget = forms.Textarea)
def __init__(self, *args, **kwargs):
super(NewPlaylistForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class' : 'form-control'})<file_sep>{% extends "postproduccion/base-2-1.html" %}
{% block page-title %}Configuración{% endblock %}
{% block section-description %}{% endblock %}
{% block section-content %} {% endblock %}
{% block section-widget %}
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Detalles de configuración</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<table class="table table-condensed">
<tbody>
<tr>
<td>
<a type="button" class="btn btn-block btn-default btn-sm" href="{% url 'config' %}" style="text-align: left;">
<i class="icon fa fa-gears"></i>
Configuración del sistema
</a>
</td>
</tr>
<tr>
<td>
<a type="button" class="btn btn-block btn-default btn-sm" href="{% url 'config_mail' %}" style="text-align: left;">
<i class="icon fa fa-envelope"></i>
Configuración de los correos
</a>
</td>
</tr>
<tr>
<td>
<a type="button" class="btn btn-block btn-default btn-sm" href="{% url 'config_plugin' %}" style="text-align: left;">
<i class="icon fa fa-wrench"></i>
Configuración del plugin de publicación
</a>
</td>
</tr>
<tr>
<td>
<a type="button" class="btn btn-block btn-default btn-sm" href="{% url 'status' %}" style="text-align: left;">
<i class="icon fa fa-heartbeat"></i>
Ver el estado del sistema
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
{% block section-widget2 %}{% endblock %}
{% endblock %}
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('postproduccion', '0007_auto_20160330_1055'),
]
operations = [
migrations.AlterField(
model_name='metadatagen',
name='transcription',
field=models.TextField(help_text='Texto que se narra en el v\xeddeo.', null=True, verbose_name='Transcripci\xf3n', blank=True),
),
]
<file_sep># -*- encoding: utf-8 -*-
from django.core.management.base import BaseCommand
from postproduccion.models import Video
from postproduccion import video
def parse_input(input):
if 'all' in input:
return Video.objects.all()
videos = []
for arg in input:
if '-' in arg:
limits = arg.split('-')
try:
min_, max_ = int(limits[0]), int(limits[-1])
except:
continue
else:
if not min_ < max_:
continue
for id in xrange(min_, max_):
try:
v = Video.objects.get(pk=id)
except:
continue
videos += [v]
else:
try:
v = Video.objects.get(pk=int(arg))
except:
continue
videos += [v]
# Eliminar videos duplicados
return sorted(set(videos))
class Command(BaseCommand):
help = u'Incrutar metadata en los vídeos'
def add_arguments(self, parser):
# Positional argument
parser.add_argument(
'video_id',
metavar='ID',
type=str,
nargs='+',
help=u'Vídeos para incrustar metadata. Ej: 342 465 500-980'
)
# Named (optional) arguments
parser.add_argument(
'-a',
'--add',
action='store_true',
dest='add',
default=True,
help=u'Incrustar metadata en el vídeo'
)
parser.add_argument(
'-s',
'--show',
action='store_true',
dest='show',
default=False,
help=u'Mostrar metadata del vídeo'
)
def handle(self, *args, **options):
if options['show']:
options['add'] = False
for v in parse_input(options['video_id']):
print '\n--->Video [%s]: %s' % (v.id, v)
for metadata in video.get_metadata(v).split('-XMP:'):
if metadata:
print metadata
if options['add']:
for v in parse_input(options['video_id']):
if video.add_metadata(v) and options['verbosity'] > 1:
print "Video [%s]: updated metadata!" % v.id
elif options['verbosity'] > 1:
print "Video [%s]: it was not" \
"possible to add metadata..." % v.id
<file_sep>{% extends "postproduccion/base-2-1-monitor.html" %}
{% block page-title %}Centro de monitorización{% endblock %}
{% block section-class %} {% endblock %}
{% block section-content %}
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Producciones en proceso</h3>
</div>
<form method="post" action="" id="formgenerarticket" name="formgenerarticket">
{% csrf_token %}
<div class="box-body">
<table id="table_enproceso" class="table table-bordered table-hover dataTable">
<thead>
<tr role="row">
<th><input id="marcar-todo" type="checkbox" class="minimal" name="tickets" value=""></th>
<th>ID</th>
<th>Fecha</th>
<th>Operador</th>
<th>Autor/Responsable</th>
<th>Título</th>
<th>Estado</th>
</tr>
</thead>
<tbody>
{% if list %}
{% for video in list %}
<tr role="row">
<td><input type="checkbox" class="minimal" name="ticket" value="{{video.id}}" id="{{video.id}}"></td>
<td>{{ video.id }}</td>
<td>{{ video.fecha }}</td>
<td>{{ video.operador }}</td>
<td>{{ video.responsable }}</td>
<td>
{% if video.status == 'Incompleto' %}
<a href="{% url 'crear' video.id %}">{{ video.titulo }}</a>
{% else %}
<a href="{% url 'estado_video' video.id %}">{{ video.titulo }}</a>
{% endif %}
</td>
{% if video.archivado == True %}
<td><span class="label label-default">Archivado</span></td>
{% else %}
{% if video.status == 'Aceptado' %}
<td><span class="label label-success">{{ video.status }}</span></td>
{% elif video.status == 'Pendiente del usuario' or video.status == 'Definido'%}
<td><span class="label label-warning">{{ video.status }}</span></td>
{% else %}
<td><span class="label label-danger">{{ video.status }}</span></td>
{% endif %}
{% endif %}
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
<input id="generar-ticket" class="btn btn-primary" type="button" onclick="this.form.action='{% url 'regenerar_tickets' %}'; this.form.submit(); return false;" value="Generar ticket">
<input id="archivar" class="btn btn-primary" type="button" onclick="this.form.action='{% url 'archivar_desarchivar' %}'; this.form.submit(); return false;" value="Archivar/Desarchivar">
</div>
</form>
</div>
{% endblock %}
{% block filter-widget %}
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Filtrar:</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<form method="GET">
<div class="form-group">
<label>Operador:</label>
<select class="form-control select2" id="operator_id" name="operator_id"">
<option value="">Todos los operadores</option>
{% for usuario in usuarios %}
<option value="{{usuario.id}}">{{usuario.username}}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label>Mostrar archivados:</label>
<input type="checkbox" class="minimal" id="archivados" name="archivados">
</div>
<a class="btn btn-default" href="{% url 'enproceso' %}">Reiniciar</a>
<input class="btn btn-primary pull-right" type="submit" value="Filtrar" />
</form>
</div>
</div>
{% endblock %}
{% block section-widget %}
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Información de interés</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<table class="table table-condensed">
<tbody>
<tr>
<td><i class="fa fa-fw fa-info" style="font-size: 150%;"></i></td>
<td>Producciones que actualmente están siendo procesadas en el sistema en cualquiera de los estados en el que se encuentre.</td>
</tr>
</tbody>
</table>
</div>
</div>
{% endblock %}<file_sep>from django.contrib import admin
from postproduccion.models import Cola, Video, FicheroEntrada, TipoVideo
from postproduccion.models import PlantillaFDV, MetadataOA, MetadataGen
from postproduccion.models import InformeProduccion, RegistroPublicacion
class FicherosInline(admin.StackedInline):
model = FicheroEntrada
max_num = 2
extra = 1
class MetadataOAInline(admin.StackedInline):
model = MetadataOA
max_num = 1
class MetadataGenInline(admin.StackedInline):
model = MetadataGen
max_num = 1
class InformeProduccionInline(admin.StackedInline):
model = InformeProduccion
max_num = 1
class ColaInline(admin.TabularInline):
model = Cola
max_num = 1
readonly_fields = ('status', 'tipo', 'comienzo', 'fin', 'logfile')
class RegistroPublicacionInline(admin.TabularInline):
model = RegistroPublicacion
max_num = 1
readonly_fields = ('enlace',)
class VideoAdmin(admin.ModelAdmin):
list_display = ('titulo', 'status')
inlines = [FicherosInline, MetadataOAInline, MetadataGenInline,
InformeProduccionInline, ColaInline, RegistroPublicacionInline]
list_filter = ('status', 'objecto_aprendizaje')
class TipoVideoInline(admin.StackedInline):
model = TipoVideo
extra = 1
class PlantillaFDVAdmin(admin.ModelAdmin):
inlines = [TipoVideoInline]
admin.site.register(PlantillaFDV, PlantillaFDVAdmin)
admin.site.register(Video, VideoAdmin)
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('postproduccion', '0005_auto_20160315_1351'),
]
operations = [
migrations.AddField(
model_name='metadatagen',
name='transcription',
field=models.CharField(max_length=255, null=True, verbose_name='Transcripci\xf3n', blank=True),
),
]
<file_sep>{% extends "postproduccion/section-info-produccion.html" %}
{% block current-metadata %} disabled {% endblock %}
{% block section-content %}
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Metadata principal</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<form method="post" role="form">
{% csrf_token %}
{%for campo in form%}
<div class="form-group">
<label>{{ campo.label }}:</label>
{{ campo}}
<p class="text-muted">{{ campo.help_text}}</p>
</div>
{%endfor%}
<input class="btn btn-primary pull-right" type="submit" value="Guardar" />
</form>
</div>
</div>
{% endblock %}
{% block section-widget2 %}
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Tipo de metadata</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<table class="table table-condensed">
<tbody>
<tr>
<td>
<a type="button" class="btn btn-block btn-default btn-sm" href="{% url 'definir_metadatos_oper' v.id %}">
<i class="icon fa fa-file-text"></i>
Metadata principal
</a>
</td>
</tr>
<tr>
<td>
<a type="button" class="btn btn-block btn-default btn-sm" href="{% url 'media_info' v.id %}">
<i class="icon fa fa-file-text"></i>
Metadata técnica
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="box box-solid box-primary">
<div class="box-header with-border">
<h3 class="box-title">Información de interés</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body">
<table class="table table-condensed">
<tbody>
<tr>
<td><i class="fa fa-fw fa-info" style="font-size: 150%;"></i></td>
<td>Revise y valide el contenido de los metadatos antes de continuar.</td>
</tr>
</tbody>
</table>
</div>
</div>
{% endblock %}
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('postproduccion', '0009_video_archivado'),
]
operations = [
migrations.CreateModel(
name='Coleccion',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('titulo', models.CharField(max_length=100, verbose_name='T\xedtulo de Colecci\xf3n')),
('autor', models.CharField(default=b'', max_length=255, verbose_name='Responsable')),
('email', models.EmailField(default=b'', max_length=254, verbose_name='Email del responsable')),
('tipoVideo', models.CharField(default=b'UNK', max_length=3, verbose_name=b'Tipo Producci\xc3\xb3n', choices=[(b'UNK', 'Sin definir'), (b'PIL', 'P\xedldora formativa'), (b'VID', 'Videotutoriales'), (b'EDU', 'V\xeddeos Educativos'), (b'EVE', 'Grabaci\xf3n de Eventos'), (b'OTR', 'Otros')])),
('objecto_aprendizaje', models.BooleanField(default=True, verbose_name='Objeto de aprendizaje')),
('fecha', models.DateTimeField(null=True, verbose_name='Fecha de creaci\xf3n', blank=True)),
],
),
migrations.AddField(
model_name='video',
name='coleccion',
field=models.ForeignKey(blank=True, to='postproduccion.Coleccion', null=True),
),
]
<file_sep># encoding: utf-8
from django import forms
from django.forms import ModelForm, CharField, Textarea
from django.forms import widgets, Form, ValidationError
from django.forms.models import BaseInlineFormSet
from django.template import Template, TemplateSyntaxError
from postproduccion.models import Coleccion, Video, FicheroEntrada, MetadataOA
from postproduccion.models import MetadataGen, InformeProduccion
from postproduccion.models import IncidenciaProduccion, PlantillaFDV
from postproduccion.utils import is_exec, is_dir
from postproduccion.encoder import is_video_file
from configuracion import config
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
import os
class LoginForm(AuthenticationForm):
def clean(self):
username = password = <PASSWORD>
if 'username' in self.cleaned_data.keys():
username = self.cleaned_data['username']
if 'password' in self.cleaned_data.keys():
password = self.cleaned_data['password']
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError('Error de login')
return self.cleaned_data
def __init__(self, *args, **kwargs):
super(AuthenticationForm, self).__init__(*args, **kwargs)
self.fields['username'].label = 'Usuario'
self.fields['username'].widget.attrs.update({'class': 'form-control'})
self.fields['password'].widget.attrs.update({'class': 'form-control'})
class VideoForm(ModelForm):
class Meta:
model = Video
fields = '__all__'
exclude = ['archivado', 'coleccion']
def __init__(self, *args, **kwargs):
super(VideoForm, self).__init__(*args, **kwargs)
self.fields['plantilla'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['plantilla'].empty_label = 'Por defecto'
self.fields['titulo'].widget.attrs.update({'class': 'form-control'})
self.fields['autor'].widget.attrs.update({'class': 'form-control'})
self.fields['email'].widget.attrs.update({'class': 'form-control'})
self.fields['tipoVideo'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['objecto_aprendizaje'].widget.attrs.update(
{'class': 'minimal', 'checked': 'checked'}
)
class CrearColeccionForm(ModelForm):
class Meta:
model = Coleccion
fields = '__all__'
def __init__(self, *args, **kwargs):
super(CrearColeccionForm, self).__init__(*args, **kwargs)
self.fields['titulo'].widget.attrs.update({'class': 'form-control'})
self.fields['autor'].widget.attrs.update({'class': 'form-control'})
self.fields['email'].widget.attrs.update({'class': 'form-control'})
self.fields['tipoVideo'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['objecto_aprendizaje'].widget.attrs.update(
{'class': 'minimal', 'checked': 'checked'}
)
self.fields['fecha'].widget.attrs.update(
{'class': 'form-control pull-right'}
)
class AddColeccionForm(forms.Form):
plantilla = forms.ModelChoiceField(
queryset=PlantillaFDV.objects.all(),
label=u'Plantilla',
required=False
)
plantilla.widget.attrs.update({'class': 'form-control select2'})
plantilla.empty_label = 'Por defecto'
video = forms.CharField(label=u'Título de producción')
video.widget.attrs.update({'class': 'form-control'})
coleccion = forms.ModelChoiceField(
queryset=Coleccion.objects.all(), label=u'Colección')
coleccion.widget.attrs.update({'class': 'form-control select2'})
class InformeCreacionForm(ModelForm):
class Meta:
model = InformeProduccion
fields = ('observacion', 'aprobacion', 'fecha_grabacion')
def __init__(self, *args, **kwargs):
super(InformeCreacionForm, self).__init__(*args, **kwargs)
self.fields['observacion'].widget.attrs.update(
{'class': 'form-control', 'rows': '5'}
)
self.fields['aprobacion'].widget.attrs.update(
{'class': 'minimal', 'checked': 'checked'}
)
self.fields['fecha_grabacion'].widget.attrs.update(
{'class': 'form-control pull-right'}
)
class VideoEditarForm(ModelForm):
class Meta:
model = Video
fields = '__all__'
exclude = ['plantilla']
# fields = ('titulo', 'autor', 'email', 'objecto_aprendizaje')
def __init__(self, *args, **kwargs):
super(VideoEditarForm, self).__init__(*args, **kwargs)
self.fields['titulo'].widget.attrs.update({'class': 'form-control'})
self.fields['autor'].widget.attrs.update({'class': 'form-control'})
self.fields['email'].widget.attrs.update({'class': 'form-control'})
self.fields['tipoVideo'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['objecto_aprendizaje'].widget.attrs.update(
{'class': 'minimal', 'checked': 'checked'}
)
class InformeEditarForm(ModelForm):
class Meta:
model = InformeProduccion
fields = ('observacion',)
def __init__(self, *args, **kwargs):
super(InformeEditarForm, self).__init__(*args, **kwargs)
self.fields['observacion'].widget.attrs.update(
{'class': 'form-control', 'rows': '5'}
)
class IncidenciaProduccionForm(ModelForm):
class Meta:
model = IncidenciaProduccion
fields = ('comentario',)
def __init__(self, *args, **kwargs):
super(IncidenciaProduccionForm, self).__init__(*args, **kwargs)
self.fields['comentario'].widget.attrs.update(
{'class': 'form-control', 'rows': '5'}
)
class FicheroEntradaForm(ModelForm):
class Meta:
model = FicheroEntrada
fields = '__all__'
def __init__(self, *args, **kwargs):
super(FicheroEntradaForm, self).__init__(*args, **kwargs)
self.fields['fichero'].widget.attrs.update({'class': 'form-control'})
def clean_fichero(self):
data = self.cleaned_data['fichero']
try:
str(data)
except UnicodeEncodeError:
raise forms.ValidationError(
"El campo no debe contener tíldes ni caracteres especiales")
if not is_video_file(
os.path.normpath(config.get_option('VIDEO_INPUT_PATH') + data)
):
raise ValidationError(
u"El fichero no es un formato de vídeo reconocido")
return data
class RequiredBaseInlineFormSet(BaseInlineFormSet):
def _construct_form(self, i, **kwargs):
form = super(RequiredBaseInlineFormSet,
self)._construct_form(i, **kwargs)
form.empty_permitted = False
return form
class MetadataOAForm(ModelForm):
class Meta:
model = MetadataOA
fields = '__all__'
def __init__(self, *args, **kwargs):
super(MetadataOAForm, self).__init__(*args, **kwargs)
self.fields['knowledge_areas'].widget.attrs.update(
{'class': 'form-control select2'})
self.fields['title'].widget.attrs.update({'class': 'form-control'})
self.fields['creator'].widget.attrs.update({'class': 'form-control'})
self.fields['keyword'].widget.attrs.update({'class': 'form-control'})
self.fields['description'].widget.attrs.update(
{'class': 'form-control', 'rows': '5'}
)
self.fields['license'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['guideline'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['contributor'].widget.attrs.update(
{'class': 'form-control'}
)
self.fields['audience'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['typical_age_range'].widget.attrs.update(
{'class': 'form-control'}
)
self.fields['source'].widget.attrs.update({'class': 'form-control'})
self.fields['language'].widget.attrs.update({'class': 'form-control'})
self.fields['ispartof'].widget.attrs.update({'class': 'form-control'})
self.fields['location'].widget.attrs.update({'class': 'form-control'})
self.fields['venue'].widget.attrs.update({'class': 'form-control'})
self.fields['temporal'].widget.attrs.update(
{'class': 'form-control', 'rows': '5'}
)
self.fields['rightsholder'].widget.attrs.update(
{'class': 'form-control'}
)
self.fields['type'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['interactivity_type'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['interactivity_level'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['learning_resource_type'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['semantic_density'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['context'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['dificulty'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['typical_learning_time'].widget.attrs.update(
{'class': 'form-control'}
)
self.fields['educational_language'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['purpose'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['unesco'].widget.attrs.update(
{'class': 'form-control select2'}
)
class MetadataGenForm(ModelForm):
class Meta:
model = MetadataGen
fields = '__all__'
def __init__(self, *args, **kwargs):
super(MetadataGenForm, self).__init__(*args, **kwargs)
self.fields['knowledge_areas'].widget.attrs.update(
{'class': 'form-control select2'})
self.fields['title'].widget.attrs.update({'class': 'form-control'})
self.fields['creator'].widget.attrs.update({'class': 'form-control'})
self.fields['keyword'].widget.attrs.update({'class': 'form-control'})
self.fields['description'].widget.attrs.update(
{'class': 'form-control', 'rows': '5'}
)
self.fields['license'].widget.attrs.update(
{'class': 'form-control select2'}
)
self.fields['transcription'].widget.attrs.update(
{'class': 'form-control', 'rows': '5'}
)
self.fields['contributor'].widget.attrs.update(
{'class': 'form-control'}
)
self.fields['language'].widget.attrs.update({'class': 'form-control'})
self.fields['location'].widget.attrs.update({'class': 'form-control'})
self.fields['venue'].widget.attrs.update({'class': 'form-control'})
class ASCIIField(forms.CharField):
def validate(self, value):
super(ASCIIField, self).validate(value)
try:
str(value)
except UnicodeEncodeError:
raise forms.ValidationError(
"El campo no debe contener tíldes ni caracteres especiales.")
class ExecutableField(ASCIIField):
def validate(self, value):
super(ExecutableField, self).validate(value)
if not is_exec(value):
raise forms.ValidationError(
"El fichero no existe o no es ejecutable.")
class DirectoryField(ASCIIField):
def validate(self, value):
super(DirectoryField, self).validate(value)
if not is_dir(value):
raise forms.ValidationError(
"El directorio no existe o no es accesible.")
class TemplateField(forms.CharField):
widget = Textarea()
def validate(self, value):
super(TemplateField, self).validate(value)
try:
Template(value)
except:
raise forms.ValidationError(
u"El mensaje contiene etiquetas inválidas")
class ConfigForm(Form):
max_encoding_tasks = forms.IntegerField(
label=u'Nº máximo de codificaciones simultaneas')
mediainfo_path = ExecutableField(label=u'Ruta del \'mediainfo\'')
melt_path = ExecutableField(label=u'Ruta del \'melt\'')
avconv_path = ExecutableField(label=u'Ruta del \'avconv\'')
mp4box_path = ExecutableField(label=u'Ruta del \'MP4Box\'')
exiftool_path = ExecutableField(label=u'Ruta del \'exiftool\'')
crontab_path = ExecutableField(label=u'Ruta del \'crontab\'')
max_preview_width = forms.IntegerField(
label=u'Anchura máxima de la previsualización'
)
max_preview_height = forms.IntegerField(
label=u'Altura máxima de la previsualización'
)
video_library_path = DirectoryField(
label=u'Directorio base de la videoteca'
)
video_input_path = DirectoryField(
label=u'Directorio base de los ficheros de vídeo fuente'
)
previews_path = DirectoryField(
label=u'Directorio de base de las previsualizaciones'
)
token_valid_days = forms.IntegerField(
label=u'Periodo de validez del ticket de usuario (en días)'
)
site_url = forms.CharField(label=u'URL del sitio')
log_max_lines = forms.IntegerField(
label=u'Nº máximo de líneas del registro de sistema'
)
max_num_logfiles = forms.IntegerField(
label=u'Nº máximo de ficheros de registro de sistema antiguos'
)
def __init__(self, *args, **kwargs):
super(ConfigForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class': 'form-control'})
class ConfigMailForm(Form):
return_email = forms.EmailField(
label=u'Dirección del remitente para envíos de correos electrónicos'
)
notify_mail_subject = forms.CharField(
label=u'Asunto del correo de notificación de producción realizada'
)
notify_mail_message = TemplateField(
label=u'Mensaje del correo de notificación de producción realizada'
)
custom_mail_subject = forms.CharField(
label=u'Asusnto del correo de nuevo ticket por parte del operador'
)
custom_mail_message = TemplateField(
label=u'Mensaje del correo de nuevo ticket por parte del operador'
)
validated_mail_subject = forms.CharField(
label=u'Asunto del correo de aviso de validación de una producción'
)
validated_mail_message = TemplateField(
label=u'Mensaje del correo de aviso de validación de una producción'
)
published_mail_subject = forms.CharField(
label=u'Asunto del correo de aviso de publicación de una producción'
)
published_mail_message = TemplateField(
label=u'Mensaje del correo de aviso de publicación de una producción'
)
def __init__(self, *args, **kwargs):
super(ConfigMailForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class': 'form-control'})
<file_sep># encoding: utf-8
from django.contrib.auth.models import User
from django.template.loader import render_to_string
from django.template import Template, Context
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from postproduccion.models import Token, Video
from postproduccion import utils
from configuracion import config
from datetime import datetime, timedelta
from urlparse import urljoin
def create_token(v):
"""
Crea un nuevo token y devuelve su valor.
"""
if hasattr(v, 'token'): v.token.delete()
t = Token(video=v, token=utils.generate_token(25))
t.save()
return Video.objects.get(token=t)
def is_valid_token(tk_str):
"""
Verifica que una petición es válida.
En caso afirmativo devuelve el vídeo asociado.
"""
tk_query = Token.objects.filter(
token=tk_str,
instante__gt=datetime.now() - timedelta(
days=int(config.get_option('TOKEN_VALID_DAYS'))
)
)
if tk_query.count() != 1: return False
return tk_query[0].video
def get_expired_tokens(days=None):
"""
Devuelve los tokens caducados.
"""
if days is None:
return Token.objects.filter(
id__gt=2179,
instante__lt=datetime.now() - timedelta(
days=int(config.get_option('TOKEN_VALID_DAYS'))
)
)
else:
return Token.objects.filter(
id__gt=2179,
instante__gt=datetime.today() - timedelta(days=days)
)
def purge_expired_tokens():
"""
Borra los tokens caducados.
"""
get_expired_tokens().delete()
def get_token_data(v):
"""
Devuelve un hash con los datos del token del vídeo o falso si no existe.
"""
if hasattr(v, 'token'):
return {
'create_date': v.token.instante,
'expiration_date': v.token.instante + timedelta(
days=int(config.get_option('TOKEN_VALID_DAYS'))
),
'valid': True if is_valid_token(v.token.token) else False,
'url': get_token_url(v),
}
else:
return False
def get_expire_time(t):
"""
Devuelve la fecha de caducidad de un token.
"""
return t.instante + timedelta(
days=int(config.get_option('TOKEN_VALID_DAYS'))
)
def token_attended(v):
"""
Borra de la base de datos un token que ya ha sido atendido
"""
v.token.delete()
return Video.objects.get(id=v.id)
def get_token_url(v):
"""
Devuelve la url del ticket de usuario correspondiente al vídeo dado.
"""
return urljoin(
config.get_option('SITE_URL'),
reverse('postproduccion.views.aprobacion_video', args=(v.token.token,))
)
def generate_mail_message(v):
"""
Genera el mensaje de correo con las indicaciones para usar el token.
"""
(nombre, titulo, vid, fecha) = (
v.autor,
v.titulo,
v.id,
v.informeproduccion.fecha_grabacion
)
url = get_token_url(v)
return Template(config.get_option('NOTIFY_MAIL_MESSAGE')).render(Context({
'nombre': nombre,
'titulo': titulo,
'vid': vid,
'fecha': fecha,
'url': url,
'validez': get_token_data(v)['expiration_date'],
}))
def send_mail_to_user(v):
"""
Envía un correo al usuario para solicitar
la aprobación y los metadatos de un vídeo.
"""
v = create_token(v)
try:
send_mail(
config.get_option('NOTIFY_MAIL_SUBJECT'),
generate_mail_message(v),
config.get_option('RETURN_EMAIL'),
[v.email]
)
except:
return None
return v
def generate_custom_mail_message(v, texto, operador):
"""
Genera el mensaje de correo personalizado
con las indicaciones para usar el token.
"""
(nombre, titulo, vid, fecha) = (
v.autor,
v.titulo,
v.id,
v.informeproduccion.fecha_grabacion
)
url = get_token_url(v)
return Template(config.get_option('CUSTOM_MAIL_MESSAGE')).render(Context({
'nombre': nombre,
'titulo': titulo,
'vid': vid,
'fecha': fecha,
'texto': texto,
'url': url,
'operador': operador,
'validez': get_token_data(v)['expiration_date'],
}))
def send_custom_mail_to_user(v, texto, operador):
"""
Envía un correo personalizado al usuario
para solicitar la aprobación y los metadatos de un vídeo.
"""
v = create_token(v)
try:
send_mail(
config.get_option('CUSTOM_MAIL_SUBJECT'),
generate_custom_mail_message(v, texto, operador),
config.get_option('RETURN_EMAIL'),
[v.email]
)
except:
return None
return v
def generate_validation_mail_message(v, operador):
"""
Genera el mensaje de correo para avisar al
usuario de que su producción ya ha sido validada.
"""
(nombre, titulo, vid, fecha) = (
v.autor,
v.titulo,
v.id,
v.informeproduccion.fecha_grabacion
)
return Template(config.get_option('VALIDATED_MAIL_MESSAGE')).render(
Context({
'nombre': nombre,
'titulo': titulo,
'vid': vid,
'fecha': fecha,
'operador': operador,
})
)
def send_validation_mail_to_user(v, operador):
"""
Envía un correo para avisar al usuario de
que su producción ya ha sido validada.
"""
try:
send_mail(
config.get_option('VALIDATED_MAIL_SUBJECT'),
generate_validation_mail_message(v, operador),
config.get_option('RETURN_EMAIL'),
[v.email]
)
except:
return None
return v
def generate_published_mail_message(r):
"""
Genera el mensaje de correo para avisar al
usuario de que su producción ya ha sido publicada.
"""
(nombre, titulo, vid, fecha, url) = (
r.video.autor,
r.video.titulo,
r.video.id,
r.fecha,
r.enlace
)
return Template(config.get_option('PUBLISHED_MAIL_MESSAGE')).render(
Context({
'nombre': nombre,
'titulo': titulo,
'vid': vid,
'fecha': fecha,
'url': url,
})
)
def send_published_mail_to_user(r):
"""
Envía un correo para avisar al usuario
de que su producción ya ha sido publicada.
"""
try:
send_mail(
config.get_option('PUBLISHED_MAIL_SUBJECT'),
generate_published_mail_message(r),
config.get_option('RETURN_EMAIL'),
[r.video.email]
)
except:
return None
return True
<file_sep># encoding: utf-8
import string
import random
import unicodedata
import os
import threading
import subprocess
import shlex
import re
import json
from django.conf import settings
from configuracion import config
"""
Declara un cerrojo global para los bloqueos entre threads.
"""
lock = threading.Lock()
def set_default_settings():
"""
Fija los valores de configuración por defecto
"""
defaults = [
['MAX_ENCODING_TASKS', 5],
['MELT_PATH', which('melt')],
['AVCONV_PATH', which('avconv')],
['MP4BOX_PATH', which('MP4Box')],
['CRONTAB_PATH', which('crontab')],
['MEDIAINFO_PATH', which('mediainfo')],
['EXIFTOOL_PATH', which('exiftool')],
['EXIFTOOL_CONFIG', os.path.join(
settings.MEDIA_ROOT,
'config/exiftool_dpcat.config'
)],
['MAX_PREVIEW_WIDTH', 400],
['MAX_PREVIEW_HEIGHT', 300],
['VIDEO_LIBRARY_PATH', '/home/adminudv/videos/videoteca/'],
['VIDEO_INPUT_PATH', '/home/adminudv/videos/'],
['PREVIEWS_PATH', '/home/adminudv/videos/previews/'],
['TOKEN_VALID_DAYS', 7],
['SITE_URL', 'http://127.0.0.1:8000'],
['LOG_MAX_LINES', 1000],
['MAX_NUM_LOGFILES', 6],
['RETURN_EMAIL', '<EMAIL>'],
]
for op in defaults:
config.get_option(op[0]) or config.set_option(op[0], op[1])
def generate_token(length):
"""
Genera un token alfanumérico del tamaño dado
"""
random.seed()
return "".join(
[random.choice(string.letters + string.digits) for x in range(length)]
)
def normalize_filename(name):
"""
Normaliza una cadena para generar nombres de fichero seguros.
"""
return unicodedata.normalize('NFKD', name).encode(
'ascii',
'ignore'
).translate(None, string.punctuation).replace(' ', '_')
def normalize_string(string):
"""
Devuelve una cadena normalizada a partir de una de tipo unicode.
"""
try:
return unicodedata.normalize('NFKD', string).encode('ascii', 'ignore')
except:
return string
def generate_safe_filename(name, date, extension):
"""
Genera un nombre de fichero para un nuevo vídeo
"""
day = date.strftime("%Y/%m/%d")
safename = normalize_filename(name)
return "%s_%s_%s%s" % (day, safename, generate_token(8), extension)
def ensure_dir(f):
"""
Se asegura de que exista un directorio antes de crear un fichero en él.
"""
d = os.path.dirname(f)
lock.acquire()
if not os.path.exists(d):
os.makedirs(d)
lock.release()
def remove_file_path(f):
"""
Borra el fichero dado y los directorios que lo contienen si están vacíos.
"""
if os.path.isfile(f):
os.remove(f)
try:
os.removedirs(os.path.dirname(f))
except OSError:
pass
def is_dir(path):
"""
Comprueba si la ruta dada coresponde a un directorio
"""
return os.path.isdir(path)
def is_exec(fpath):
"""
Comprueba si la ruta dada corresponde a un fichero ejecutable
"""
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
def run_command(*commands):
"""
Ejecutar comando con posibilidad de concatenar tuberías
"""
p = subprocess.Popen(
shlex.split(str(commands[0])),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
for cmd in commands[1:]:
prev = p
p = subprocess.Popen(
shlex.split(str(cmd)),
stdin=prev.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
return p.communicate()[0]
def which(fpath):
"""
Trata de localizar la ruta del ejecutable dado en el PATH
"""
return run_command("/usr/bin/which %s" % fpath)
def avconv_version():
"""
Devuelve la versión del avconv instalado.
"""
fpath = config.get_option('AVCONV_PATH')
if is_exec(fpath):
data = run_command('%s -version' % fpath)
try:
return re.match('avconv version ([\.0-9]+)', data).group(1)
except AttributeError:
return None
def melt_version():
"""
Devuelve la versión del melt instalado.
"""
fpath = config.get_option('MELT_PATH')
if is_exec(fpath):
data = run_command('%s -version' % fpath)
try:
return re.search('melt ([\.0-9]+)', data).group(1)
except AttributeError:
return None
def mediainfo_version():
"""
Devuelve la versión del mediainfo instalado.
"""
fpath = config.get_option('MEDIAINFO_PATH')
if is_exec(fpath):
data = run_command('%s --Version' % fpath)
try:
return re.search('(v[0-9\.]+)$', data).group(1)
except AttributeError:
return None
def mp4box_version():
"""
Devuelve la versión del MP4Box instalado.
"""
fpath = config.get_option('MP4BOX_PATH')
if is_exec(fpath):
data = run_command('%s -version' % fpath)
try:
return re.search('version (\S*)', data).group(1)
except AttributeError:
return None
def exiftool_version():
"""
Devuelve la versión del exiftool instalado.
"""
fpath = config.get_option('EXIFTOOL_PATH')
if is_exec(fpath):
data = run_command('%s -ver' % fpath)
try:
return re.search('([\.0-9]+)', data).group(1)
except AttributeError:
return None
def df(fpath):
"""
Devuelve la información de uso del sistema
de ficheros en el que se encuentra la ruta dada.
"""
data = run_command('df %s -Ph' % fpath).strip().splitlines()[1]
return re.search('^.* +([\.0-9,]+[KMGTPEZY]?) +([\.0-9,]+[KMGTPEZY]?) +([\.0-9,]+[KMGTPEZY]?) +([\.0-9,]+%) +(/.*$)', data).group(1, 2, 3, 4, 5)
def dpcat_info():
"""
Devuelve la información acerca de la versión actual de dpCat.
"""
info = {}
repo = 'https://github.com/tic-ull/dpCat/tree/'
info['version'] = run_command('git tag', 'tail -1').strip()
tag_version = run_command('git rev-list --count %s' %
info['version']).strip()
head_version = run_command('git rev-list --count HEAD').strip()
if tag_version != head_version:
info['version'] = 'HEAD'
info['commit'] = 'r.%s.%s' % (
run_command('git rev-list --count %s' % info['version']).strip(),
run_command('git rev-parse --short %s' % info['version']).strip()
)
info['branch'] = run_command(
'git branch', 'grep *', 'cut -d " " -f2'
).strip()
info['url'] = repo + run_command('git rev-parse %s' %
info['version']).strip()
info['date'] = run_command('git show -s --format=%%ci %s' %
info['version']).strip()
info['message'] = run_command('git show -s --format=%%B %s' %
info['version']).strip()
info['author'] = run_command('git show -s --format=%%an %s' %
info['version']).strip()
return info
def check_dir(fpath):
"""
Comprueba si el directorio dado existe y es accesible.
Si no existe y puede, lo creará y devolverá verdadero.
"""
if os.path.isdir(fpath) and os.access(fpath, os.R_OK | os.W_OK | os.X_OK):
return True
if not os.path.exists(fpath):
try:
os.makedirs(fpath)
except:
return False
return True
else:
return False
def time_to_seconds(t):
"""
Convierte, en caso necesario, una marca temporal
en formato HH:MM:SS.ss a segundos.
"""
try:
return float(t)
except ValueError:
ct = t.split(':')
return float(ct[0]) * 3600 + float(ct[1]) * 60 + float(ct[2])
class FileIterWrapper(object):
"""
Clase envoltorio que permite iterar sobre un fichero.
"""
def __init__(self, flo, chunk_size=1024**2):
self.flo = flo
self.chunk_size = chunk_size
def next(self):
data = self.flo.read(self.chunk_size)
if data:
return data
else:
raise StopIteration
def __iter__(self):
return self
def stream_file(filename):
"""
Devuelve a modo de flujo el contenido del fichero dado.
"""
return FileIterWrapper(open(filename, "rb"))
<file_sep>from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'postproduccion.views',
url(r'^$', 'index', name="index"),
url(r'^nueva/$', 'nueva', name="nueva"),
url(r'^crear/$', 'crear', name="crear"),
url(r'^crear/(?P<video_id>\d+)/$', 'crear', name="crear"),
url(r'^add_coleccion/$', 'add_coleccion', name="add_coleccion"),
url(r'^crear_coleccion/$', 'crear_coleccion', name="crear_coleccion"),
(r'^fichero_entrada/(?P<video_id>\d+)/$', 'fichero_entrada'),
(r'^resumen_video/(?P<video_id>\d+)/$', 'resumen_video'),
(r'^dirlist/$', 'dirlist'),
url(r'^cola/$', 'cola_base', name="cola"),
(r'^cola_listado/$', 'cola_listado'),
url(r'^mostrar_log/(?P<task_id>\d+)/$', 'mostrar_log', name="mostrar_log"),
url(r'^definir_metadatos/(?P<tk_str>\w{25})/$', 'definir_metadatos_user', name="definir_metadatos_user"),
url(r'^definir_metadatos/(?P<video_id>\d+)/$', 'definir_metadatos_oper', name="definir_metadatos_oper"),
url(r'^estado_video/(?P<video_id>\d+)/$', 'estado_video', name="estado_video"),
url(r'^estado_coleccion/(?P<coleccion_id>\d+)/$', 'estado_coleccion', name="estado_coleccion"),
url(r'^validar_produccion/(?P<video_id>\d+)/$', 'validar_produccion', name="validar_produccion"),
url(r'^reemplazar/(?P<video_id>\d+)/$', 'reemplazar_video', name="reemplazar_video"),
url(r'^media_info/(?P<video_id>\d+)/$', 'media_info', name="media_info"),
url(r'^download_media_info/(?P<video_id>\d+)/$', 'download_media_info', name="download_media_info"),
url(r'^gestion_tickets/(?P<video_id>\d+)/$', 'gestion_tickets', name="gestion_tickets"),
url(r'^regenerar_tickets/$', 'regenerar_tickets', name="regenerar_tickets"),
url(r'^archivar_desarchivar/$', 'archivar_desarchivar', name="archivar_desarchivar"),
url(r'^editar/(?P<video_id>\d+)/$', 'editar_produccion', name="editar"),
url(r'^borrar/(?P<video_id>\d+)/$', 'borrar_produccion', name="borrar"),
url(r'^borrar_coleccion/(?P<coleccion_id>\d+)/$', 'borrar_coleccion', name="borrar_coleccion"),
url(r'^notificar/(?P<record_id>\d+)/$', 'notificar_publicacion', name="notificar_publicacion"),
url(r'^borrar_registro/(?P<record_id>\d+)/$', 'borrar_registro', name="borrar_registro"),
url(r'^aprobacion_video/(?P<tk_str>\w{25})/$', 'aprobacion_video', name="aprobacion_video"),
url(r'^rechazar_video/(?P<tk_str>\w{25})/$', 'rechazar_video', name="rechazar_video"),
url(r'^stream/(?P<video_id>\d+).mp4$', 'stream_video', name="stream_video"),
url(r'^download/(?P<video_id>\d+).mp4$', 'download_video', name="download_video"),
url(r'^stream/(?P<tk_str>\w{25}).flv$', 'stream_preview', name="stream_preview"),
url(r'^enproceso/$', 'listar_en_proceso', name="enproceso"),
url(r'^enproceso/(?P<operator_id>\d+)/$', 'listar_en_proceso', name="enproceso"),
url(r'^pendientes/$', 'listar_pendientes', name="pendientes"),
url(r'^log/$', 'showlog', name='log'),
url(r'^oldlog/$', 'showlog', { 'old' : True }, name="oldlog"),
url(r'^alertas/$', 'alerts', name="alertas"),
url(r'^config/$', 'config_settings', name="config"),
url(r'^config_mail/$', 'config_settings', {'mail': True}, name="config_mail"),
url(r'^status/$', 'status', name="status"),
url(r'^videoteca/$', 'videoteca', name="videoteca"),
url(r'^colecciones/$', 'colecciones', name="colecciones"),
url(r'^estadisticas/$', 'estadisticas', name="estadisticas"),
url(r'^ultimas/$', 'ultimas_producciones', name="ultimas"),
)
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('postproduccion', '0006_metadatagen_transcription'),
]
operations = [
migrations.AlterField(
model_name='metadatagen',
name='transcription',
field=models.TextField(null=True, verbose_name='Transcripci\xf3n', blank=True),
),
]
| 327bb5a8ae71c64a40a19c0c7130796ec7e3b85e | [
"JavaScript",
"Python",
"HTML",
"Markdown"
] | 23 | HTML | cjgonza/dpCat | 99f71805f3a913574dfa579a0e8d4a5db74b41cf | 28778e08b23d37404e8fc0cc7f3c0a0ccee17121 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpScript : MonoBehaviour
{
public GameObject shieldUI;
public GameObject shield;
//public GameObject shieldPickUp;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("PickUp"))
{
other.gameObject.SetActive(false);
shieldUI.SetActive(true);
}
}
void Update()
{
if (shieldUI.activeSelf == true)
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
shield.SetActive(true);
shieldUI.SetActive(false);
StartCoroutine(ShieldOff());
}
}
}
IEnumerator ShieldOff()
{
{
yield return new WaitForSeconds(5);
shield.SetActive(false);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using UnityEngine;
public class EnemyFollow : MonoBehaviour
{
public float enemySpeed;
//public float gravity;
private void FixedUpdate()
{
//GetComponent<Rigidbody>().AddForce(0, gravity, 0);
transform.position += Vector3.right * enemySpeed * Time.deltaTime;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatypusRunAnim : MonoBehaviour
{
public GameObject enemy;
void Start()
{
enemy.GetComponent<Animation>().Play();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class dirtEmission : MonoBehaviour
{
public Transform dirt;
public AudioSource dirtSource;
void Start()
{
dirt.GetComponent<ParticleSystem>().Stop();
dirtSource = GetComponent<AudioSource>();
}
private void OnTriggerEnter(Collider other)
{
dirt.GetComponent<ParticleSystem>().Play();
dirtSource.Play();
StartCoroutine(stopDirt());
}
IEnumerator stopDirt()
{
yield return new WaitForSeconds(1f);
dirt.GetComponent<ParticleSystem>().Stop();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SnowballSubtractSpeed : MonoBehaviour
{
public GameObject Snowball;
private EnemyFollow EnemyFollowScript;
public float newSpeed = 16;
private void OnTriggerEnter(Collider other)
{
EnemyFollowScript = Snowball.GetComponent<EnemyFollow>();
if (EnemyFollowScript.enemySpeed >= 19)
{
EnemyFollowScript.enemySpeed = newSpeed;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMove : MonoBehaviour
{
public float speed = 6.0f;
public float jumpSpeed = 10.0f;
public float gravity = -9.81f;
private Vector3 moveDirection = Vector3.zero;
private CharacterController controller;
private void Start()
{
controller = GetComponent<CharacterController>();
gameObject.transform.position = new Vector3(3,5,62);
}
private void FixedUpdate()
{
if (controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection = moveDirection * speed;
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
moveDirection.y = moveDirection.y - (gravity * Time.deltaTime);
controller.Move(moveDirection * Time.deltaTime);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterAnim : MonoBehaviour
{
private Animator anim;
public AudioSource squeekSource;
void Start()
{
anim = GetComponent<Animator>();
//squeekSource = GetComponent<AudioSource>();
}
void Update()
{
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
{
anim.SetBool("isRunning", true);
//squeekSource.enabled = true;
//squeekSource.loop = true;
}
else
{
anim.SetBool("isRunning", false);
//squeekSource.enabled = false;
//squeekSource.loop = false;
}
if (Input.GetKey(KeyCode.Space))
{
anim.SetTrigger("jump");
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BeakAnimation : MonoBehaviour
{
public void BeakPlay()
{
gameObject.GetComponent<Animation>().Play();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEngine;
public class Enlarger : MonoBehaviour
{
void Start ()
{
StartCoroutine(Grow());
}
IEnumerator Grow()
{
transform.localScale += new Vector3(0.5f, 0.5f, 0.5f);
yield return null;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Beak_Trigger : MonoBehaviour
{
public BeakAnimation anim;
public GameObject beak;
public AudioSource beakSource;
private void Start()
{
beakSource = GetComponent<AudioSource>();
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
anim.BeakPlay();
StartCoroutine(beakSound());
}
}
IEnumerator beakSound()
{
yield return new WaitForSeconds(.25f);
beakSource.Play();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEditor.Experimental.Animations;
using UnityEngine;
public class IcicleSpawn : MonoBehaviour
{
public GameObject icicle;
public Transform icicleSpawn;
public float fireRate;
private float nextFire;
void Update ()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(icicle, icicleSpawn.position, icicleSpawn.rotation);
Destroy(GameObject.Find("Icicle_Main(Clone)"), 1);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class HunterTrapTrigger : MonoBehaviour
{
public Transform Player;
//public Transform RespawnPoint;
private PlayerHealth playerHealthScript;
public float damage = 2;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
GetComponent<Animation>().Play();
PlayerHealth p = Player.GetComponent<PlayerHealth>();
p.TakeDamage(damage);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
public class PlatypusSetActive : MonoBehaviour
{
public GameObject platypus;
public GameObject platypus2;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
platypus.SetActive(true);
}
if (other.gameObject.CompareTag("Player"))
{
platypus2.SetActive(false);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using UnityEngine;
public class DamageSystem : MonoBehaviour
{
[SerializeField] private float beakDamage;
[SerializeField] private HealthSystem healthController;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
Damage();
}
if (other.gameObject.CompareTag("Enemy"))
{
Damage();
}
}
void Damage()
{
healthController.playerHealth = healthController.playerHealth - beakDamage;
healthController.UpdateHealth();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMove : MonoBehaviour
{
public float speed = 6.0f;
public float jumpSpeed = 10.0f;
public float gravity = -9.81f;
public AudioSource boingSource;
//public float moveX;
//public float moveY;
//public float moveZ;
private Vector3 moveDirection = Vector3.zero;
private CharacterController controller;
private void Start()
{
controller = GetComponent<CharacterController>();
gameObject.transform.position = new Vector3(-100, 9, -3.2f);
boingSource = GetComponent<AudioSource>();
}
private void FixedUpdate()
{
if (controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection = moveDirection * speed;
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
boingSource.Play();
}
}
moveDirection.y = moveDirection.y - (gravity * Time.deltaTime);
controller.Move(moveDirection * Time.deltaTime);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class WinScript : MonoBehaviour
{
public GameObject restartButton;
public GameObject mainMenuButton;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
restartButton.SetActive(true);
mainMenuButton.SetActive(true);
}
}
public void Restart()
{
SceneManager.LoadScene(1);
}
public void MainMenu()
{
SceneManager.LoadScene(0);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerHealth : MonoBehaviour
{
private float health;
public float startHealth = 100;
public Image healthBar;
private void Start()
{
health = startHealth;
}
public void TakeDamage(float amount)
{
health -= amount;
healthBar.fillAmount = health / startHealth;
if (health <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyDamage : MonoBehaviour
{
public GameObject Player;
private PlayerHealth playerHealthScript;
public float damage = 10;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
PlayerHealth p = Player.GetComponent<PlayerHealth>();
p.TakeDamage(damage);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SnowballSetActive : MonoBehaviour
{
public GameObject Snowball;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Snowball.SetActive(true);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyIcicles : MonoBehaviour {
float lifetime = 3.0f;
void Start()
{
Destroy (gameObject, lifetime);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCharacter : MonoBehaviour
{
public float moveSpeed = 5;
public float Gravity = 20.0f;
public float jumpSpeed = 8.0f;
private Vector3 moveDirection = Vector3.zero;
private CharacterController controller;
private Vector3 position;
// Use this for initialization
void Start ()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void FixedUpdate()
{
position.x = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
position.y = Gravity * Time.deltaTime;
controller.Move(position);
if (controller.isGrounded)
{
if (Input.GetKey(KeyCode.Space))
{
moveDirection.y = jumpSpeed;
}
}
moveDirection.y = moveDirection.y - (Gravity * Time.deltaTime);
controller.Move(moveDirection * Time.deltaTime);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoundrySetActive : MonoBehaviour
{
public GameObject Boundry;
// Start is called before the first frame update
void Start()
{
Boundry.SetActive(true);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Snow_Explosion : MonoBehaviour
{
public GameObject Snowball;
public Transform DestroyTrigger;
public GameObject Explosion;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Snowball"))
{
Instantiate(Explosion, DestroyTrigger.position, DestroyTrigger.rotation);
Destroy(Snowball);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class HealthSystem : MonoBehaviour
{
public float playerHealth;
[SerializeField] private Text healthText;
public GameObject restartButton;
public GameObject mainMenuButton;
public void UpdateHealth()
{
healthText.text = playerHealth.ToString("0");
if (playerHealth <= 0)
{
restartButton.SetActive(true);
mainMenuButton.SetActive(true);
}
}
public void Restart()
{
SceneManager.LoadScene(1);
}
public void MainMenu()
{
SceneManager.LoadScene(0);
}
}
| 9b10a4144b07dedbe49fb599a39aacfa77995e2c | [
"C#"
] | 24 | C# | jonnyrogers24/UVU_SPRING_2019 | 417203e59e1e8fa606e54204268d83fa1d21196b | aad581a3585a760bbabfcd82b6d6c24222d4fb4e |
refs/heads/main | <repo_name>hanielchang/password-generator<file_sep>/README.md
# Password Generator
## Goals for this Challenge
* Create a functional password generator of random characters
* Prompt the user for criteria and verify that minimum requirements have been met
* Display the user selected password to the display box in HTML
## List of implemented functions - Three functions total
* First we have the writePassword(). This simply writes the password to the display box
* Then we have a generatePasswordContent function which prompts and creates the password as a string
* Finally we have a generatePasswordLength that prompts for a password of certain desired length.
## Summary of code
* All of the characters upper, lower, numbers, and special were put into arrays. The arrays were
used and concatenated as needed based on criteria via prompts inside generatePasswordContent. The password length
was prompeted as well, and that value was prompted inside generatePasswordLength. The
resulting random password created there in the generatePasswordContent was passed into writePassword
to be displayed.
<file_sep>/assets/js/script.js
// Lower case, upper case, and numbers arrays
const lowerCase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
const upperCase = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
const numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
// For neatness, I chose to seperate the special characters by similarity (via their codenames) in 5 arrays. I then concatenated the 5 arrays into one
const part1 = ["\u0020","\u0021","\u0022","\u0023","\u0024","\u0025","\u0026","\u0027","\u0028","\u0029"];
const part2 = ["\u002A","\u002B","\u002C","\u002D","\u002E","\u002F"];
const part3 = ["\u003A","\u003B","\u003C","\u003D","\u003E","\u003F"];
const part4 = ["\u0040","\u005B","\u005C","\u005D","\u005E","\u005F"];
const part5 = ["\u0060","\u007B","\u007C","\u007D","\u007E"];
const specialChars = part1.concat(part2,part3,part4,part5);
// Get references to the #generate element
var generateBtn = document.querySelector("#generate");
// Write password to the #password input
function writePassword() {
var password = generatePasswordContent();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
function generatePasswordContent() {
var options = [];
var wantsLowerCase = window.confirm("Would you like lower case letters?");
var wantsUpperCase = window.confirm("Would you like upper case letters?");
var wantsNumbers = window.confirm("Would you like numbers?");
var wantsSpecialChars = window.confirm("Would you like special characters?");
// Here we do a recursive call. Variable string holds the value when we convert to base case
if (!wantsLowerCase && !wantsUpperCase && !wantsNumbers && !wantsSpecialChars) {
window.alert("You must select at least one character type! Please try again.");
var string = generatePasswordContent();
return string;
}
if (wantsLowerCase){
options = options.concat(lowerCase);
}
if (wantsUpperCase){
options = options.concat(upperCase);
}
if (wantsNumbers){
options = options.concat(numbers);
}
if (wantsSpecialChars){
options = options.concat(specialChars);
}
// Creating and verifying the password meets length requirements. Value received from function call.
var passwordLength = generatePasswordLength();
var password = '';
// This for loop generates the random password
for (let count = 0; count < passwordLength; count++) {
index = Math.floor(Math.random() * options.length);
randomChar = options[index]
password = <PASSWORD>.concat(randomChar);
}
return password;
};
function generatePasswordLength() {
var length = window.prompt("How long would you like your password to be? Please choose between a length of 8 to 128 characters.");
length = parseInt(length);
// Here we do a recursive call, again with the variable 'number' to hold the value when we reach the base case
if ((length < 8) || (length > 128) || Number.isNaN(length)) {
window.alert("Password does not meet length requirements. Please try again.");
var number = generatePasswordLength();
return number;
}
else {
window.alert("You have selected a password length of " + length + " characters.");
return length;
}
};
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
| af1e7104f05a41d5ee578da88e9e862fdd507f68 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | hanielchang/password-generator | c9fc742a65516a683456eb4fcea797f83cc5aba1 | 0b5aa569f6b565edf5f9c1bec73ecf05eeba4364 |
refs/heads/master | <repo_name>techniq/react-move<file_sep>/README.md
<div style="text-align:center;">
<a href="https://github.com/react-tools/react-move" target="\_parent"><img src="https://github.com/react-tools/media/raw/master/logo-react-move.png" alt="React Table Logo" style="width:450px;"/></a>
</div>
# React-Move
Beautiful, data-driven animations for React.
### Go to [live examples, code and docs](https://react-move.js.org)!
<a href="https://npmjs.com/package/react-move">
<img alt="" src="https://img.shields.io/npm/dm/react-move.svg" />
</a>
<a href="https://react-chat-signup.herokuapp.com/">
<img alt="" src="https://img.shields.io/badge/slack-react--tools-blue.svg" />
</a>
<a href="https://github.com/react-tools/react-move">
<img alt="" src="https://img.shields.io/github/stars/react-tools/react-move.svg?style=social&label=Star" />
</a>
<a href="https://twitter.com/react-tools">
<img alt="" src="https://img.shields.io/twitter/follow/react-tools.svg?style=social&label=Follow" />
</a>
<a href="https://cdnjs.com/libraries/react-move">
<img alt="" src="https://img.shields.io/cdnjs/v/react-move.svg" />
</a>
<a href="https://www.npmjs.com/package/react-move">
<img alt="" src="https://img.shields.io/npm/v/react-move.svg" />
</a>
## Features
- **17kb!** (gzipped)
- Supported in React, React-Native & React-VR
- Animate anything. HTML, SVG, React-Native
- Prop-level delays & duration customization
- Animation lifecycle events eg. (start, interrupt, end)
- Custom easing & tweening functions
- Supports interpolation of
- Numbers
- Colors
- SVG paths
- Any string with embedded numbers
- Arrays of any of these
- Objects of any of these
- Arrays of objects of any of these... you get the point
- Anything [d3-interpolate](https://github.com/d3/d3-interpolate) can handle
## Demos
- [CodeSandbox](https://codesandbox.io/s/j4mv3lvj6v)
- [Examples](https://react-move.js.org)
## Installation
```bash
$ yarn add react-move
# or
$ npm install react-move
```
##### CDN
```html
<script src='https://npmcdn.com/react-move@latest/react-move.js'></script>
```
# Documentation
The docs below are for version **2.x.x** of React-Move.
Older versions:
- [Version 1.x.x](https://github.com/react-tools/react-move/tree/v1.6.1)
## < NodeGroup />
The NodeGroup component allows you to create complex animated transitions. You pass it an array of objects and a key accessor function and it will run your enter, update and leave transitions as the data updates.
The idea is similar to transition components like [react-transition-group](https://github.com/reactjs/react-transition-group) or [react-motion's TransitionMotion](https://github.com/chenglou/react-motion) but you use objects to express how you want your state to transition.
Not only can you can have independent duration, delay and easing for entering, updating and leaving but each individual key in your state can define its own timing!
### Component Props
| Name | Type | Default | Description |
|:-----|:-----|:-----|:-----|
| <span style="color: #31a148">data *</span> | Array | | An array of data objects. The data prop is treated as immutable so the nodes will only update if prev.data !== next.data. |
| <span style="color: #31a148">keyAccessor *</span> | function | | Function that returns a string key given a data object and its index. Used to track which nodes are entering, updating and leaving. |
| <span style="color: #31a148">start *</span> | function | | A function that returns the starting state. The function is passed the data and index and must return an object. |
| enter | function | () => {} | A function that **returns an object or array of objects** describing how the state should transform on enter. The function is passed the data and index. |
| update | function | () => {} | A function that **returns an object or array of objects** describing how the state should transform on update. The function is passed the data and index. |
| leave | function | () => {} | A function that **returns an object or array of objects** describing how the state should transform on leave. The function is passed the data and index. |
| <span style="color: #31a148">children *</span> | function | | A function that renders the nodes. It should accept an array of nodes as its only argument. Each node is an object with the key, data, state and a type of 'ENTER', 'UPDATE' or 'LEAVE'. |
* required props
### Usage
Go to [live examples, code and docs](https://react-move.js.org)!
A typical usage of NodeGroup looks like this...
```js
<NodeGroup
data={this.state.data} // array of data objects (required)
keyAccessor={(d) => d.name} // function to get the key of each object (required)
start={(data, index) => ({ // returns the starting state of node (required)
...
})}
enter={(data, index) => ({ // how to transform node state on enter - runs immediately after start (optional)
...
})}
update={(data, index) => ({ // how to transform node state on update - runs each time data updates and key remains (optional)
...
})}
leave={(data, index) => ({ // how to transform node state on leave - run when data updates and key is gone (optional)
...
})}
>
{(nodes) => ( // the only child of NodeGroup should be a function to render the nodes (required)
...
{nodes.map(({ key, data, state }) => {
...
})}
...
)}
</NodeGroup>
```
### Transitions
Go to [live examples, code and docs](https://react-move.js.org)!
```js
<NodeGroup
data={this.state.data}
keyAccessor={(d) => d.name}
// start - starting state of the node. Just return an object.
start={(data, index) => ({
opacity: 1e-6,
x: 1e-6,
fill: 'green',
width: scale.bandwidth(),
})}
// enter - return an object or array of objects describing how to transform the state.
enter={(data, index) => ({
opacity: [0.5], // transition opacity on enter
x: [scale(data.name)], // transition x on on enter
timing: { duration: 1500 }, // timing for transitions
})}
update={(data) => ({
...
})}
leave={() => ({
...
})}
>
{(nodes) => (
...
)}
</NodeGroup>
```
You return an object or an array of objects in your **enter**, **update** and **leave** functions.
Instead of simply returning the next state these objects describe how to transform the state.
This is far more powerful than just returning a state object. By approaching it this way, you can describe really complex transformations and handle interrupts easily.
If you're familiar with D3, this approach mimics selection/transition behavior. In D3 your are really describing how the state should look on enter, update and exit and how to get there: set the value immediately or transition to it.
D3 deals with the fact that transitions might be in-flight or the key is already at that value in the background without you having to worry about that.
The NodeGroup takes the same approach but it's done in idiomatic React.
Each object returned from your enter, update and leave functions can specify its own duration, delay, easing and events independently.
To support that, inside your object there are two special keys you can use: **timing** and **events**. Both are optional.
Timing and events are covered in more detail below.
The rest of the keys in each object are assumed to be keys in your state.
If you aren't transitioning anything then it wouldn't make sense to be using NodeGroup.
That said, like in D3, it's also convenient to be able to set a key to value when a node enters, updates or leaves without transitioning.
To support this you can return four different types of values to specify how you want to transform the state.
* `string or number`: Set the key to the value immediately with no transition.
* `array [value]`: Transition from the key's current value to the specified value. Value is a string or number.
* `array [value, value]`: Transition from the first value to the second value. Each value is a string or number.
* `function`: Function will be used as a custom tween function.
In all cases above a "string" can be a color, path, transform (the key must be called "transform" see below), etc and it will be interpolated using the correct interpolator.
See the interpolators section below.
## Timing
Go to [live examples, code and docs](https://react-move.js.org)!
If there's no timing key in your object you'll get the timing defaults.
You can specify just the things you want to override on your timing key.
Here's the timing defaults...
```js
const defaultTiming = {
delay: 0,
duration: 250,
ease: easeLinear,
};
```
For the ease key, just provide the function. You can use any easing function, like those from d3-ease...
[List of ease functions exported from d3-ease](https://github.com/d3/d3-ease/blob/master/index.js)
## Passing an array of objects
Go to [live examples, code and docs](https://react-move.js.org)!
Each object can define its own timing and it will be applied to any transitions in the object.
```js
import { easeQuadInOut } from 'd3-ease';
...
<NodeGroup
data={this.state.data}
keyAccessor={(d) => d.name}
// start - starting state of the node. Just return an object.
start={(data, index) => ({
opacity: 1e-6,
x: 1e-6,
fill: 'green',
width: scale.bandwidth(),
})}
// enter - return an object or array of objects describing how to transform the state.
enter={(data, index) => ([ // An array
{
opacity: [0.5], // transition opacity on enter
timing: { duration: 1000 }, // timing for transition
},
{
x: [scale(data.name)], // transition x on on enter
timing: { delay: 750, duration: 1500, ease: easeQuadInOut }, // timing for transition
},
])}
update={(data) => ({
...
})}
leave={() => ({
...
})}
>
{(nodes) => (
...
)}
</NodeGroup>
```
## Contributing
We love contributions from the community! Read the [contributing info here](https://github.com/react-tools/react-move/blob/master/CONTRIBUTING.md).
#### Run the repo locally
- Fork this repo
- `npm install`
- `cd docs`
- `npm install`
- `npm start`
#### Scripts
Run these from the root of the repo
- `npm run lint` Lints all files in src and docs
- `npm run test` Runs the test suite locally
- `npm run test:coverage` Get a coverage report in the console
- `npm run test:coverage:html` Get an HTML coverage report in coverage folder
Go to [live examples, code and docs](https://react-move.js.org)!
<file_sep>/docs/src/routes/examples/Simple/index.js
// @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import CodeExample from 'docs/src/components/CodeExample';
import Bars1 from './Bars1';
import Bars2 from './Bars2';
import Bars3 from './Bars3';
import Circles from './Circles';
const Example = (props) => {
const { route: { exampleContext } } = props;
return (
<div>
<CodeExample
code={exampleContext('./Simple/Bars1')}
title="Example 1: Simple Bars"
>
<Bars1 />
</CodeExample>
<CodeExample
code={exampleContext('./Simple/Bars2')}
title="Example 2: Bars w/ More Complex Timing"
>
<Bars2 />
</CodeExample>
<CodeExample
code={exampleContext('./Simple/Bars3')}
title="Example 3: Passing Arrays of Transitions"
>
<Bars3 />
</CodeExample>
<CodeExample
code={exampleContext('./Simple/Circles')}
title="Example 4: Namespacing State"
>
<Circles />
</CodeExample>
</div>
);
};
Example.propTypes = {
route: PropTypes.object.isRequired,
};
export default Example;
| b24fa815506fd34028e5df55a5ceb04e18dd722e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | techniq/react-move | dc17d83ffa7565def729b2bdd17b056235d4b862 | 7163e79d772d6852358f3b3defe38629538fd0e7 |
refs/heads/master | <file_sep># rspec spec/models/tracking_referer_spec.rb
RSpec.describe Tracking::Referer, :type => :model do
let(:referer) { FactoryGirl.create(:tracking_referer) }
before :all do
Tracking::Referer.destroy_all
end
describe "Spec" do
it "should have a valid base factory" do
expect(referer).to be_valid
end
end
describe "#parse" do
before :all do
@referer = FactoryGirl.create(:tracking_referer, :empty)
end
it "sets scheme correctly" do
expect(@referer.scheme).to eq "http"
end
it "sets host correctly" do
expect(@referer.host).to eq "lvh.me"
end
it "sets port correctly" do
expect(@referer.port).to eq 3000
end
it "sets path correctly" do
expect(@referer.path).to eq "/levels/1/show"
end
it "sets query correctly" do
expect(@referer.query).to eq "get_param_1=1&get_param_2=1"
end
end
end
<file_sep>class Tracking::Referer < ActiveRecord::Base
attr_accessible :scheme, :host, :port, :path, :query, :url, :tracking_logs
has_many :tracking_logs, class_name: "Tracking::Log"
before_create :parse
validates :url, presence: {message: ":url missing!"}, uniqueness: {message: "already taken!"}
def parse
referer = URI.parse(url)
self.scheme = referer.scheme
self.host = referer.host
self.port = referer.port
self.path = referer.path
self.query = referer.query
end
end
<file_sep>$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "creative_tracking/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "creative_tracking"
s.version = CreativeTracking::VERSION
s.authors = ["Epigene"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/CreativeMobile/activity_tracker"
s.summary = "Adds user activity tracking infrastucture"
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "rails", "~> 4.1.2"
s.add_dependency 'protected_attributes'
s.add_development_dependency "rake", '~> 10.5.0'
s.add_development_dependency "rspec-rails"
s.add_development_dependency 'factory_girl_rails'
s.add_development_dependency "pry"
s.add_development_dependency "timecop"
s.add_development_dependency "pg", "~> 0.18.4"
end
<file_sep>module CreativeTracking
VERSION = "0.0.4.1"
end
<file_sep>class TrackingLogs < ActiveRecord::Migration
def change
change_table :tracking_logs do |t|
t.references :user, index: true unless column_exists?(:tracking_logs, :user_id)
t.references :tracking_referer, index: true unless column_exists?(:tracking_logs, :tracking_referer_id)
t.string :to, index: true unless column_exists?(:tracking_logs, :to)
t.string :controller_name, index: true unless column_exists?(:tracking_logs, :controller_name)
t.string :action_name, index: true unless column_exists?(:tracking_logs, :action_name)
t.references :tracking_activity, index: true unless column_exists?(:tracking_logs, :tracking_activity_id)
t.integer :time_since_last_log unless column_exists?(:tracking_logs, :time_since_last_log)
t.timestamps null: false unless column_exists?(:tracking_logs, :created_at)
end
end
end<file_sep>FactoryGirl.define do
factory :tracking_referer, class: Tracking::Referer do
sequence(:url, 1) { |n| "http://lvh.me:3000/test/#{n}/show?get_param_1=1&get_param_2=1" }
trait :empty do
url "http://lvh.me:3000/levels/1/show?get_param_1=1&get_param_2=1"
end
trait :filled do
url "http://lvh.me:3000/levels/1/show?get_param_1=1&get_param_2=1"
scheme "http"
host "lvh.me"
port 3000
path "/levels/1/show"
query "get_param_1=1&get_param_2=1"
end
end
end
<file_sep>class TrackingActivities < ActiveRecord::Migration
def change
change_table :tracking_activities do |t|
t.string :name unless column_exists?(:tracking_activities, :name)
t.string :path, null: false, unique: true unless column_exists?(:tracking_activities, :path)
end
end
end<file_sep>require "creative_tracking/engine"
require "creative_tracking/tracking_ext"<file_sep>class TrackingReferers < ActiveRecord::Migration
def change
change_table :tracking_referers do |t|
t.string :scheme unless column_exists?(:tracking_referers, :scheme)
t.string :host unless column_exists?(:tracking_referers, :host)
t.integer :port unless column_exists?(:tracking_referers, :port)
t.text :path unless column_exists?(:tracking_referers, :path)
t.text :query unless column_exists?(:tracking_referers, :query)
t.text :url, null: false unless column_exists?(:tracking_referers, :url)
end
end
end
<file_sep>ENV['RAILS_ENV'] = 'test'
require 'protected_attributes'
require 'pry'
require 'factory_girl'
require 'timecop'
require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'
ENGINE_ROOT = File.expand_path("..", File.dirname(__FILE__))
require "#{ENGINE_ROOT}/spec/dummy/config/environment"
# load factories (using root)
Dir[File.join(ENGINE_ROOT, "spec/factories/**/*.rb")].each {|f| require f }
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
<file_sep>class Tracking::Log < ActiveRecord::Base
attr_accessible :user_id, :user, :tracking_referer_id, :tracking_referer, :to, :controller_name, :action_name, :tracking_activity_id, :tracking_activity, :time_since_last_log
belongs_to :user
belongs_to :tracking_referer, class_name: "Tracking::Referer"
belongs_to :tracking_activity, class_name: "Tracking::Activity"
validates :user_id, presence: {message: "must be assigned to user!"}
validates :to, presence: {message: ":to missing!"}
scope :in_daterange, ->(start_date, end_date) { where(created_at: start_date.to_date.beginning_of_day..end_date.to_date.end_of_day) }
scope :with_activity, ->(id) { where(tracking_activity_id: id) }
def to_s
tracking_activity.present? ? "#{self.to} | #{tracking_activity.name}" : "#{self.to}"
end
def self.make_new_log request, params, session
@user = User.includes(:tracking_logs).find(session["user_id"])
logs = @user.tracking_logs
time_since_last_log = (logs.any? ? (Time.now.to_i - logs.last.created_at.to_i) : -1 )
# 1. pielasīt aktivitāti no :to satura
@activity = Tracking::Activity.find_activity_by_url(request.url)
# 2. uztaisīt referer
@referer_id = Tracking::Referer.where(url: request.env["HTTP_REFERER"]).first_or_create.id if request.env["HTTP_REFERER"].present?
# 3. uztaisīt logu
tracking_log_hash = {
user_id: session["user_id"],
tracking_referer_id: @referer_id,
to: request.url,
controller_name: params[:controller],
action_name: params[:action],
tracking_activity_id: @activity.id,
time_since_last_log: time_since_last_log
}
@log = Tracking::Log.create(tracking_log_hash)
raise "FailedToMakeTrackingLog" unless @log
return @log
end
end
<file_sep>class Tracking::Activity < ActiveRecord::Base
attr_accessible :name, :tracking_logs
has_many :tracking_logs, class_name: Tracking::Log
validates :name, uniqueness: {message: "already taken!"}, presence: {message: "missing!"}
# FALSE SCOPES, return objects, not collections
scope :dummy, -> { find_by(name: "Dummy") }
#scope :login, -> { find_by(path: "/user_program") }
def self.login
return find_by(path: '/user_program')
end
def self.find_activity_by_url(url)
uri = URI.parse(url)
activity = Tracking::Activity.find_by(path: uri.path)
activity.present? ? activity : Tracking::Activity.dummy
end
end
<file_sep>Rails.application.routes.draw do
mount CreativeTracking::Engine => "/creative_tracking"
end
<file_sep>module TrackingExt
extend ActiveSupport::Concern
included do
helper_method :track_user_activity
before_filter :track_user_activity
end
def track_user_activity
session_hash = session.keys.inject(Hash.new){|hash, key| hash[key] = session[key] ; hash }
@current_tracking_log ||= Tracking::Log.make_new_log(request, params, session_hash) if session[:user_id].present?
end
end<file_sep># Creative Tracking
## Setup
1. `gem 'creative_tracking'` and `bundle`
2. `bundle exec rake railties:install:migrations db:migrate`
2. `include TrackingExt` in trackable controllers
3. Use session[:user_id]
4. Use User model
`has_many :tracking_logs, class_name: "Tracking::Log", dependent: :destroy`
5. Make seeds
```ruby
Tracking::Activity.where(name: "Dummy", path: "").first_or_create # TO-DO: Populate this with a list of actual activities
Tracking::Activity.where(name: "Atvēra levels home", path: "/levels").first_or_create`
```
## Usage
Gem exposes three models
```ruby
Tracking::Activity
Tracking::Log
Tracking::Referer
```
<file_sep>module Tracking
def self.table_name_prefix
'tracking_'
end
end
<file_sep>class InitializeModels < ActiveRecord::Migration
def change
[:tracking_activities, :tracking_logs, :tracking_referers].each do |table|
create_table(table) unless table_exists?(table)
end
end
end
| 6a202d86a6bdf8594adb5622c880b0fcb00df2d8 | [
"Markdown",
"Ruby"
] | 17 | Ruby | CreativeMobile/activity_tracker | 8dee86824d307fdfadb9bda6a09a128d9a3a7fe9 | c24b66e0f4da8a893480f73db710c217bda95a57 |
refs/heads/master | <repo_name>rafaelfelipesantos/prototype-ecommerce<file_sep>/app/Helper/ProxyFactory.js
/**
* ProxyFactory:
*/
export default class ProxyFactory {
static create(instance, props, callback) {
return new Proxy(instance, {
get(target, property, receiver) {
const method = Reflect.get(...arguments);
if (typeof method === 'function' && props.includes(property)) {
return function(...args) {
Reflect.apply(method, target, args);
callback(target);
}
}
return Reflect.get(...arguments);
},
set(target, property, value, receiver) {
return Reflect.set(...arguments);
}
});
}
}
<file_sep>/app/index.js
'use strict';
import CartController from './Controller/CartController.js';
new CartController();
<file_sep>/app/Service/ProductService.js
import HttpService from './HttpService.js';
import GhostDB from '../Helper/GhostDB.js';
import Product from '../Model/Product.js';
/**
* ProductService:
*/
export default class ProductService {
constructor() {
this._http = new HttpService('./data/products.json');
this._db = new GhostDB('ecommerce', 1);
}
async importProductsFromDB() {
try {
const data = await this._db.findAll('products');
return data.map(product => new Product(
product._id,
product._photo,
product._title,
product._price,
product._amount
));
} catch (e) {
console.warn(e.toString());
}
}
async findAll() {
try {
return await this._http.findAll();
} catch (e) {
console.warn(e.toString());
}
}
async findById(id) {
try {
const data = await this._http.findById(id);
return new Product(
data.id,
data.photo,
data.title,
data.price,
data.amount
);
} catch (e) {
console.warn(e.toString());
}
}
async insert(product) {
try {
return await this._db.insert('products', product);
} catch (e) {
console.warn(e.toString());
}
}
async update(object) {
try {
return await this._db.update('products', object);
} catch (e) {
console.warn(e.toString());
}
}
async delete(id) {
try {
return await this._db.delete('products', id);
} catch (e) {
console.warn(e.toString());
}
}
}
<file_sep>/app/Helper/GhostDB.js
/**
* GhostDB: Abstraction layer for offline first application
*/
export default class GhostDB {
constructor(dbName, dbVersion) {
this._dbName = dbName;
this._dbVersion = dbVersion;
}
async _openATransaction(store, mode) {
try {
const request = await this.open(store);
const transaction = request.transaction([store], mode);
return transaction.objectStore(store);
} catch (e) {
console.warn(e.toString());
}
}
open(store) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this._dbName, this._dbVersion);
request.addEventListener('upgradeneeded', event => {
const db = event.target.result;
if (db.objectStoreNames.contains(store))
db.deleteObjectStore(store);
db.createObjectStore(store, {
autoIncrement: true,
keyPath: '_id'
});
}, false);
request.addEventListener('success', event =>
resolve(event.target.result), false);
request.addEventListener('error', event =>
reject(event.target.error), false);
});
}
insert(store, object) {
return new Promise((resolve, reject) => {
this._openATransaction(store, 'readwrite')
.then(objectStore => {
const request = objectStore.add(object);
request.addEventListener('success', event =>
resolve(object), false);
request.addEventListener('error', event =>
reject(event.target.result), false);
});
});
}
findAll(store) {
return new Promise((resolve, reject) => {
this._openATransaction(store, 'readonly')
.then(objectStore => {
const request = objectStore.openCursor();
const items = [];
request.addEventListener('success', event => {
const cursor = event.target.result;
if (!(cursor && items.push(cursor.value)))
return resolve(items);
cursor.continue();
}, false);
request.addEventListener('error', event =>
reject(event.target.error), false);
});
});
}
findById(store, id) {
return new Promise((resolve, reject) => {
this._openATransaction(store, 'readonly')
.then(objectStore => {
const request = objectStore.get(id);
request.addEventListener('success', event =>
resolve(event.target.result), false);
request.addEventListener('error', event =>
reject(event.target.error), false);
});
});
}
update(store, object) {
return new Promise((resolve, reject) => {
this._openATransaction(store, 'readwrite')
.then(objectStore => {
const request = objectStore.put(object);
request.addEventListener('success', event =>
resolve(event.target.result), false);
request.addEventListener('success', event =>
reject(event.target.error), false);
});
});
}
delete(store, id) {
return new Promise((resolve, reject) => {
this._openATransaction(store, 'readwrite')
.then(objectStore => {
const request = objectStore.delete(id);
request.addEventListener('success', event =>
resolve(id), false);
request.addEventListener('error', event =>
reject(event.target.error), false);
});
});
}
}
<file_sep>/app/Model/Cart.js
import Product from './Product.js';
import CouponOfDiscount from './CouponOfDiscount.js';
/**
* Cart:
*/
export default class Cart {
constructor() {
this._items = [];
this._total = 0;
this._discount = 0;
}
get items() {
return this._items.slice();
}
get total() {
this._total = this._items.reduce((accumulated, actual) => accumulated + actual.total(), 0);
if (this._discount)
return this._total - this._discount;
return this._total;
}
add(product) {
if (!(product instanceof Product))
throw new TypeError('The product should be instance of Product!');
this._items.push(product);
}
remove(id) {
this._byProductId(id, (product, index) => this._items.splice(index, 1));
}
changeAmount(id, amount) {
this._byProductId(id, product => product._amount = amount);
}
applyCouponOfDiscount(code) {
this._discount = (new CouponOfDiscount(this)).apply(code);
console.log(this._discount);
}
_byProductId(id, callback) {
if (!this._hasProduct(id))
throw new Error('Product id not found!');
this._items.forEach((product, index) => {
if (id === product._id)
callback(product, index);
});
}
_hasProduct(id) {
return this._items.some(product => id === product._id);
}
}
<file_sep>/app/Service/HttpService.js
/**
* HttpService:
*/
export default class HttpService {
constructor(resource) {
this._resource = resource;
}
async findAll() {
try {
const request = await fetch(this._resource);
const data = await request.json();
if (!data.length)
return new Error('Not found!');
return data;
} catch (e) {
console.warn(e.toString());
}
}
async findById(id) {
try {
const request = await fetch(this._resource);
const data = await request.json();
if (!data.length)
return new Error('Not found!');
return await data.filter(item => id === item.id)[0];
} catch (e) {
console.warn(e.toString());
}
}
}
<file_sep>/README.md
# Prototype e-commerce
This project was thought as a proof of concept for the implementation of a shopping cart in JS.
The first step identify the model system classes as Product, Cart and Discount Coupon.
The cart aggregates products, the discount coupon applies the discount on a cart. We're talking about trust, so the discount coupon knows how to apply / calculate the discount on a shopping cart class. The shopping cart knows how to add, remove products as well as how to calculate the total of the sale. The product knows how to estimate its price from its quantity.
In technical terms:
* The MVC pattern was used to separate responsibilities
* An abstraction layer was created to work offline with the shopping cart (GhostDB)
* I can promise that everything will work, so promises were used as well as async / await
* A toy proxy was used to bind the data with the view
* Fetch was used to create an abstraction layer to consume web services (HttpService)
* The node was used in version 12, but all modules are loaded from the browser (Chromium 74)
Reviews and suggestions are always welcome :)
<file_sep>/app/View/ViewItemsFromCart.js
import View from './View.js';
/**
* ViewItemFromCart:
*/
export default class ViewItemsFromCart extends View {
constructor(element) {
super(element);
}
template(cart) {
return `
<table>
<thead>
<tr>
<th>Items</th>
<th>Amount</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody data-js="tbody">
${cart.items.map(item =>
`<tr data-product-id="${item._id}">
<td>
<div class="cart-item">
<div class="wrapper-img">
<img src="${item._photo}" alt="${item._title}">
</div>
<div class="cart-item-content">
<h1>${item._title}</h1>
</div>
</div>
</td>
<td>
<select data-product-id="${item._id}">
${[1, 2, 3].map(number => {
return number === item._amount
? `<option selected value="${number}">${number}</option>`
: `<option value="${number}">${number}</option>`
}).join('')}
</select>
</td>
<td>${(new Intl.NumberFormat()).format(item.total())}</td>
<td>
<a data-remove="${item._id}" href="#" class="btn bg-yellow">Remove</a>
</td>
</tr>`
).join('')}
</tbody>
<tfoot>
<td colspan="3">Subtotal</td>
<td>${(new Intl.NumberFormat()).format(cart.total)}</td>
</tfoot>
</table>`;
}
}
<file_sep>/app/Model/CouponOfDiscount.js
import Cart from './Cart.js';
export default class CouponOfDiscount {
constructor(cart) {
if (!(cart instanceof Cart))
throw new TypeError('The cart should be instance of Cart!');
this._cart = cart;
}
apply(code) {
const coupons = {
'5OFF': () => this._calculateDiscount(5),
'10OFF': () => this._calculateDiscount(10),
'15OFF': () => this._calculateDiscount(15)
};
if (!coupons.hasOwnProperty(code))
throw new Error('This code is not valid!');
return coupons[code]();
}
_calculateDiscount(percent) {
return (this._cart.total / 100) * percent;
}
}
<file_sep>/app/Model/Product.js
/**
* Product:
*/
export default class Product {
constructor(id, photo, title, price, amount = 1) {
this._id = id;
this._photo = photo;
this._title = title;
this._price = price;
this._amount = amount;
}
total() {
return parseFloat(this._price) * parseFloat(this._amount);
}
}
| ae4657704890a7f069611f7a0294aaee0866217b | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | rafaelfelipesantos/prototype-ecommerce | 7b5ccc14a61b6c591de973764d07be19e5d04dba | 0a4626e4fe4818473c1ad5805c0168c6afe07b86 |
refs/heads/master | <repo_name>tiffanybacher/byob<file_sep>/datasets/housesData.js
const housesData = [
{
id: 1,
house: 'Gryffindor',
founder: '<NAME>',
animal: 'lion',
colors: 'red and gold',
students: [
{ name: '<NAME>', id: 10001 },
{ name: '<NAME>', id: 10002 },
{ name: '<NAME>', id: 10003 },
{ name: '<NAME>', id: 10004 },
{ name: '<NAME>', id: 10005 },
{ name: '<NAME>', id: 10006 },
{ name: '<NAME>', id: 10007 },
{ name: '<NAME>', id: 10008 },
{ name: '<NAME>', id: 10009 },
{ name: '<NAME>', id: 10010 },
{ name: '<NAME>', id: 10011 },
{ name: '<NAME>', id: 10012 },
{ name: '<NAME>', id: 10013 },
{ name: '<NAME>', id: 10014 },
{ name: '<NAME>', id: 10015 },
{ name: '<NAME>', id: 10016 },
{ name: '<NAME>', id: 10017 },
{ name: '<NAME>', id: 10018 },
{ name: '<NAME>', id: 10019 },
{ name: '<NAME>', id: 10020 }
]
},
{
id: 2,
house: 'Ravenclaw',
founder: '<NAME>',
animal: 'eagle',
colors: 'blue and bronze',
students: [
{ name: '<NAME>', id: 10021 },
{ name: '<NAME>', id: 10022 },
{ name: '<NAME>', id: 10023 },
{ name: '<NAME>', id: 10024 },
{ name: '<NAME>', id: 10025 },
{ name: '<NAME>', id: 10026 },
{ name: '<NAME>', id: 10027 },
{ name: '<NAME>', id: 10028 },
{ name: '<NAME>', id: 10029 },
{ name: '<NAME>', id: 10030 },
{ name: '<NAME>', id: 10031 }
]
},
{
id: 3,
house: 'Hufflepuff',
founder: '<NAME>',
animal: 'badger',
colors: 'yellow and black',
students: [
{ name: '<NAME>', id: 10032 },
{ name: '<NAME>', id: 10033 },
{ name: '<NAME>', id: 10034 },
{ name: '<NAME>', id: 10035 },
{ name: '<NAME>', id: 10036 },
{ name: '<NAME>', id: 10037 }
]
},
{
id: 4,
house: 'Slytherin',
founder: '<NAME>',
animal: 'snake',
colors: 'green and silver',
students: [
{ name: '<NAME>', id: 10038 },
{ name: '<NAME>', id: 10039 },
{ name: '<NAME>', id: 10040 },
{ name: '<NAME>', id: 10041 },
{ name: '<NAME>', id: 10042 },
{ name: '<NAME>', id: 10043 },
{ name: '<NAME>', id: 10044 }
]
}
];
module.exports = housesData;<file_sep>/db/seeds/dev/houses.js
const housesData = require('../../../datasets/housesData.js');
const createHouse = (knex, house) => {
return knex('houses').insert({
id: house.id,
house: house.house,
founder: house.founder,
animal: house.animal,
colors: house.colors,
})
.then(() => {
let studentPromises = house.students.map(student => {
return createStudent(knex, student, house.id);
});
return Promise.all(studentPromises);
});
}
const createStudent = (knex, student, house_id) => {
return knex('students').insert({
name: student.name,
house_id
});
}
exports.seed = function(knex) {
return knex('students').del()
.then(() => knex('houses').del())
.then(() => {
let housePromises = housesData.map(house => {
return createHouse(knex, house);
});
return Promise.all(housePromises);
})
.catch(error => console.log(`Error seeding data: ${error}`));
};
<file_sep>/datasets/staffData.js
const staffData = [
{
name: '<NAME>',
job_title: 'Headmaster',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Transfiguration',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Charms',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Herbology',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Potions',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'History of Magic',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Muggle Studies',
},
{
name: '<NAME>',
job_title: 'Caretaker',
},
{
name: '<NAME>',
job_title: 'Grounds Keeper',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Flying',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Care of Magical Creatures',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Defense Against the Dark Arts',
},
{
name: '<NAME>',
job_title: 'Librarian',
},
{
name: '<NAME>',
job_title: 'Matron',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Astronomy',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Divination',
},
{
name: '<NAME>',
job_title: 'Instructor',
class: 'Arithmancy',
}
]
module.exports = staffData;<file_sep>/README.md
# BYOB
Build Your Own Backend! An educational project aimed to get comfortable with building a RESTful API.
This API contains accessible data on Hogwarts students, staff, and classes.
## Learning Goals
- Build a dataset then store data using PostgreSQL/Knex.js
- Create endpoints using Node.js/Express
- Deploy API on Heroku
## Getting started
To run the API in development mode:
run `git clone https://github.com/tiffanybacher/byob.git`\
run `node server.js`\
open `localhost:3001` in your browser
## Deployed on Heroku
To view API in production: https://hogwarts-roster.herokuapp.com/
## API Endpoints
### Students
- **Post Student** - `/api/v1/students`
You must pass the student's name and house id into the request body.\
EX: `{ name: '<NAME>', house_id: 1 }`.\
The response will return the new student's id.
- **Get All Students** - `/api/v1/students`
This will return an array of student objects.
- **Get Specific Student** - `/api/v1/students/:id`
The student's id must be passed into the `:id` param. This will return a student object containing an id, name, and house_id.
- **Delete Student** - `/api/v1/students/:id`
The student's id must be passed into the `:id` param.
### Staff
- **Post Staff Member** - `/api/v1/staff`
You must pass the staff member's name and job title into the request body.\
EX: `{ name: '<NAME>', job_title: 'Instructor' }`.\
The response will return the new staff member's id.
- **Get All Staff** - `/api/v1/staff`
This will return an array of staff member objects.
- **Get Specific Staff Member** - `/api/v1/staff/:id`
The staff member's id must be passed into the `:id` param. This will return a staff member object containing an id, name, and job_title.
- **Delete Staff Member** - `/api/v1/staff/:id`
The staff member's id must be passed into the `:id` param.
### Classes
- **Post Class** - `/api/v1/classes`
You must pass the class name and instructor id into the request body.\
EX: `{ class: '', instructor_id: 64 }`.\
The response will return the new class's id.
- **Get All Classes** - `/api/v1/classes`
This will return an array of classes as objects.
- **Get Specific Class** - `/api/v1/classes/:id`
The class's id must be passed into the `:id` param. This will return a class as an object containing an id, class, and instructor_id.
- **Delete Class** - `/api/v1/classes/:id`
The class's id must be passed into the `:id` param.
## Authored By:
[<NAME>](https://github.com/tiffanybacher)
<file_sep>/db/migrations/20190625213316_initial.js
exports.up = function(knex) {
return Promise.all([
knex.schema.createTable('houses', table => {
table.increments('id').primary();
table.string('house');
table.string('founder');
table.string('animal');
table.string('colors');
table.timestamps(true, true);
}),
knex.schema.createTable('staff', table => {
table.increments('id').primary();
table.string('name');
table.string('job_title');
}),
knex.schema.createTable('students', table => {
table.increments('id').primary();
table.string('name');
table.integer('house_id').unsigned().references('houses.id');
table.timestamps(true, true);
}),
knex.schema.createTable('classes', table => {
table.increments('id').primary();
table.string('class');
table.integer('instructor_id').unsigned().references('staff.id');
table.timestamps(true, true);
}),
knex.schema.createTable('classrooms', table => {
table.integer('class_id').unsigned().references('classes.id');
table.integer('student_id').unsigned().references('students.id');
table.timestamps(true, true);
})
]);
};
exports.down = function(knex) {
return Promise.all([
knex.schema.dropTable('houses'),
knex.schema.dropTable('staff'),
knex.schema.dropTable('students'),
knex.schema.dropTable('classes'),
knex.schema.dropTable('classrooms')
]);
};
<file_sep>/datasets/studentsData.js
const studentsData = [
{
name: ''
house_id:
}
] | e2eef1eafd66d2e0fa0c615e32c2b7dcb3abd3a8 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | tiffanybacher/byob | 5fc3201880ae2229b9f46e03212d1dd01d06140d | bd0cf97be9fe6ad31fbedcdba4077353e750becb |
refs/heads/master | <repo_name>SandeepIB/espn<file_sep>/espn/espn.admin.inc
<?php
/**
* @file
* Administrative forms for the ESPN module.
*/
/**
* ESPN admin settings form.
*/
function espn_admin_form() {
drupal_add_css(drupal_get_path('module', 'espn') . '/espn.css');
$form['espn_apikey'] = array(
'#title' => t('ESPN API key'),
'#type' => 'textfield',
'#required' => TRUE,
'#description' => t('To request an API key, visit ESPN\'s <a href="@espn_url">developer site</a>.', array('@espn_url' => 'http://developer.espn.com/member/register')),
'#default_value' => variable_get('espn_apikey', ''),
);
return system_settings_form($form);
}
| eaa12f714f689d4edbb9df7974312692da527106 | [
"PHP"
] | 1 | PHP | SandeepIB/espn | e97ba7b5e0bebe30c23005decc4a57280c951602 | df77e92b5858b04225678f2dcb303e089e91a1c5 |
refs/heads/master | <file_sep>全プログラムはPython3を想定しています。
# kan.pyを実行する時に必要なもの
* ## cv2(openCV-python)
* ## zpybar
* ## Zbar
# kan2.pyを実行する時に必要なもの
* ## tkinter<file_sep># coding: -*- utf-8 -*-
from pyzbar.pyzbar import decode
from PIL import Image
import cv2
import requests
import webbrowser
import tkinter
import tkinter.filedialog
import sys
data = None
capture = cv2.VideoCapture(0)
while not data:
ret, image = capture.read()
image = cv2.flip(image,1)
cv2.imshow('QRcodeReader', image)
image = cv2.flip(image,1)
if cv2.waitKey(1) >= 0:
# GUIでファイル読み込み
show = tkinter.Tk()
show.withdraw()
image = Image.open(tkinter.filedialog.askopenfilename(filetypes=[('image files','*.png')]))
show.destroy()
ret = True
if ret == True:
# QRコードの読取り
data = decode(image)
capture.release()
cv2.destroyAllWindows()
#デバック用プリント
print(data[0][0].decode('utf-8', 'ignore'))
URL=data[0][0].decode('utf-8', 'ignore')
if not URL.count('http'):
URL='http://'+URL
print(URL)
payload={
"browserHeight":"683",
"browserWidth":"1138",
"url":URL,
"waitTime":"0"
}
r=requests.post('https://securl.nu/jx/get_page_jx.php',data=payload)
hash=r.json()
try:
result=hash['viruses'][0]['type']
except KeyError:
print("URL not found")
sys.exit()
except IndexError:
print("check marware")
print("virus not included")
else:
print("check marware")
print("---warning---")
print("This site includes marware!!")
print(result)
print("check fishing")
try:
result=hash['blackList'][0]['type']
except IndexError:
print("safty site")
webbrowser.open(URL)
else:
print("---warning---")
print("This site is fishing site!!")
print(result)
| ed4271b227df2b937caeffd61c6c6ed881d1c9a1 | [
"Markdown",
"Python"
] | 2 | Markdown | sinchoku-doudesuka/sintyoku-1 | 05c7b5abeb685b2c659f5d4682adcbd65b1a115f | 914a549517bc38d264b5b704a133975a11bc1aea |
refs/heads/master | <repo_name>ECHartill/SuburbanNaturalist<file_sep>/src/com/parents/SuburbanNaturalistHttpServlet.java
package com.parents;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SuburbanNaturalistHttpServlet extends HttpServlet
{
private static final long serialVersionUID = 6063276226361967817L;
protected ArrayList<String> errors = new ArrayList<String>();
protected void forward(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException
{
//Always set the errors
request.setAttribute("errors", errors);
RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
rd.forward(request, response);
}
}
<file_sep>/test-output/old/Default suite/methods-alphabetical.html
<h2>Methods run, sorted chronologically</h2><h3>>> means before, << means after</h3><p/><br/><em>Default suite</em><p/><small><i>(Hover the method name to see the test class name)</i></small><p/>
<table border="1">
<tr><th>Time</th><th>Delta (ms)</th><th>Suite<br>configuration</th><th>Test<br>configuration</th><th>Class<br>configuration</th><th>Groups<br>configuration</th><th>Method<br>configuration</th><th>Test<br>method</th><th>Thread</th><th>Instances</th></tr>
<tr bgcolor="8260d5"> <td>13/06/20 18:11:37</td> <td>0</td> <td> </td><td> </td><td> </td><td> </td><td title="<<SubNatBrowserTest.closeBrowser()[pri:0, instance:test.selenium.scripts.browser.login.LoginAsUser@681e2ca7]"><<closeBrowser</td>
<td> </td> <td>main@46635017</td> <td></td> </tr>
<tr bgcolor="8260d5"> <td>13/06/20 18:11:38</td> <td>1783</td> <td> </td><td> </td><td> </td><td> </td><td title="<<SubNatBrowserTest.closeBrowser()[pri:0, instance:test.selenium.scripts.browser.login.LoginAsUser@681e2ca7]"><<closeBrowser</td>
<td> </td> <td>main@46635017</td> <td></td> </tr>
<tr bgcolor="8260d5"> <td>13/06/20 18:11:40</td> <td>3517</td> <td> </td><td> </td><td> </td><td> </td><td title="<<SubNatBrowserTest.closeBrowser()[pri:0, instance:test.selenium.scripts.browser.login.LoginAsUser@681e2ca7]"><<closeBrowser</td>
<td> </td> <td>main@46635017</td> <td></td> </tr>
<tr bgcolor="8260d5"> <td>13/06/20 18:11:29</td> <td>-7784</td> <td> </td><td> </td><td> </td><td> </td><td title=">>SubNatBrowserTest.gotoJoinPage()[pri:0, instance:test.selenium.scripts.browser.login.LoginAsUser@681e2ca7]">>>gotoJoinPage</td>
<td> </td> <td>main@46635017</td> <td></td> </tr>
<tr bgcolor="8260d5"> <td>13/06/20 18:11:37</td> <td>9</td> <td> </td><td> </td><td> </td><td> </td><td title=">>SubNatBrowserTest.gotoJoinPage()[pri:0, instance:test.selenium.scripts.browser.login.LoginAsUser@681e2ca7]">>>gotoJoinPage</td>
<td> </td> <td>main@46635017</td> <td></td> </tr>
<tr bgcolor="8260d5"> <td>13/06/20 18:11:38</td> <td>1790</td> <td> </td><td> </td><td> </td><td> </td><td title=">>SubNatBrowserTest.gotoJoinPage()[pri:0, instance:test.selenium.scripts.browser.login.LoginAsUser@681e2ca7]">>>gotoJoinPage</td>
<td> </td> <td>main@46635017</td> <td></td> </tr>
<tr bgcolor="aed5f9"> <td>13/06/20 18:11:36</td> <td>-223</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="LoginAsUser.invalidPasswordLogin()[pri:0, instance:test.selenium.scripts.browser.login.LoginAsUser@681e2ca7]">invalidPasswordLogin</td>
<td>main@46635017</td> <td></td> </tr>
<tr bgcolor="aed5f9"> <td>13/06/20 18:11:38</td> <td>1571</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="LoginAsUser.invalidUsernameLogin()[pri:0, instance:test.selenium.scripts.browser.login.LoginAsUser@681e2ca7]">invalidUsernameLogin</td>
<td>main@46635017</td> <td></td> </tr>
<tr bgcolor="aed5f9"> <td>13/06/20 18:11:40</td> <td>3309</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="LoginAsUser.validLogin()[pri:0, instance:test.selenium.scripts.browser.login.LoginAsUser@681e2ca7]">validLogin</td>
<td>main@46635017</td> <td></td> </tr>
</table>
<file_sep>/src/test/unit/modeltests/user/UserUnit.java
package test.unit.modeltests.user;
import org.testng.annotations.Test;
import com.models.User;
public class UserUnit
{
@Test
public void testId()
{
User u = new User();
u.setId(100);
assert 100 == u.getId();
u.setId(null);
assert null == u.getId();
u.setId(0);
assert 0 == u.getId();
}
@Test
public void testFirstname()
{
User u = new User();
u.setFirstname("");
assert u.getFirstname().length() == 0;
u.setFirstname(null);
assert null == u.getFirstname();
u.setFirstname("Alpha");
assert u.getFirstname().equals("Alpha");
}
@Test
public void testLastname()
{
User u = new User();
u.setLastname("");
assert u.getLastname().length() == 0;
u.setLastname(null);
assert null == u.getLastname();
u.setLastname("Omega");
assert u.getLastname().equals("Omega");
}
@Test
public void testUsername()
{
User u = new User();
u.setUsername("");
assert u.getUsername().length() == 0;
u.setUsername(null);
assert null == u.getUsername();
u.setUsername("Andre 3000");
assert u.getUsername().equals("Andre 3000");
}
@Test
public void testPassword()
{
User u = new User();
u.setPassword("");
assert u.getPassword().length() == 0;
u.setPassword(null);
assert null == u.getPassword();
u.setPassword("<PASSWORD>");
assert u.getPassword().equals("<PASSWORD>");
}
}
<file_sep>/src/com/parents/SuburbanNaturalistException.java
package com.parents;
public class SuburbanNaturalistException extends Exception
{
private static final long serialVersionUID = -3599803706330685108L;
public SuburbanNaturalistException(String message)
{
super(message);
}
public SuburbanNaturalistException(Exception e)
{
super(e);
}
}
<file_sep>/src/com/helpers/ValidationHelper.java
package com.helpers;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.http.Part;
public class ValidationHelper
{
public void validateSignup(HashMap<String, String> params, ArrayList<String> errors)
{
boolean pwd = true;
boolean pwdcfm = true;
if(params.get("firstname") == null || params.get("firstname").length() == 0)
{
errors.add("First Name cannot be empty");
}
if(params.get("lastname") == null || params.get("lastname").length() == 0)
{
errors.add("Last Name cannot be empty");
}
if(params.get("email") == null || params.get("email").length() == 0)
{
errors.add("Email cannot be empty");
}
else
{
// check that emal is well-formed
if(!params.get("email").contains("@") || !params.get("email").contains("."))
{
errors.add("The email is not well formed");
}
}
if(params.get("password") == null || params.get("password").length() == 0)
{
pwd = false;
errors.add("Password cannot be empty");
}
if(params.get("confirm") == null || params.get("confirm").length() == 0)
{
pwdcfm = false;
errors.add("Password Confirm cannot be empty");
}
if(pwd && pwdcfm && !params.get("password").equals(params.get("confirm")))
{
errors.add("The passwords do not match");
}
}
public ArrayList<String> validateFileUpload(Part part)
{
ArrayList<String> errors = new ArrayList<String>();
if(part.getSize() > 2000000)
{
errors.add("The image size must be less than 2MB");
}
return errors;
}
}
<file_sep>/src/com/database/HibernateDatabaseManager.java
package com.database;
import java.util.ArrayList;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.PropertyNotFoundException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projections;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import com.models.Image;
import com.models.User;
import com.parents.SuburbanNaturalistException;
public class HibernateDatabaseManager
{
private Configuration config = null;
private ServiceRegistry serviceRegistry = null;
private SessionFactory sessionFactory = null;
private Session session = null;
private Transaction trans = null;
/**
* initialize the hibernate database manager
* Create a session from the session factory
*
*/
public HibernateDatabaseManager()
{
try
{
config = new Configuration().configure("hibernate.cfg.xml");
}
catch (HibernateException he)
{
System.out.println("Error getting configuration file: " + he.getMessage());
he.printStackTrace();
}
serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
}
private void getSession()
{
try
{
sessionFactory = new Configuration().configure().buildSessionFactory(serviceRegistry);
}
catch(PropertyNotFoundException pnfe)
{
System.out.println("Error building factory: " + pnfe.getMessage());
pnfe.printStackTrace();
}
catch(HibernateException he)
{
System.out.println("Error building session factory: " + he.getMessage());
he.printStackTrace();
}
session = sessionFactory.getCurrentSession();
}
public User login(String username, String password) throws SuburbanNaturalistException
{
this.getSession();
User u = null;
ArrayList<User> ual = null;
try
{
trans = session.beginTransaction();
ual = (ArrayList<User>)session.createQuery("from User where username = :username and password = :<PASSWORD>")
.setParameter("username", username)
.setParameter("password", <PASSWORD>).list();
if(ual != null && ual.size() > 0)
{
u = ual.get(0);
}
else
{
throw new SuburbanNaturalistException("The user does not exist");
}
trans.commit();
//do not return a user with a password
u.setPassword(null);
}
catch(HibernateException he)
{
u = null;
if(trans != null)
{
trans.rollback();
}
throw new SuburbanNaturalistException(he);
}
return u;
}
public void saveUser(User u) throws SuburbanNaturalistException
{
this.getSession();
try
{
trans = session.beginTransaction();
session.save(u);
trans.commit();
u.setPassword(<PASSWORD>);
}
catch(HibernateException he)
{
if(trans != null)
{
trans.rollback();
}
throw new SuburbanNaturalistException(he);
}
}
public void saveImage(Image i) throws SuburbanNaturalistException
{
this.getSession();
int imageId;
try
{
trans = session.beginTransaction();
session.save(i);
Criteria criteria = session
.createCriteria(Image.class)
.setProjection(Projections.max("id"));
imageId = (Integer)criteria.uniqueResult();
i.setImagePath(i.getImagePath() + "/" + imageId);
session.saveOrUpdate(i);
trans.commit();
}
catch(HibernateException he)
{
if(trans != null)
{
trans.rollback();
}
throw new SuburbanNaturalistException(he);
}
}
}
<file_sep>/src/test/selenium/scripts/browser/parents/SubNatBrowserTest.java
package test.selenium.scripts.browser.parents;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
public class SubNatBrowserTest
{
protected String url = "http://localhost:8080/SubNat";
protected WebDriver browser;
@BeforeMethod
@Parameters({"browser"})
public void gotoJoinPage(String testBrowser)
{
if("firefox".equalsIgnoreCase(testBrowser))
{
browser = new FirefoxDriver();
}
else if("htmlunit".equalsIgnoreCase(testBrowser))
{
browser = new HtmlUnitDriver();
}
browser.get(url);
}
@AfterMethod
public void closeBrowser()
{
browser.close();
}
protected void sleep(long millis)
{
try
{
Thread.sleep(millis);
}
catch(InterruptedException ie){}
}
}
<file_sep>/test-output/old/all_tests/unit.properties
[SuiteResult unit][SuiteResult selenium]<file_sep>/src/com/web/LoginServlet.java
package com.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.database.HibernateDatabaseManager;
import com.helpers.Encryptor;
import com.models.User;
import com.parents.SuburbanNaturalistException;
import com.parents.SuburbanNaturalistHttpServlet;
public class LoginServlet extends SuburbanNaturalistHttpServlet
{
private static final long serialVersionUID = 8020498799316191565L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
errors.clear();
String action = request.getParameter("action");
String username = request.getParameter("username");
String password = request.getParameter("password");
Encryptor e = Encryptor.getInstance();
HibernateDatabaseManager hdbm = new HibernateDatabaseManager();
User user = (User)request.getSession().getAttribute("user");
if(action == null && user != null)
{
//logged in, clicked logout link
request.getSession().setAttribute("user", null);
this.forward(request, response, "/");
}
else if(action == null && user == null)
{
this.forward(request, response, "/");
}
else if(action.equalsIgnoreCase("login"))
{
if(username == null || username.length() == 0)
{
errors.add("You must enter a username");
}
if(password == null || password.length() == 0)
{
errors.add("You must enter a password");
}
if(errors.size() > 0)
{
this.forward(request, response, "/");
}
else
{
try
{
user = hdbm.login(username, e.encrypt(password));
}
catch (SuburbanNaturalistException we)
{
System.out.println("Error logging in: " + we.getMessage());
errors.add("That user password combination was not found");
}
request.getSession().setAttribute("user", user);
if(errors.size() > 0)
{
this.forward(request, response, "/");
}
else
{
this.forward(request, response, "/jsp/user/home.jsp");
}
}
}
}
}
<file_sep>/src/test/selenium/scripts/browser/parents/Join.java
package test.selenium.scripts.browser.parents;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.BeforeMethod;
public class Join extends SubNatBrowserTest
{
protected String url = "http://localhost:8080/SubNat/signup";
protected String firstname_id = "signup_firstname";
protected String lastname_id = "signup_lastname";
protected String email_id = "signup_email";
protected String password_id = "<PASSWORD>";
protected String confirm_id = "signup_confirm";
//for individual errors; need to append counter (counter starts at 1)
protected String error_id = "error_list_";
protected String errors_id = "errors_list";
protected WebElement firstname;
protected WebElement lastname;
protected WebElement email;
protected WebElement password;
protected WebElement confirm;
protected WebElement error;
protected ArrayList<WebElement> errors;
@BeforeMethod
public void findElements()
{
browser.findElement(By.id("signup_link")).click();
firstname = browser.findElement(By.id(firstname_id));
lastname = browser.findElement(By.id(lastname_id));
email = browser.findElement(By.id(email_id));
password = browser.findElement(By.id(password_id));
confirm = browser.findElement(By.id(confirm_id));
}
}
<file_sep>/README.md
SuburbanNaturalist
==================
| b00d70cdbbeb8b96d031ee63261394edfc9bf4e5 | [
"Markdown",
"Java",
"HTML",
"INI"
] | 11 | Java | ECHartill/SuburbanNaturalist | 825d4a55e950822ffed7046be003e79f6dd8ca9a | 780495c7e48c31c18647120517cb3f7a92d4fffd |
refs/heads/main | <file_sep># Face-Recognition-Based-Attendance-System
Python Version : 3.7
Libraries Used :
Opencv
Numpy
Pandas
PIL
Kivy
Shutil
Abstract:
To detect real time human face are used and a simple fast Principal Component Analysis has used to recognize the faces detected with a high accuracy rate. The matched face is used to mark attendance of the students. Our system maintains the attendance records of students automatically.Our module enrolls the student’s face. This enrolling is a onetime process and their face will be stored in the database. During enrolling of face we require a system since it is a onetime process. You can have your own roll number as your id which will be unique for each student. The presence of each student will be updated in a database. Attendance is marked after student identification.
Algorithm :
Step 1: Take an image of a normal expression of a human face.
Step 2: Converts the color image to grayscale.
Step 3: Crop the 3 facial image region of interest (ROI) (eyes, eye brows and lip) from the image by defining region.
Step 4: Find edges of all image region.
Step 5: Take an image of a faces and create dataset
Step 7: Train the dataset.
Step 8: Recognize the faces in video camera.
Step 9: Mark the attendance accordingly.
<file_sep>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
import cv2,os
import shutil
import csv
import numpy as np
import pandas as pd
from datetime import datetime
import time
from PIL import Image
import os.path, time
import datetime
class CreateAccountWindow(Screen):
def submit(self):
sm.current = "login"
def TrackImages(self):
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("TrainingImageLabel/Trainner.yml")
harcascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(harcascadePath);
df=pd.read_csv("StudentDetails/StudentDetails.csv")
cam = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
col_names = ['ID','Name','Date','Time']
attendance = []
while True:
ret, im =cam.read()
gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
faces=faceCascade.detectMultiScale(gray, 1.2,5)
for(x,y,w,h) in faces:
cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2)
Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
if 'Id' in df and (conf < 50):
ts = time.time()
date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
aa=df.loc[df['Id'] == Id]['Name'].values
tt=str(Id)+"-"+aa
attendance = [Id,aa,date,timeStamp]
else:
Id='Unknown'
tt=str(Id)
if(conf > 75):
noOfFile=len(os.listdir("ImagesUnknown"))+1
cv2.imwrite("ImagesUnknown/Image"+str(noOfFile) + ".jpg", im[y:y+h,x:x+w])
cv2.putText(im,str(tt),(x,y+h), font, 1,(255,255,255),2)
cv2.imshow('im',im)
if (cv2.waitKey(1)==ord('q')):
break
ts = time.time()
date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
exists = os.path.isfile("Attendance/Attendance_" + date + ".csv")
if exists:
df1=pd.read_csv("Attendance/Attendance_" + date + ".csv")
if Id in df1['ID']:
print("Attendance Marked")
else:
with open("Attendance/Attendance_" + date + ".csv", 'a+') as csvFile1:
writer = csv.writer(csvFile1)
writer.writerow(attendance)
csvFile1.close()
else:
with open("Attendance\Attendance_" + date + ".csv", 'a+') as csvFile1:
writer = csv.writer(csvFile1)
writer.writerow(col_names)
writer.writerow(attendance)
csvFile1.close()
cam.release()
cv2.destroyAllWindows()
class LoginWindow(Screen):
namee = ObjectProperty(None)
rollno = ObjectProperty(None)
def goback(self):
sm.current = "create"
def loginBtn(self):
a = self.namee.text
b = self.rollno.text
TakeImages(b ,a)
TrainImages()
getImagesAndLabels('TrainingImage')
class WindowManager(ScreenManager):
pass
def TakeImages(Id ,name):
if(int(Id)!=0):
cam = cv2.VideoCapture(0)
harcascadePath = "haarcascade_frontalface_default.xml"
detector=cv2.CascadeClassifier(harcascadePath)
sampleNum=0
while(True):
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
sampleNum=sampleNum+1
cv2.imwrite("TrainingImage/ "+name +"."+Id +'.'+ str(sampleNum) + ".jpg", gray[y:y+h,x:x+w])
cv2.imshow('frame',img)
if cv2.waitKey(100) & 0xFF == ord('q'):
break
elif sampleNum>100:
break
cam.release()
cv2.destroyAllWindows()
row = [Id , name]
with open('StudentDetails/StudentDetails.csv','a+') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
csvFile.close()
def TrainImages():
recognizer = cv2.face_LBPHFaceRecognizer.create()
harcascadePath = "haarcascade_frontalface_default.xml"
detector =cv2.CascadeClassifier(harcascadePath)
faces,Id = getImagesAndLabels("TrainingImage")
recognizer.train(faces, np.array(Id))
recognizer.save("TrainingImageLabel/Trainner.yml")
def getImagesAndLabels(path):
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
faces=[]
Ids=[]
for imagePath in imagePaths:
pilImage=Image.open(imagePath).convert('L')
imageNp=np.array(pilImage,'uint8')
Id=int(os.path.split(imagePath)[-1].split(".")[1])
faces.append(imageNp)
Ids.append(Id)
return faces,Ids
kv = Builder.load_file("my.kv")
sm = WindowManager()
screens = [CreateAccountWindow(name="create"),LoginWindow(name="login")]
for screen in screens:
sm.add_widget(screen)
class MyMainApp(App):
def build(self):
return sm
if __name__ == "__main__":
MyMainApp().run() | 5b7a56636c9df466a86ded5291e8eb48d05afdae | [
"Markdown",
"Python"
] | 2 | Markdown | sohail252/Face-Recognition-Based-Attendance-System | 85ae11efebc88235a53c15600341502f96c9378f | 93ec34ed7d26539ecdf2181e7e668fd9837cefb9 |
refs/heads/master | <file_sep>#ifndef _CUBE_H_
#define _CUBE_H_
#include "Geode.h"
#include "Vector3d.h"
#include "Const.h"
class Cube : public Geode{
public:
Cube(double s, Vector3d c, draw::mode);
Bs update();
private:
void render();
double size;
Vector3d color;
draw::mode mode;
};
#endif<file_sep>#include <stdlib.h>
#include "shader.h"
#include "Window.h"
#include <iostream>
#include "Matrix4d.h"
#include "Debug.h"
#include "Const.h"
#include "Light.h"
#include "Material.h"
#include "ObjNode.h"
#include "Cone.h"
#define ROTSCALE 180.0;
#define ZOOMSCALE 2.0;
using namespace std;
int Window::width = 512; // set window width in pixels here
int Window::height = 512; // set window height in pixels here
int Window::old_x = width / 2;
int Window::old_y = height / 2;
MatrixTransform * Window::root = new MatrixTransform(Matrix4d());
MatrixTransform * Window::bunny;
MatrixTransform * Window::dragon;
MatrixTransform * Window::bear;
MatrixTransform * Window::spotL;
MatrixTransform * Window::pointL;
// camera parameters
Vector3d eye(0, 0, 20);
Vector3d lookat(0, 0, 0);
Vector3d up(0, 1, 0);
// bunny data
Matrix4d bunny_tran, bunny_scale;
Coordinate3d bunny_min, bunny_max;
vector<Coordinate3d> bunny_pos;
vector<Vector3d> bunny_nor;
vector<Coordinate3i> bunny_pos_ind;
vector<Coordinate3i> bunny_nor_ind;
// bear data
Matrix4d bear_tran, bear_scale;
Coordinate3d bear_min, bear_max;
vector<Coordinate3d> bear_pos;
vector<Vector3d> bear_nor;
vector<Coordinate3i> bear_pos_ind;
vector<Coordinate3i> bear_nor_ind;
// dragon data
Matrix4d dragon_tran, dragon_scale;
Coordinate3d dragon_min, dragon_max;
vector<Coordinate3d> dragon_pos;
vector<Vector3d> dragon_nor;
vector<Coordinate3i> dragon_pos_ind;
vector<Coordinate3i> dragon_nor_ind;
//trackball variables
control::MOVEMENT movement = control::NONE;
Vector3d lastPoint;
Matrix4d rotation;
Matrix4d scaling;
MatrixTransform* Window::scaling_mt;
MatrixTransform* Window::rotate_mt;
// spotlight sources parameters
f4 ambient(0.1, 0.1, 0.1, 1.0);
f4 diffuse(0.2, 0.2, 0.2, 1.0);
f4 specular(1, 1, 1, 1.0);
f4 position(3.0, 10.0, 0.0, 1.0);
f3 spot_direction(-3.0, -10.0, 0.0);
// point light source parameters
f4 p_ambient(0.4, 0.4, 0.4, 1.0);
f4 p_diffuse(1, 1, 1, 1.0);
f4 position2(-3.0, -10.0, 2.0, 0.0);
Light spotLight(ambient, diffuse, specular, position);
Light pointLight(p_ambient, p_diffuse, specular, position2);
//shine material parameters
f4 m_ambient(0.19225, 0.19225, 0.19225, 1.0);
f4 m_diffuse(0.50754, 0.50754, 0.50754, 1.0);
f4 m_specular(0.508273, 0.508273, 0.508273, 1.0);
f4 m_emission(0.8, 0.8, 0.8, 0.0);
float shininess = 51.2;
Material material;
Material b_material;
Material emissive_ma;
Shader * shader;
bool useShader = false;
bool lightControl = false;
KEY key = F1;
void Window::init(){
// load shader
shader = new Shader("shaders/spotlight.vert", "shaders/spotlight.frag");
//shader->printLog("shader log:");
//system("pause");
/// loading bunny
Parser::parseObj("bunny.obj", bunny_pos, bunny_nor, bunny_pos_ind, bunny_nor_ind, bunny_min, bunny_max);
bunny_tran.makeTranslate(-(bunny_min.x + bunny_max.x) / 2,
-(bunny_min.y + bunny_max.y) / 2, -(bunny_min.z + bunny_max.z) / 2);
bunny_scale = calculateScalingMatrix(width, height, bunny_min, bunny_max);
/// loading bear
Parser::parseObj("bear.obj", bear_pos, bear_nor, bear_pos_ind, bear_nor_ind, bear_min, bear_max);
bear_tran.makeTranslate(-(bear_min.x + bear_max.x) / 2,
-(bear_min.y + bear_max.y) / 2, -(bear_min.z + bear_max.z) / 2);
bear_scale = calculateScalingMatrix(width, height, bear_min, bear_max);
/// loading dragon
Parser::parseObj("dragon.obj", dragon_pos, dragon_nor, dragon_pos_ind, dragon_nor_ind, dragon_min, dragon_max);
dragon_tran.makeTranslate(-(dragon_min.x + dragon_max.x) / 2,
-(dragon_min.y + dragon_max.y) / 2, -(dragon_min.z + dragon_max.z) / 2);
dragon_scale = calculateScalingMatrix(width, height, dragon_min, dragon_max);
//setting up light sources
spotLight.setExponent(1);
spotLight.setCutOff(5);
spotLight.setSpotDirection(spot_direction);
spotLight.setAttenuation(1.0, 0.1, 0.0);
//setting up material for bunny
material.setAmbient(m_ambient);
material.setDiffuse(m_diffuse);
material.setSpecular(m_specular);
material.setShininess(shininess);
//setting up material for bear
b_material.setAmbient(f4(0.2, 0.6, 0.6, 1.0));
b_material.setDiffuse(f4(0.5, 0.5, 0.5, 1.0));
//setting up emissive material for point light
emissive_ma.setAmbient(f4(0.8, 0.8, 0.8, 1.0));
emissive_ma.setDiffuse(diffuse);
emissive_ma.setSpecular(specular);
emissive_ma.setEmission(f4(0.1,0.1,0.1,1.0));
//building scene graph
scaling_mt = new MatrixTransform(Matrix4d());
rotate_mt = new MatrixTransform(Matrix4d());
bunny = new MatrixTransform(bunny_scale * bunny_tran);
root->addChild(rotate_mt);
rotate_mt->addChild(scaling_mt);
scaling_mt->addChild(bunny);
bunny->addChild(new ObjNode(&bunny_pos, &bunny_nor, &bunny_pos_ind, &bunny_nor_ind, bunny_min, bunny_max, &material));
bear = new MatrixTransform(bear_scale * bear_tran);
bear->addChild(new ObjNode(&bear_pos, &bear_nor, &bear_pos_ind, &bear_nor_ind, bear_min, bear_max, &b_material));
dragon = new MatrixTransform(dragon_scale * dragon_tran);
dragon->addChild(new ObjNode(&dragon_pos, &dragon_nor, &dragon_pos_ind, &dragon_nor_ind, dragon_min, dragon_max, &b_material));
Matrix4d t1;
t1.makeTranslate(-3.0, -10.0, 2.0);
pointL = new MatrixTransform(t1);
root->addChild(pointL);
pointL->addChild(new Sphere(0.5, 20, 20, Vector3d(1, 1, 1), draw::SOLID, &emissive_ma));
Vector3d vCone(-3, -10, 0);
vCone.normalize();
Vector3d axis = Vector3d(0, 0, -1) * vCone;
axis.normalize();
Matrix4d rCone;
rCone.makeRotate(acos(vCone.dot(Vector3d(0, 0, -1))) * 180 / M_PI, axis);
Matrix4d t2;
t2.makeTranslate(3, 10, 0);
spotL = new MatrixTransform(t2 * rCone);
root->addChild(spotL);
Material * m_cone = new Material(f4(0.5, 0.6, 0.9, 1.0), f4(0.5, 0.5, 0.5, 1.0), f4(0, 0, 0, 1.0), 20, f4(0, 0, 0, 1.0), f3(0, 0, 0));
spotL->addChild(new Cone(0.5, 1, 20, 20, Vector3d(0.0, 0.0, 0.0),draw::SOLID, m_cone));
}
Matrix4d Window::calculateScalingMatrix(int w, int h, Coordinate3d min, Coordinate3d max){
double x = (max.x - min.x) / 2;
double y = (max.y - min.y) / 2;
double z = (max.z - min.z) / 2;
//cout << "x : " << x << " y : " << y << " z : " << z << endl;
double a = z / y;
double ymax = 20 / (a + 1 / tan(30 * M_PI / 180));
double sy = ymax / y;
double xmax = ymax * double(w) / double(h);
double sx = xmax / x;
double factor = sy < sx ? sy : sx;
Matrix4d s;
s.makeScale(factor, factor, factor);
return s;
}
//----------------------------------------------------------------------------
// Callback method called when system is idle.
void Window::idleCallback()
{
displayCallback(); // call display routine to show the cube
}
//----------------------------------------------------------------------------
// Callback method called by GLUT when graphics window is resized by the user
void Window::reshapeCallback(int w, int h)
{
cerr << "Window::reshapeCallback called" << endl;
width = w;
height = h;
glViewport(0, 0, w, h); // set new viewport size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, double(width) / (double)height, 1.0, 1000.0); // set perspective projection viewing frustum
gluLookAt(eye[0], eye[1], eye[2], lookat[0], lookat[1], lookat[2], up[0], up[1], up[2]);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
spotLight.apply();
pointLight.apply();
// recalculate bunny_scale matrix
bunny_scale = calculateScalingMatrix(w, h, bunny_min, bunny_max);
bunny->setMatrix(bunny_scale * bunny_tran);
}
//----------------------------------------------------------------------------
// Callback method called by GLUT when window readraw is necessary or when glutPostRedisplay() was called.
void Window::displayCallback()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear color and depth buffers
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
spotLight.apply();
pointLight.apply();
glMatrixMode(GL_MODELVIEW);
root->draw(Matrix4d());
glFlush();
glutSwapBuffers();
}
void Window::keyboardProcess(unsigned char key, int x, int y){
switch (key){
case 'p':
useShader = !useShader;
if (useShader)
shader->bind();
else
shader->unbind();
break;
case 'l':
lightControl = !lightControl;
break;
case 27:
exit(0);
}
}
void Window::processSpecialKeys(int k, int x, int y){
switch (k){
case GLUT_KEY_F1:
if (key != F1){
if (key == F2)
scaling_mt->removeChild(bear);
if (key == F3)
scaling_mt->removeChild(dragon);
scaling_mt->addChild(bunny);
key = F1;
}
break;
case GLUT_KEY_F2:
if (key != F2){
if (key == F1)
scaling_mt->removeChild(bunny);
if (key == F3)
scaling_mt->removeChild(dragon);
scaling_mt->addChild(bear);
key = F2;
}
break;
case GLUT_KEY_F3:
if (key != F3){
if (key == F1)
scaling_mt->removeChild(bunny);
if (key == F2)
scaling_mt->removeChild(bear);
scaling_mt->addChild(dragon);
key = F3;
}
break;
}
}
void Window::mouseMotionProcess(int x, int y){
Vector3d direction;
double pixel_diff;
double rot_angle, zoom_factor;
Vector3d curPoint;
curPoint = trackBallMapping(x, y);
switch (movement){
case control::ROTATION:
{
if (!lightControl){
direction = curPoint - lastPoint;
double velocity = direction.magnitude();
if (velocity > 0.0001){
Vector3d rotAxis = lastPoint * curPoint;
rotAxis.normalize();
rot_angle = velocity * ROTSCALE;
Matrix4d r;
r.makeRotate(rot_angle, rotAxis);
rotation = r * rotation;
rotate_mt->setMatrix(rotation);
}
}
}
break;
case control::SCALING:
{
pixel_diff = curPoint[1] - lastPoint[1];
zoom_factor = 1.0 + pixel_diff * ZOOMSCALE;
if (!lightControl){
Matrix4d s;
s.makeScale(zoom_factor, zoom_factor, zoom_factor);
scaling = scaling * s;
scaling_mt->setMatrix(scaling);
displayCallback();
}
else{
spotLight.setCutOff(spotLight.getCutOff() * zoom_factor);
}
}
break;
}
lastPoint = curPoint;
}
void Window::mouseProcess(int button, int state, int x, int y){
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
movement = control::ROTATION;
old_x = x;
old_y = y;
lastPoint = trackBallMapping(x, y);
}
else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN){
movement = control::SCALING;
old_x = x;
old_y = y;
lastPoint = trackBallMapping(x, y);
}
else
movement = control::NONE;
}
Vector3d Window::trackBallMapping(int x, int y){
Vector3d v(double (2*x - width) / double (width), double (height - 2*y) / double (height), 0);
double d = v.magnitude();
d = d < 1.0 ? d : 1.0;
v.set(2, sqrt(1.001 - d*d));
v.normalize();
return v;
}<file_sep>#include <iostream>
#include "Vector4d.h"
Vector4d::Vector4d(){
for (int i = 0; i < 3; i++)
v[i] = 0.0;
v[3] = 1.0;
}
Vector4d::Vector4d(GLdouble x, GLdouble y, GLdouble z){
v[0] = x;
v[1] = y;
v[2] = z;
v[3] = 1.0;
}
Vector4d::Vector4d(GLdouble x, GLdouble y, GLdouble z, GLdouble w){
v[0] = x;
v[1] = y;
v[2] = z;
v[3] = w;
}
void Vector4d::set(int index, GLdouble value){
if (index <= 4 && index >= 0)
v[index] = value;
}
GLdouble Vector4d::get(int index){
return v[index];
}
GLdouble Vector4d::operator[](int index){
return v[index];
}
Vector4d Vector4d::operator+(Vector4d & another){
GLdouble x = v[0] / v[3];
GLdouble y = v[1] / v[3];
GLdouble z = v[2] / v[3];
GLdouble w = v[3];
x = (x + another[0] / another[3]) * w;
y = (y + another[1] / another[3]) * w;
z = (z + another[2] / another[3]) * w;
return Vector4d(x, y, z, w);
}
Vector4d& Vector4d::operator=(Vector4d & other){
if (this != &other)
{
for (int i = 0; i<4; ++i)
{
v[i] = other[i];
}
}
return *this;
}
void Vector4d::add(Vector4d & another){
GLdouble x = another[0] / another[3];
GLdouble y = another[1] / another[3];
GLdouble z = another[2] / another[3];
v[0] = (v[0] / v[3] + x) * v[3];
v[1] = (v[1] / v[3] + y) * v[3];
v[2] = (v[2] / v[3] + z) * v[3];
}
Vector4d Vector4d::operator-(Vector4d & another){
GLdouble x = v[0] / v[3];
GLdouble y = v[1] / v[3];
GLdouble z = v[2] / v[3];
GLdouble w = v[3];
x = (x - another[0] / another[3]) * w;
y = (y - another[1] / another[3]) * w;
z = (z - another[2] / another[3]) * w;
return Vector4d(x, y, z, w);
}
void Vector4d::substract(Vector4d & another){
GLdouble x = another[0] / another[3];
GLdouble y = another[1] / another[3];
GLdouble z = another[2] / another[3];
v[0] = (v[0] / v[3] - x) * v[3];
v[1] = (v[1] / v[3] - y) * v[3];
v[2] = (v[2] / v[3] - z) * v[3];
}
void Vector4d::dehomogenize(){
for (int i = 0; i < 3; i++)
v[i] /= v[3];
v[3] = 1.0;
}
void Vector4d::print(){
std::cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << std::endl;
}
Vector3d Vector4d::getVector3d(){
return Vector3d(v[0], v[1], v[2]);
}<file_sep>#include "parser.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
void Parser::parse(char* file, vector<double> &position, vector<Vector3d> &normal, double &x_min, double &x_max, double &y_min, double &y_max, double &z_min, double &z_max){
ifstream infile;
infile.open(file, std::ifstream::in);
if (!infile.is_open()){
std::cout << "failed to open file" << std::endl;
return;
}
else
std::cout << "file has been opened" << std::endl;
string line;
x_min = y_min = z_min = std::numeric_limits<double>::max();
x_max = y_max = z_max = std::numeric_limits<double>::min();
while (getline(infile, line)){
std::istringstream iss(line);
double d;
iss >> d;
if (d > x_max)
x_max = d;
if (d < x_min)
x_min = d;
position.push_back(d);
iss >> d;
if (d > y_max)
y_max = d;
if (d < y_min)
y_min = d;
position.push_back(d);
iss >> d;
if (d > z_max)
z_max = d;
if (d < z_min)
z_min = d;
position.push_back(d);
Vector3d n;
for (int i = 0; i < 3; i++){
iss >> d;
n.set(i, d);
}
n.normalize();
normal.push_back(n);
}
std::cout << "x min: " << x_min << "x max: " << x_max << "y min: " << y_min << "y max: " << y_max << "z min: " << z_min << "z max: " << z_max << std::endl;
}
void Parser::parseObj(char* file, vector<Coordinate3d> &position, vector<Vector3d> &normal, vector<Coordinate3i> & posIndex, vector<Coordinate3i> & norIndex, Coordinate3d & min, Coordinate3d & max){
FILE* fp;
double x, y, z;
fp = fopen(file, "rb");
if (fp == NULL){
cerr << "error loading file" << endl;
exit(-1);
}
min.x = min.y = min.z = std::numeric_limits<double>::max();
max.x = max.y = max.z = std::numeric_limits<double>::min();
char c1, c2;
char line[128];
while (fgets(line, 128, fp)){
c1 = line[0];
c2 = line[1];
if (c1 == 'v' && c2 == ' '){ // reading vertex and color v 0.145852 0.104651 0.517576 0.2 0.8 0.4
Coordinate3d c;
sscanf(line, "v %lf %lf %lf\n", &(c.x), &(c.y), &(c.z));
//cout << "vertex x : " << c.x << " y : " << c.y << " z: " << c.z << endl;
if (c.x > max.x)
max.x = c.x;
if (c.x < min.x)
min.x = c.x;
if (c.y > max.y)
max.y = c.y;
if (c.y < min.y)
min.y = c.y;
if (c.z > max.z)
max.z = c.z;
if (c.z < min.z)
min.z = c.z;
position.push_back(c);
}
else if (c1 == 'v' && c2 == 'n'){ // reading vertex normal vn -0.380694 3.839313 4.956321
sscanf(line, "vn%lf %lf %lf\n", &x, &y, &z);
//cout << " normal x : " << x << " y : " << y << " z: " << z << endl;
Vector3d n(x, y, z);
n.normalize();
normal.push_back(n);
}
else if (c1 == 'f' && c2 == ' '){ // reading faces f 31514//31514 31465//31465 31464//31464
Coordinate3i pos;
Coordinate3i nor;
sscanf(line, "f %d//%d %d//%d %d//%d\n", &(pos.x), &(nor.x), &(pos.y), &(nor.y), &(pos.z), &(nor.z));
//cout << "pos.x " << pos.x << " pos.y " << pos.y << " pos.z " << pos.z << endl;
//cout << "nor.x " << nor.x << " nor.y " << nor.y << " nor.z " << nor.z << endl;
posIndex.push_back(pos);
norIndex.push_back(nor);
}
else
continue;
}
fclose(fp);
}
<file_sep>#include <stdlib.h>
#include "Window.h"
#include "Cube.h"
#include "MatrixTransform.h"
#include "Sphere.h"
#include "Matrix4d.h"
#include "parser.h"
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
/*
vector<Coordinate3d> position;
vector<Vector3d> normal;
vector<Coordinate3i> posIndex;
vector<Coordinate3i> norIndex;
Coordinate3d min;
Coordinate3d max;
Parser::parseObj("dragon.obj", position, normal, posIndex, norIndex, min, max);
cout << "# of vertice : " << position.size() << endl;
cout << "# of normal : " << normal.size() << endl;
cout << "# of indices of position : " << posIndex.size() << endl;
cout << "# of indices of normal : " << norIndex.size() << endl;
cout << "min: ( " << min.x << ", " << min.y << ", " << min.z << " )" << endl;
cout << "max: ( " << max.x << ", " << max.y << ", " << max.z << " )" << endl;
system("pause");
*/
///*
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize(Window::width, Window::height);
glutCreateWindow("project 5");
glEnable(GL_DEPTH_TEST); // enable depth buffering
glClear(GL_DEPTH_BUFFER_BIT); // clear depth buffer
glClearColor(0.0, 0.0, 0.0, 0.0); // set clear color to black
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // set polygon drawing mode to fill front and back of each polygon
glEnable(GL_CULL_FACE); // disable backface culling to render both sides of polygons
glShadeModel(GL_SMOOTH); // set shading to smooth
glEnable(GL_LIGHTING);
glShadeModel(GL_SMOOTH);
glEnable(GL_NORMALIZE);
glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
/*
// Generate material properties:
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
// Generate light source:
glLightfv(GL_LIGHT0, GL_POSITION, position);
glEnable(GL_LIGHT0);
*/
//Arm a(2.5, 5, 1, Vector3d(1.0, 0, 0), Vector3d(0, 1.0, 0), Vector3d(0, 0, 1.0));
//a.rotateWhole(-45);
//a.rotateLower(-15);
//Leg a(5.0, 2.5, 1, Vector3d(1.0, 0, 0), Vector3d(0, 1.0, 0), Vector3d(0, 0, 1.0), Vector3d(0, 1.0, 1.0));
//a.rotateWhole(-45);
//a.rotateLower(-15);
//Robot a;
//Window::addNode(Window::getRoot(), a.getRoot());
Window::init();
glutReshapeFunc(Window::reshapeCallback);
glutDisplayFunc(Window::displayCallback);
glutKeyboardFunc(Window::keyboardProcess);
glutIdleFunc(Window::idleCallback);
glutMouseFunc(Window::mouseProcess);
glutMotionFunc(Window::mouseMotionProcess);
//glutPassiveMotionFunc(Window::mousePassiveMotionProcess);
glutSpecialFunc(Window::processSpecialKeys);
glutMainLoop();
//*/
}<file_sep>#ifndef _WINDOW_H_
#define _WINDOW_H_
#include "Vector4d.h"
#include "Camera.h"
#include "Group.h"
#include "Node.h"
#include "MatrixTransform.h"
#include "Cube.h"
#include "Sphere.h"
#include "FrustumCulling.h"
#include "parser.h"
class Window // OpenGL output window related routines
{
public:
static int width, height; // window size
static int old_x, old_y;
static void init();
static void idleCallback(void);
static void reshapeCallback(int, int);
static void displayCallback(void);
static void keyboardProcess(unsigned char key, int x, int y);
static void processSpecialKeys(int k, int x, int y);
static void mouseMotionProcess(int, int);
static void mouseProcess(int, int, int, int);
private :
static MatrixTransform* root;
static MatrixTransform* bunny;
static MatrixTransform* dragon;
static MatrixTransform* bear;
static MatrixTransform* spotL;
static MatrixTransform* pointL;
static MatrixTransform* scaling_mt;
static MatrixTransform* rotate_mt;
static FrustumCulling fc;
static Matrix4d calculateScalingMatrix(int w, int h, Coordinate3d min, Coordinate3d max);
static Vector3d trackBallMapping(int x, int y);
};
#endif
<file_sep>#ifndef _CONST_H_
#define _CONST_H_
namespace control{
enum KEY{ F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12 };
}
namespace draw{
enum mode{WIRE, SOLID};
}
#endif | 04d7e1c71dc7a634cd8495bbfa9e39d8a07ca3a9 | [
"C++"
] | 7 | C++ | haymh/cse167_pro5 | 819d54fcf8730d24c930a358482076c402a6a3fc | e66a613a6087d69d2f2b17c79334fa2a2ced214b |
refs/heads/main | <repo_name>kaue22/ApostasPessoal<file_sep>/assets/js/script.js
$('#form').submit(function (e) {
e.preventDefault();
/* var fvalue = $('#fvalue').val();
var svalue = $('#svalue').val();
*/
var data = $("#form").serialize();
$.ajax({
// url: 'http://localhost/Estudo/exercicios/exercicio1/inserir.php',
method: 'POST',
data: data,
dataType: 'json'
}).done(function (result) {
console.log(result);
});
});
| 5161d6d5624a5e9d997f2c6ebfaafb4feff17bc4 | [
"JavaScript"
] | 1 | JavaScript | kaue22/ApostasPessoal | 2664e17ea2061a772c7f2620e1f87c1429724cba | b1d9f4db59c8265c3426cf631c1b241c4e20f2e0 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace CoreBolillero
{
class Simulacion
{
Bolillero bolillero = new Bolillero();
public bool jugar (List<byte> jugadas)
{
var comparar = 0;
bolillero.Reingresar();
foreach (var bolillaJugada in jugadas)
{
comparar = bolillero.SacarBolilla();
if (comparar != bolillaJugada)
{
return false;
}
}
return true;
}
public long jugarNveces(List<byte> jugadas, long cantJugar)
{
long cantGanados = 0;
for (long i = 0; i < cantJugar; i++)
{
if (this.jugar(jugadas) == true)
{
cantGanados++;
}
}
return cantGanados;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CoreBolillero
{
public class Bolillero
{
public List<byte> adentro { get; set; }
public List<byte> afuera { get; set; }
private Random r { get; set; }
public Bolillero(byte inicio, byte fin)
{
var r = new Random();
this.cargarBolillero(inicio, fin);
}
private void cargarBolillero(byte inicio, byte fin)
{
for (byte i = inicio; i < fin; i++)
{
adentro.Add(i);
}
}
public byte SacarBolilla()
{
var indice = 0;
indice = r.Next(0, adentro.Count);
var bolilla = adentro[indice];
return bolilla;
}
public void Reingresar()
{
adentro.AddRange(afuera);
afuera.Clear();
}
}
}
| ad9441be33aaa74f1a4830a45a4df17a023afe72 | [
"C#"
] | 2 | C# | angelcr25/BolilleroAngel | 99fd134fa4c1a0fb1bb1f4823ca0ce9ab178c76e | bfad945ff180cf5805d6ce5a250f2f80377bcaf9 |
refs/heads/master | <repo_name>contactravi676/styrish_eseizers<file_sep>/styrish/src/com/styrish/footer/dao/FooterLinksDAOImpl.java
package com.styrish.footer.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.styrish.connections.JDBCHelper;
import com.styrish.footer.action.ContactUsAction;
public class FooterLinksDAOImpl extends JDBCHelper {
protected static final String CLASSNAME = "FooterLinksDAOImpl";
protected static final Logger LOGGER = Logger.getLogger(CLASSNAME);
protected static final String CREATE_CONTACTUS_SQL = "insert into contactus (name,mobile,email,message)values(?,?,?,?) ";
public void createContactUs(ContactUsAction contactUsAction) {
final String METHODNAME = "createContactUs";
Connection connection = super.getConnection();
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(CREATE_CONTACTUS_SQL);
preparedStatement.setString(1, contactUsAction.getName());
preparedStatement.setString(2, contactUsAction.getMobile());
preparedStatement.setString(3, contactUsAction.getEmail());
preparedStatement.setString(4, contactUsAction.getMessage());
preparedStatement.execute();
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME + " " + e);
} finally {
try {
if (connection != null) {
connection.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
}
}
}
<file_sep>/styrish/src/com/styrish/users/action/UserRegistrationAction.java
package com.styrish.users.action;
import java.util.Map;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.users.dao.UserRegistrationDaoImpl;
public class UserRegistrationAction extends ActionSupport implements SessionAware {
private static final long serialVersionUID = -2613425890762568273L;
private String firstName;
private String password;
private String mobile;
private String email;
private String confirmPassword;
private String role;
private SessionMap<String,Object> sessionMap;
UserRegistrationDaoImpl userRegistrationDaoImpl = new UserRegistrationDaoImpl();
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public void setSession(Map<String, Object> map) {
sessionMap=(SessionMap<String, Object>)map;
}
public String Users() {
return "Users";
}
public String execute() {
userRegistrationDaoImpl.save(this);
Map userMap=userRegistrationDaoImpl.fetchUserMap(email) ;
sessionMap.put("userId", userMap.get("user_id"));
sessionMap.put("userName", userMap.get("userName"));
sessionMap.put("user_type", userMap.get("user_type"));
return SUCCESS;
}
public void validate(){
if(!(getPassword().equals(getConfirmPassword()))){
addFieldError("confirmPassword", "Confirm password must be equal to password");
}
String exitUser=userRegistrationDaoImpl.getUserId(email);
if(exitUser!=null){
addFieldError("email", "EmailId is already exist");
}
}
}
<file_sep>/styrish/src/com/styrish/tutor/action/TutorPanelAction.java
package com.styrish.tutor.action;
import java.util.Map;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class TutorPanelAction extends ActionSupport implements SessionAware {
private static final long serialVersionUID = 1L;
private String courseId;
private SessionMap<String,Object> sessionMap;
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
@Override
public void setSession(Map<String, Object> map) {
sessionMap=(SessionMap<String, Object>)map;
}
public String execute() throws Exception {
sessionMap.put("courseIdSession", courseId);
return "success";
}
}
<file_sep>/styrish/src/com/styrish/users/teacherpanel/action/TeachersBaseAction.java
package com.styrish.users.teacherpanel.action;
import org.apache.commons.lang3.StringUtils;
import com.opensymphony.xwork2.ActionSupport;
public class TeachersBaseAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = -543418229560738292L;
protected String URL;
protected String actionType;
@Override
public String execute() throws Exception {
if(!StringUtils.isEmpty(actionType) && actionType.equalsIgnoreCase("uploadContent")) {
this.setURL("UploadContent.jsp");
}
if(!StringUtils.isEmpty(actionType) && actionType.equalsIgnoreCase("ViewAccountDetails")) {
this.setURL("ViewAccountDetails.jsp");
}
if(!StringUtils.isEmpty(actionType) && actionType.equalsIgnoreCase("changePassword")) {
this.setURL("ChangePassword.jsp");
}
return super.execute();
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getActionType() {
return actionType;
}
public void setActionType(String actionType) {
this.actionType = actionType;
}
}
<file_sep>/styrish/src/com/styrish/courses/topics/action/TopicCreateExerciseAction.java
package com.styrish.courses.topics.action;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.courses.topics.dao.CourseTopicsDaoImpl;
public class TopicCreateExerciseAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String question;
private String optionA;
private String optionB;
private String optionC;
private String optionD;
private String correctOption;
private String questionHint;
private String topicId;
private String userId;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getOptionA() {
return optionA;
}
public void setOptionA(String optionA) {
this.optionA = optionA;
}
public String getOptionB() {
return optionB;
}
public void setOptionB(String optionB) {
this.optionB = optionB;
}
public String getOptionC() {
return optionC;
}
public void setOptionC(String optionC) {
this.optionC = optionC;
}
public String getOptionD() {
return optionD;
}
public void setOptionD(String optionD) {
this.optionD = optionD;
}
public String getCorrectOption() {
return correctOption;
}
public void setCorrectOption(String correctOption) {
this.correctOption = correctOption;
}
public String getQuestionHint() {
return questionHint;
}
public void setQuestionHint(String questionHint) {
this.questionHint = questionHint;
}
public String getTopicId() {
return topicId;
}
public void setTopicId(String topicId) {
this.topicId = topicId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String execute() throws Exception {
HttpSession session=ServletActionContext.getRequest().getSession(false);
if(session!=null) {
userId=(String) session.getAttribute("userId");
}
CourseTopicsDaoImpl courseTopicsDaoImpl=new CourseTopicsDaoImpl();
courseTopicsDaoImpl.insertExerciseQuestion(this);
return SUCCESS;
}
}
<file_sep>/styrish/WebContent/js/result.js
function data(globalData){
datapoint=[];
arr=[];
for(i=0;i<globalData.length;i++)
{
arr=[];
arr["y"]=(globalData[i].correct/globalData[i].Totalquestion)*100;
arr["label"]=globalData[i].subject;
datapoint.push(arr);
}
var chart = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
data: [{
type: "pie",
startAngle: 240,
yValueFormatString: "##0.00\"%\"",
indexLabel: "{label} {y}",
dataPoints: datapoint
}]
});
chart.render();
chart = new CanvasJS.Chart("chartContainer2", {
animationEnabled: true,
data: [{
type: "bar",
startAngle: 240,
yValueFormatString: "##0.00\"%\"",
indexLabel: "{label} {y}",
dataPoints: datapoint
}]
});
chart.render();
var body="";
for(i=0;i<globalData.length;i++)
body+=` <div class="col-sm-4" id="subject_details">
<h3>${globalData[i].subject}</h3>
<hr>
<p> we offer this course</p>
<button class="btn btn-info" >view details</button>
</div>`;
$("#courses").append(body);
}
window.onload = function() {
$.ajax({
type: "GET",
url: "http://fakerestapi.azurewebsites.net",
dataType: "jsonp",
success: function(data){
data();
},
complete: function(){
//sample data
var globalData=[];
var arr=[];
arr["subject"]="science";
arr["Totalquestion"]=10;
arr["correct"]=10;
globalData.push(arr);
arr=[];
arr["subject"]="Math";
arr["Totalquestion"]=10;
arr["correct"]=5;
globalData.push(arr);
data(globalData);
}
});
}<file_sep>/styrish/src/com/styrish/courses/dao/CoursesDaoImpl.java
package com.styrish.courses.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.styrish.connections.JDBCHelper;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CoursesDaoImpl extends JDBCHelper{
protected static final String CLASSNAME = "CoursesDaoImpl";
protected static final Logger LOGGER = Logger.getLogger(CLASSNAME);
public List<Map<String,String>> getCourses() {
final String METHODNAME = "getCourses";
Connection con = super.getConnection();
PreparedStatement ps = null;
List<Map<String,String>> courseList =new ArrayList<Map<String,String>>();
try {
ps = con.prepareStatement("SELECT course_id,course,description FROM courses ORDER BY course");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Map<String, String> courseMap = new HashMap<String, String>();
courseMap.put("courseId", rs.getString("course_id"));
courseMap.put("course", rs.getString("course"));
courseMap.put("description", rs.getString("description"));
courseList.add(courseMap);
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
finally {
try {
if (con != null) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
}
return courseList;
}
public List<Map<String,String>> getSubCourses(String courseId) {
final String METHODNAME = "getSubCourses";
LOGGER.log(Level.INFO, "logging: course id is {0} ", new Object[] { courseId});
Connection con = super.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List<Map<String,String>> subCourseList =new ArrayList<Map<String,String>>();
try {
ps = con.prepareStatement("SELECT subcourses_id,subcourse,description FROM subcourses WHERE courses_id=?");
ps.setString(1, courseId);
rs = ps.executeQuery();
while (rs.next()) {
Map<String, String> subCourseMap = new HashMap<String, String>();
subCourseMap.put("subcoursesId", rs.getString("subcourses_id"));
subCourseMap.put("subcourse", rs.getString("subcourse"));
subCourseMap.put("description", rs.getString("description"));
subCourseList.add(subCourseMap);
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
finally {
try {
if (con != null) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
}
return subCourseList;
}
public List<Map<String,String>> getCourseSubjects(String courseId) {
final String METHODNAME = "getCourseSubjects";
LOGGER.log(Level.INFO, "logging: course id is {0} ", new Object[] { courseId});
Connection con = super.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List<Map<String,String>> courseSubjectList =new ArrayList<Map<String,String>>();
try {
ps = con.prepareStatement("select subjects.subjects_name,subjects.subjects_description,coursesubject_id from subjects inner join coursesubject on(subjects.subjects_id=coursesubject.subjects_id) where course_id=?");
ps.setString(1, courseId);
rs = ps.executeQuery();
while (rs.next()) {
Map<String, String> subjectMap = new HashMap<String, String>();
subjectMap.put("coursesubject_id", rs.getString("coursesubject_id"));
subjectMap.put("subjectname", rs.getString("subjects_name"));
subjectMap.put("description", rs.getString("subjects_description"));
courseSubjectList.add(subjectMap);
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
finally {
try {
if (con != null) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
}
return courseSubjectList;
}
public List<Map<Long,String>> getCourseSubject(String courseId) {
final String METHODNAME = "getCourseSubjects";
LOGGER.log(Level.INFO, "logging: course id is {0} ", new Object[] { courseId});
Connection con = super.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List<Map<Long,String>> courseSubjectList =new ArrayList<Map<Long,String>>();
try {
ps = con.prepareStatement("select subjects.subjects_name,subjects.subjects_description,coursesubject_id from subjects inner join coursesubject on(subjects.subjects_id=coursesubject.subjects_id) where course_id=?");
ps.setString(1, courseId);
rs = ps.executeQuery();
while (rs.next()) {
Map<Long, String> subjectMap = new HashMap<Long, String>();
subjectMap.put(rs.getLong("coursesubject_id"), rs.getString("subjects_name"));
courseSubjectList.add(subjectMap);
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
finally {
try {
if (con != null) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
}
return courseSubjectList;
}
public List<Map<String, String>> getCourseTopics(String courseId,String subjectId) {
final String METHODNAME = "getCourseTopics";
LOGGER.log(Level.INFO, "logging: course id is {0} and subjectId : ", new Object[] { courseId,subjectId});
Connection con = super.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List<Map<String,String>> courseSubjectList =new ArrayList<Map<String,String>>();
try {
ps = con.prepareStatement("select coursetopic_id,topic_name,shortdescription from coursetopics where course_id=? and subject_id=?");
ps.setString(1, courseId);
ps.setString(2, subjectId);
rs = ps.executeQuery();
while (rs.next()) {
Map<String, String> courseTopicsMap = new HashMap<String, String>();
courseTopicsMap.put("coursetopic_id",rs.getString("coursetopic_id"));
courseTopicsMap.put("topic_name", rs.getString("topic_name"));
courseTopicsMap.put("shortdescription", rs.getString("shortdescription"));
courseSubjectList.add(courseTopicsMap);
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
finally {
try {
if (con != null) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
}
return courseSubjectList;
}
}
<file_sep>/styrish/WebContent/js/ApplicationAJAXServices.js
/**
*
*/
ApplicationAJAXServicesJS = {
AccountLoginServiceAjax : function(redirectURL) {
$('.btn').hide();
$('#loadingmessage').show();
$("#exceptionMessage").html("");
$("#successMessage").html("");
$("#loginModalWindowFormId").ajaxSubmit(
{
url : "ajax/AjaxAccountLoginAction",
type : "post",
dataType : "json",
responseType : "json",
success : function(data) {
if (data.loginSuccess == true) {
if (redirectURL != null && redirectURL != "") {
if (data.usersId != null) {
redirectURL = redirectURL + "&usersId="
+ data.usersId;
}
}
window.location.href = redirectURL;
} else {
$("#exceptionMessage").html("Login Failed");
}
$('.btn').show();
$('#loadingmessage').hide();
},
error : function(xhr, errorType, exception) {
}
});
},
AccountTeachersLoginServiceAjax : function(redirectURL) {
$("#teachersLoginFormId").ajaxSubmit(
{
url : "../ajax/AjaxTeachersAccountLoginAction",
type : "post",
dataType : "json",
responseType : "json",
success : function(data) {
if (data.loginSuccess == true) {
if (redirectURL != null && redirectURL != "") {
redirectURL = redirectURL;
}
window.location.href = redirectURL;
} else {
$("#exceptionMessage").html("Login Failed");
}
},
error : function(xhr, errorType, exception) {
alert("some error"+exception);
}
});
},
AccountRegistrationServiceAjax : function(redirectURL) {
$('.btn').hide();
$('#loadingmessage').show();
$("#exceptionMessage").html("");
$("#successMessage").html("");
$("#loginModalWindowFormId").ajaxSubmit(
{
url : "ajax/AjaxAccountRegisterAction",
type : "post",
dataType : "json",
responseType : "json",
success : function(data) {
var validationMessages = data.validationMessages;
if (data.exceptionMessage != null) {
$("#exceptionMessage").html(
data.exceptionMessage);
$('.btn').show();
$('#loadingmessage').hide();
}else if(validationMessages.includes("ERR_UNACTIVATED_ACCOUNT_EXISTS"))
{
LoginRegisterModalWindowJS.enableOTPVerifyAreaForRegister();
$("#successMessage").html(
"Your Account already exists but not activated , To activate it " +
",please verify the mobile number with " +
"One Time Password sent on your registered mobile.");
} else if (data.otpCreated == true) {
LoginRegisterModalWindowJS.enableOTPVerifyAreaForRegister();
$("#successMessage").html(
"Your Account has been created, To activate it " +
",please verify the mobile number with " +
"One Time Password sent on your registered mobile.");
}
if(data.otpValidated == true){
if (redirectURL != null && redirectURL != "") {
if (data.usersId != null) {
redirectURL = redirectURL + "&usersId="
+ data.usersId;
}
}
window.location.href = redirectURL;
$('.btn').show();
$('#loadingmessage').hide();
$('#myModal').modal('toggle');
} else {
/*
* if (data.exceptionMessage != null) {
* $("#exceptionMessage").html(
* data.exceptionMessage); }
*/
}
},
error : function(data) {
}
});
},
OTPLoginServiceAjax : function(mobileNumber, actionType, otp, redirectURL) {
$('.btn').hide();
$('#loadingmessage').show();
$("#exceptionMessage").html("");
$("#successMessage").html("");
$
.ajax({
type : "POST",
url : "ajax/AjaxOTPLoginAction",
data : (otp != null) ? "mobileNumber=" + mobileNumber
+ "&actionType=" + actionType + "&otp=" + otp
: "mobileNumber=" + mobileNumber + "&actionType="
+ actionType,
dataType : 'json',
responseType : 'json',
success : function(data) {
var ht = data.msg;
var otp = data.otp;
var otpValidated = data.otpValidated;
if(data.exceptionMessage != null) {
$("#exceptionMessage").html(
data.exceptionMessage);
if (data.exceptionMessageKey == "ERR_OTP_EXPITRED"
|| data.exceptionMessageKey == "ERR_WAIT_TO_REGENRATE_OTP") {
$('#loadingmessage').hide();
$('.btn').show();
}
}else if (otp != null) {
$('#loadingmessage').hide();
$("#mobileNumberArea").css("display", "none");
$("#otpArea").css("display", "block");
$('.btn').show();
$("#actionType").val("verifyOTP");
$("#otploginButtonModal").val("Verify OTP");
}
if (otpValidated != null && otpValidated == true) {
if (redirectURL != null && redirectURL != "") {
if (data.usersId != null) {
redirectURL = redirectURL + "&usersId="
+ data.usersId;
}
}
window.location.href = redirectURL;
}
},
error : function(xhr, errorType, exception) {
}
});
},
AddItem2ShopCartAjax : function(productId, userId) {
var productId = productId;
var userId = userId;
$('.btn').hide();
$('#loadingmessage1').show();
$.ajax({
type : "POST",
url : "ajax/AjaxOrderItemAddAction",
data : "productId=" + productId + "&userId=" + userId,
dataType : 'json',
success : function(data) {
var ht = data.msg;
//$("#resp").html(ht);
$('#loadingmessage1').hide();
$('#miniShopCartist').load('miniShopCartContent.jsp');
$("#myModal1").modal('show');
$('.btn').show();
$('#orderIdHidden').val(data.ordersId);
},
error : function(data) {
alert("Some error occured.");
}
});
},
RemoveItemFromCartAjax : function(orderItemsID, ordersID,usersId) {
var productId = productId;
var userId = userId;
$('#loadingmessageItem_' + orderItemsID).show();
$('#itemRemoveLinkId_' + orderItemsID).hide();
$.ajax({
type : "POST",
url : "ajax/AjaxOrderItemDeleteAction",
data : {
"orderItemsId" : orderItemsID,
"ordersId" : ordersID,
"usersId" : usersId
},
dataType : 'json',
success : function(data) {
/*
* $('#loadingmessageItem_' + orderItemsID).hide();
* $('#itemRemoveLinkId_' + orderItemsID).show();
*/
$('#orderSummaryDivId').load(
'orderAmountDisplay.jsp?ordersId=' + data.ordersId);
$('#miniShopCartist').load('miniShopCartContent.jsp');
$('#shopCartDivId').load(
'orderItemDetail.jsp?ordersId=' + data.ordersId);
// $("#myModalItemRemoved").modal('show');
},
error : function(data) {
alert("Some error occured.");
}
});
},
loadSubjects : function (courseId,teacherPanel) {
$('#uploadContentTopicListID').children().remove().end();
$('#uploadContentSubjectListID').children().remove().end();
courseId=courseId.split("_")[0];
var subjectList;
$.ajax({
type : "POST",
url : "../ajax/AjaxGetSubjectsByCourse",
data : {
"courseId" : courseId
},
dataType : 'json',
respnseType : 'json',
success : function(data) {
subjectList = data.subjectList;
if(subjectList) {
$('#uploadContentSubjectListID').append('<option value="" selected >select</option>');
for (var i = 0; i <= subjectList.length; i++) {
var subject = subjectList[i];
// alert(subject);
var hashtable = {};
$.each(subject, function (key, value) {
// hashtable[key]=value;
if(teacherPanel==true){
$('#uploadContentSubjectListID').append('<option value="' + key +'_' + value + '">' + value + '</option>');
}
});
}
}
},
error : function(data) {
alert("Some error occured.");
}
});
},
loadTopics : function(subjectID,userID) {
$('#uploadContentTopicListID').children().remove().end();
subjectID = subjectID.split("_")[0];
//alert(subjectID);
var topicList;
$.ajax({
type : "POST",
url : "../ajax/AjaxGetTopicBySubjectAndUser",
data : {
"subjectId" : subjectID,
"usersId" : userID
},
dataType : 'json',
respnseType : 'json',
success : function(data) {
topicList = data.topicList;
if(topicList) {
for (var i = 0; i <= topicList.length; i++) {
var topic = topicList[i];
// alert(subject);
var hashtable = {};
$.each(topic, function (key, value) {
//hashtable[key]=value;
$('#uploadContentTopicListID').append('<option value="' + key + '_' + value + '">' + value + '</option>');
});
//console.log(hashtable);
}
$('#uploadContentTopicListID').append('<option value="-1">New Topic</option>');
}
},
error : function(data) {
alert("Some error occured.");
}
});
},
CreateContent : function() {
$("#uploadContentMessage").html("");
$("#fileUploadFormID").ajaxSubmit(
{
url : "../ajax/AjaxUploadContentAction",
type : "post",
dataType : "json",
responseType : "json",
success : function(data) {
var fullPath;
var actionErrors = data.actionErrors;
var errorMessage = '';
if (actionErrors != null && actionErrors.length > 0) {
for (i=0; i<actionErrors.length; i++) {
if (actionErrors[i] != null && actionErrors[i]=='ERR_BLANK_TOPIC') {
errorMessage = errorMessage+"Topic Can not be blank !!<br/>";
}
if (actionErrors[i] != null && actionErrors[i]=='ERR_BLANK_SUBJECT') {
errorMessage = errorMessage+"Subject Can not be blank !!<br/>";
}
if (actionErrors[i] != null && actionErrors[i]=='ERR_BLANK_COURSE') {
errorMessage = errorMessage+"Course Can not be blank !!<br/>";
}
if (actionErrors[i] != null && actionErrors[i]=='ERR_BLANK_CONTENT_TYPE') {
errorMessage = errorMessage+"Content Type Can not be blank !!<br/>";
}
if (actionErrors[i] != null && actionErrors[i]=='ERR_BLANK_FILE') {
errorMessage = errorMessage+"Please select file to upload !!<br/>";
}
}
$("#uploadContentMessage").css("color","red");
$("#uploadContentMessage").html(errorMessage);
} else {
if (data.directoryPath != null && data.directoryPath != '' && data.fileName != null && data.fileName != '') {
fullPath = data.directoryPath+data.fileName;
fullPath = fullPath.trim().replace(/\s/g, '%20');
}
var messageKey = data.message;
var messageValue;
if (messageKey != null && messageKey=='TOPIC_CREATED') {
messageValue = "New Topic Created !!";
} else if (messageKey != null && messageKey=='VERSON_UPDATED') {
messageValue = "New Version of existing topic Created !!";
}
$("#uploadContentMessage").css("color","green");
$("#uploadContentMessage").html(messageValue);
$('#contentDisplayDivId').load('ContentDisplay.jsp?contentType='+data.contentType+'&filePath='+fullPath);
$("#uploadFileButtonDiv").css("display","none");
$("#approveContentButtonDiv").css("display","block");
$("#topicIdHidden").val(data.topicID);
$("#topicVersionHidden").val(data.version);
$("#contentTypeHidden").val(data.contentType);
}
},
error : function(data) {
alert("some error"+data.actionErrors);
}
});
},
ApproveContent : function(contentId,version,contentTypeHidden) {
//alert(contentId+'--'+version+'--'+contentTypeHidden);
$.ajax({
type : "POST",
url : "../ajax/AjaxApproveContentAction",
data : {
"topicID" : contentId,
"version" : version,
"contentTypeHidden" : contentTypeHidden
},
dataType : 'json',
respnseType : 'json',
success : function(data) {
$("#uploadContentMessage").css("color","green");
$("#uploadContentMessage").html("Topic Approved !!");
$("#uploadFileButtonDiv").css("display","block");
$("#approveContentButtonDiv").css("display","none");
},
error : function(data) {
alert("Some error occured.");
}
});
}
}<file_sep>/styrish/src/com/styrish/courses/subjects/dao/CourseSubjectsDaoImpl.java
package com.styrish.courses.subjects.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.styrish.connections.JDBCHelper;
public class CourseSubjectsDaoImpl extends JDBCHelper{
protected static final String CLASSNAME = "CourseSubjectsDaoImpl";
protected static final Logger LOGGER = Logger.getLogger(CLASSNAME);
public List<Map<String,String>> getCourseSubjectList(String courseId) {
final String METHODNAME = "getCourseSubjectList";
LOGGER.log(Level.INFO, "logging: course id is {0} ", new Object[] { courseId});
Connection con = super.getConnection();
PreparedStatement ps = null;
ResultSet rs=null;
List<Map<String,String>> courseSubjectList =new ArrayList<Map<String,String>>();
try {
ps = con.prepareStatement("SELECT coursesubject_id,subjectname,description,longdescription FROM coursesubject WHERE course_id==?");
ps.setString(1, courseId);
rs = ps.executeQuery();
while (rs.next()) {
Map<String, String> courseSubjectMap = new HashMap<String, String>();
courseSubjectMap.put("coursesubject_id", rs.getString("coursesubject_id"));
courseSubjectMap.put("subjectname", rs.getString("subjectname"));
courseSubjectMap.put("description", rs.getString("description"));
courseSubjectMap.put("longdescription", rs.getString("longdescription"));
courseSubjectList.add(courseSubjectMap);
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
finally {
try {
if (con != null) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
}
return courseSubjectList;
}
}
<file_sep>/styrish/src/com/styrish/courses/topics/teacherpanel/action/contents/upload/TopicContentUploadAction.java
package com.styrish.courses.topics.teacherpanel.action.contents.upload;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.courses.topics.dao.CourseTopicsDaoImpl;
import com.styrish.courses.topics.databean.CourseTopic;
public class TopicContentUploadAction extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 6226376767317016623L;
private static final String CLASSNAME = "TopicContentUploadAction";
private static final Logger LOGGER = Logger.getLogger(CLASSNAME);
protected String filesPath;
protected int version;
protected String fileName;
protected File fileUpload;
protected String directoryPath;
protected String destinationPath;
protected Long courseID;
protected String courseName;
protected Long subjectID;
protected String subjectName;
protected Long topicID;
protected String topicName;
protected String contentType;
protected String topicNameText;
protected boolean topicCreatedOnServer;
protected boolean topicCreatedInDb;
protected String message;
protected String errorMessage;
protected Map<String, Object> sessionMap;
protected List<String> errorsList;
protected CourseTopic courseTopic;
protected CourseTopicsDaoImpl courseTopicDAO;
@Override
public String execute() throws IOException {
CourseTopic courseTopic = getCourseTopic();
if (courseTopic.getTopicId() != null) {
fetchExistingTopic(courseTopic);
}
Long courseTopicId = courseTopic.getTopicId();
int version = courseTopic.getVersion().intValue();
int status = courseTopic.getStatus().intValue();
constructDestinationPath();
String file = renameFile(getFileName(), (String) getSessionMap().get("userId"));
setFileName(file.toString());
if (courseTopicId != null) {
version = version + 1;
setFileName(renameFile(getFileName(), new StringBuilder("v").append(version).toString()));
courseTopic.setVersion(version);
courseTopic.setTopicType(getContentType());
courseTopic.setTopicPath(new StringBuilder(getDestinationPath()).append(getFileName()).toString());
createNewTopicOnServer(courseTopic);
if (isTopicCreatedOnServer()) {
upgradeTopicVersion(courseTopic);
setTopicCreatedInDb(true);
setMessage("VERSON_UPDATED");
setVersion(version);
} else {
setErrorMessage("ERR_VERSION_UPGRADING");
}
} else {
courseTopic.setTopicId(System.currentTimeMillis());
courseTopic.setCourseId(getCourseID());
courseTopic.setSubjectId(getSubjectID());
courseTopic.setTopicName(getTopicName());
courseTopic.setTopicDescription(getTopicName());
Long userId = Long.valueOf((String) getSessionMap().get("userId"));
courseTopic.setUserId(userId);
courseTopic.setStatus(0);
courseTopic.setVersion(1);
courseTopic.setTopicType(getContentType());
courseTopic.setTopicPath(new StringBuilder(getDestinationPath()).append(getFileName()).toString());
createNewTopicOnServer(courseTopic);
if (isTopicCreatedOnServer()) {
createTopicInDB(courseTopic);
setTopicCreatedInDb(true);
setMessage("TOPIC_CREATED");
setVersion(version);
setTopicID(courseTopic.getTopicId());
} else {
setErrorMessage("ERR_CREATING_TOPIC");
}
}
return "success";
}
@Override
public void validate() {
final String METHODNAME = "validate";
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
if (!StringUtils.isEmpty(courseName) && StringUtils.contains(courseName, "_")) {
StringTokenizer stringTokenizer = new StringTokenizer(courseName, "_");
while (stringTokenizer.hasMoreTokens()) {
String token = (String) stringTokenizer.nextToken();
Long courseID = Long.valueOf(token);
String courseName = stringTokenizer.nextToken();
setCourseID(courseID);
setCourseName(courseName);
}
} else {
if (errorsList == null) {
errorsList = new ArrayList<String>();
}
errorsList.add("ERR_BLANK_COURSE");
LOGGER.logp(Level.FINE, CLASSNAME, METHODNAME, "Course is not present in request");
}
if (!StringUtils.isEmpty(subjectName) && StringUtils.contains(subjectName, "_")) {
StringTokenizer stringTokenizer = new StringTokenizer(subjectName, "_");
while (stringTokenizer.hasMoreTokens()) {
String token = (String) stringTokenizer.nextToken();
Long subjectID = Long.valueOf(token);
String subjectName = stringTokenizer.nextToken();
setSubjectID(subjectID);
setSubjectName(subjectName);
}
} else {
if (errorsList == null) {
errorsList = new ArrayList<String>();
}
errorsList.add("ERR_BLANK_SUBJECT");
LOGGER.logp(Level.FINE, CLASSNAME, METHODNAME, "Subject is not present in request");
}
if (!StringUtils.isEmpty(topicName) && StringUtils.contains(topicName, "_")) {
StringTokenizer stringTokenizer = new StringTokenizer(topicName, "_");
while (stringTokenizer.hasMoreTokens()) {
String token = (String) stringTokenizer.nextToken();
Long topicID = Long.valueOf(token);
String topicName = stringTokenizer.nextToken();
setTopicID(topicID);
setTopicName(topicName);
}
} else if (!StringUtils.isEmpty(topicNameText)) {
topicNameText = topicNameText.trim();
setTopicName(topicNameText);
} else {
if (errorsList == null) {
errorsList = new ArrayList<String>();
}
errorsList.add("ERR_BLANK_TOPIC");
LOGGER.logp(Level.FINE, CLASSNAME, METHODNAME, "Topic is not present in request");
}
if (StringUtils.isEmpty(contentType)) {
if (errorsList == null) {
errorsList = new ArrayList<String>();
}
errorsList.add("ERR_BLANK_CONTENT_TYPE");
}
if (StringUtils.isEmpty(fileName)) {
if (errorsList == null) {
errorsList = new ArrayList<String>();
}
errorsList.add("ERR_BLANK_FILE");
}
setActionErrors(errorsList);
if (errorsList == null || errorsList.isEmpty()) {
CourseTopic courseTopic = new CourseTopic();
courseTopic.setTopicId(getTopicID());
courseTopic.setTopicName(getTopicName());
courseTopic.setTopicType(getContentType());
setCourseTopic(courseTopic);
}
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.exiting(CLASSNAME, METHODNAME);
}
}
@Override
public void setSession(Map<String, Object> sessionMap) {
this.sessionMap = sessionMap;
}
protected void createTopicInDB(CourseTopic courseTopic) {
CourseTopicsDaoImpl courseTopicsDao = getCourseTopicDAO();
courseTopicsDao.createNewTopic(courseTopic);
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
protected void createNewTopicOnServer(CourseTopic courseTopic) {
try {
File fileToCreate = new File(courseTopic.getTopicPath());
FileUtils.copyFile(getFileUpload(), fileToCreate);
setTopicCreatedOnServer(fileToCreate.exists());
} catch (IOException e) {
e.printStackTrace();
}
}
protected void upgradeTopicVersion(CourseTopic courseTopic) {
CourseTopicsDaoImpl courseTopicsDao = getCourseTopicDAO();
courseTopicsDao.updateTopicVersion(courseTopic);
}
protected void fetchExistingTopic(CourseTopic courseTopic) {
CourseTopicsDaoImpl courseTopicsDao = getCourseTopicDAO();
courseTopic = courseTopicsDao.fetchTopicById(courseTopic);
}
protected void constructDestinationPath() {
final String METHODNAME = "constructDestinationPath";
StringBuilder strB = new StringBuilder(getFilesPath());
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
String dirPath = new StringBuilder().append(getCourseName()).append("//").append(getSubjectName()).append("//")
.append(getTopicName()).append("//").append(getContentType()).append("//").toString();
setDirectoryPath(dirPath);
strB.append(getCourseName()).append("//").append(getSubjectName()).append("//").append(getTopicName())
.append("//").append(getContentType()).append("//");
setDestinationPath(strB.toString());
LOGGER.logp(Level.ALL, CLASSNAME, METHODNAME, "File Path Created Is " + getDestinationPath());
}
public CourseTopicsDaoImpl getCourseTopicDAO() {
if (courseTopicDAO == null) {
courseTopicDAO = new CourseTopicsDaoImpl();
}
return courseTopicDAO;
}
protected String renameFile(String file, String prefix) {
if (fileName != null) {
String fileName = file.substring(0, file.indexOf("."));
String fileType = file.substring(file.indexOf("."), file.length());
StringBuilder strB = new StringBuilder(fileName);
strB.append("_").append(prefix).append(fileType);
file = strB.toString();
}
return file;
}
public String getDirectoryPath() {
return directoryPath;
}
public void setDirectoryPath(String directoryPath) {
this.directoryPath = directoryPath;
}
public void setCourseTopicDAO(CourseTopicsDaoImpl courseTopicDAO) {
this.courseTopicDAO = courseTopicDAO;
}
public String getDestinationPath() {
return destinationPath;
}
public void setDestinationPath(String destinationPath) {
this.destinationPath = destinationPath;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public File getFileUpload() {
return fileUpload;
}
public void setFileUpload(File fileUpload) {
this.fileUpload = fileUpload;
}
public String getFilesPath() {
return filesPath;
}
public void setFilesPath(String filesPath) {
this.filesPath = filesPath;
}
public Long getCourseID() {
return courseID;
}
public void setCourseID(Long courseID) {
this.courseID = courseID;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public Long getSubjectID() {
return subjectID;
}
public void setSubjectID(Long subjectID) {
this.subjectID = subjectID;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public Long getTopicID() {
return topicID;
}
public void setTopicID(Long topicID) {
this.topicID = topicID;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getTopicNameText() {
return topicNameText;
}
public void setTopicNameText(String topicNameText) {
this.topicNameText = topicNameText;
}
public List<String> getErrorsList() {
return errorsList;
}
public void setErrorsList(List<String> errorsList) {
this.errorsList = errorsList;
}
public Map<String, Object> getSessionMap() {
return sessionMap;
}
public void setSessionMap(Map<String, Object> sessionMap) {
this.sessionMap = sessionMap;
}
public CourseTopic getCourseTopic() {
return courseTopic;
}
public void setCourseTopic(CourseTopic courseTopic) {
this.courseTopic = courseTopic;
}
public boolean isTopicCreatedOnServer() {
return topicCreatedOnServer;
}
public void setTopicCreatedOnServer(boolean topicCreatedOnServer) {
this.topicCreatedOnServer = topicCreatedOnServer;
}
public boolean isTopicCreatedInDb() {
return topicCreatedInDb;
}
public void setTopicCreatedInDb(boolean topicCreatedInDb) {
this.topicCreatedInDb = topicCreatedInDb;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
<file_sep>/styrish/src/com/styrish/student/action/StudentMockTestPaperSubmitAction.java
package com.styrish.student.action;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class StudentMockTestPaperSubmitAction extends ActionSupport implements ServletContextAware {
private static final long serialVersionUID = 1L;
private String mockTestId;
private String courseId;
private String userId;
private String questionId;
private String correctOption;
private String optionA;
private String optionB;
private String optionC;
private String optionD;
private ServletContext servletContext;
public void setServletContext(ServletContext context) {
servletContext=context;
}
public String getMockTestId() {
return mockTestId;
}
public void setMockTestId(String mockTestId) {
this.mockTestId = mockTestId;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getQuestionId() {
return questionId;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public String getCorrectOption() {
return correctOption;
}
public void setCorrectOption(String correctOption) {
this.correctOption = correctOption;
}
public String getOptionA() {
return optionA;
}
public void setOptionA(String optionA) {
this.optionA = optionA;
}
public String getOptionB() {
return optionB;
}
public void setOptionB(String optionB) {
this.optionB = optionB;
}
public String getOptionC() {
return optionC;
}
public void setOptionC(String optionC) {
this.optionC = optionC;
}
public String getOptionD() {
return optionD;
}
public void setOptionD(String optionD) {
this.optionD = optionD;
}
public String execute() {
HttpSession session=ServletActionContext.getRequest().getSession(false);
if(session.getAttribute("courseIdSession")!=null) {
courseId=(String) session.getAttribute("courseIdSession");
userId=(String) session.getAttribute("userId");
}
return SUCCESS;
}
}
<file_sep>/styrish/src/com/styrish/links/action/LinkAction.java
package com.styrish.links.action;
import com.opensymphony.xwork2.ActionSupport;
public class LinkAction extends ActionSupport {
private static final long serialVersionUID = -2613425890762568273L;
private String userLogin;
public String getUserLogin() {
return userLogin;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
}
<file_sep>/styrish/src/com/styrish/shopping/action/OrderRefreshAndInitiatePaymentAction.java
package com.styrish.shopping.action;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.shopping.beans.OrderDataBean;
import com.styrish.shopping.dao.OrdersDAOImpl;
public class OrderRefreshAndInitiatePaymentAction extends ActionSupport {
/**
* ===================================================================================================================
* This command will have the behaviour as : 1). Refresh order by canceling the
* previous order and updating the current logged in user id to new order if
* needed. 2). Initiate a payment and redirecting to payment site.
* ===================================================================================================================
*/
private static final long serialVersionUID = 1L;
protected Long ordersId;
protected Long usersId;
protected String URL;
@Override
public String execute() throws Exception {
moveOrderToLoggedInUser();
createPaymentProviderURL();
return "success";
}
protected void moveOrderToLoggedInUser() {
OrderDataBean orderDataBean = new OrderDataBean();
orderDataBean.setOrdersId(getOrdersId());
orderDataBean.setAccessProfile("OrderSummaryData");
OrdersDAOImpl ordersDAOImpl = new OrdersDAOImpl();
ordersDAOImpl.fetchOrderDetails(orderDataBean);
Long usersID = orderDataBean.getUsersId();
if (usersID != null && !usersID.equals(getUsersId())) {
// cancel any previous order for the logged in user, the current order will be
// treted as its new order.
orderDataBean.resetOrderDataBean();
orderDataBean.setUsersId(getUsersId());
ordersDAOImpl.findCurrentPendingOrderForUser(orderDataBean);
if (orderDataBean.getOrdersId() != null) {
ordersDAOImpl.cancelOrder(orderDataBean);
}
orderDataBean.setOrdersId(getOrdersId());
ordersDAOImpl.updateOrderOwner(orderDataBean);
}
}
public Long getOrdersId() {
return ordersId;
}
public void setOrdersId(Long ordersId) {
this.ordersId = ordersId;
}
public Long getUsersId() {
return usersId;
}
public void setUsersId(Long usersId) {
this.usersId = usersId;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
protected void createPaymentProviderURL() {
String redirectURL = "orderPaymentCallBackAction?ordersId=" + getOrdersId();
this.setURL(redirectURL);
}
}
<file_sep>/styrish/src/com/styrish/courses/product/action/ProductDetailAction.java
package com.styrish.courses.product.action;
import java.util.*;
import com.opensymphony.xwork2.ActionSupport;
public class ProductDetailAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String packId;
private List<Map<String, String>> productDetailsList;
public String getPackId() {
return packId;
}
public void setPackId(String packId) {
this.packId = packId;
}
public List<Map<String, String>> getProductDetailsList() {
return productDetailsList;
}
public void setProductDetailsList(List<Map<String, String>> productDetailsList) {
this.productDetailsList = productDetailsList;
}
public String execute() {
return SUCCESS;
}
}
<file_sep>/styrish/src/com/styrish/commons/util/objects/CachedObject.java
package com.styrish.commons.util.objects;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CachedObject implements Cacheable {
private java.util.Date dateofExpiration = null;
private Object identifier = null;
public Object object = null;
protected static final String CLASSNAME = "CachedObject";
protected static final Logger LOGGER = Logger.getLogger(CLASSNAME);
public CachedObject(Object obj, Object id, int minutesToLive) {
this.object = obj;
this.identifier = id;
// minutesToLive of 0 means it lives on indefinitely.
if (minutesToLive != 0) {
dateofExpiration = new java.util.Date();
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setTime(dateofExpiration);
cal.add(Calendar.MINUTE, minutesToLive);
dateofExpiration = cal.getTime();
}
}
@Override
public boolean isExpired() {
final String METHODNAME = "isExpired";
// Remember if the minutes to live is zero then it lives forever!
if (dateofExpiration != null) {
// date of expiration is compared.
if (dateofExpiration.before(new java.util.Date())) {
LOGGER.logp(Level.FINEST, CLASSNAME, METHODNAME,
"CachedResultSet.isExpired: Expired from Cache! EXPIRE TIME: " + dateofExpiration.toString()
+ " CURRENT TIME: " + (new java.util.Date()).toString());
return true;
} else {
LOGGER.logp(Level.FINEST, CLASSNAME, METHODNAME,
"Cache Object Not Expired Yet, will be served !");
return false;
}
} else // This means it lives forever!
return false;
}
@Override
public Object getIdentifier() {
return identifier;
}
}
<file_sep>/styrish/src/com/styrish/courses/topics/databean/CourseTopic.java
package com.styrish.courses.topics.databean;
import java.io.Serializable;
public class CourseTopic implements Serializable {
/**
* Course Topic DTO having its getters and setters
*/
private static final long serialVersionUID = 1014927254502544519L;
protected Long topicId;
protected Long courseId;
protected Long subjectId;
protected Long userId;
protected String topicName;
protected String topicDescription;
protected int status;
protected String topicType;
protected String topicPath;
protected int version;
public Long getTopicId() {
return topicId;
}
public void setTopicId(Long topicId) {
this.topicId = topicId;
}
public Long getCourseId() {
return courseId;
}
public void setCourseId(Long courseId) {
this.courseId = courseId;
}
public Long getSubjectId() {
return subjectId;
}
public void setSubjectId(Long subjectId) {
this.subjectId = subjectId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getTopicDescription() {
return topicDescription;
}
public void setTopicDescription(String topicDescription) {
this.topicDescription = topicDescription;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getTopicType() {
return topicType;
}
public void setTopicType(String topicType) {
this.topicType = topicType;
}
public String getTopicPath() {
return topicPath;
}
public void setTopicPath(String topicPath) {
this.topicPath = topicPath;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CourseTopic [topicId=");
builder.append(topicId);
builder.append(", courseId=");
builder.append(courseId);
builder.append(", subjectId=");
builder.append(subjectId);
builder.append(", userId=");
builder.append(userId);
builder.append(", topicName=");
builder.append(topicName);
builder.append(", topicDescription=");
builder.append(topicDescription);
builder.append(", status=");
builder.append(status);
builder.append(", topicType=");
builder.append(topicType);
builder.append(", topicPath=");
builder.append(topicPath);
builder.append(", version=");
builder.append(version);
builder.append("]");
return builder.toString();
}
}
<file_sep>/styrish/src/com/styrish/users/action/UserLoginAction.java
package com.styrish.users.action;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.users.dao.UserRegistrationDaoImpl;
import java.util.Map;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
public class UserLoginAction extends ActionSupport implements SessionAware{
private static final long serialVersionUID = 1L;
private String username;
private String password;
private SessionMap<String, Object> sessionMap;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
UserRegistrationDaoImpl userRegistrationDaoImpl = new UserRegistrationDaoImpl();
@Override
public void validate() {
boolean aunthatication=userRegistrationDaoImpl.validateLogin(username,password);
if (getUsername().length() == 0) {
addFieldError("userName", "UserName.required");
}else if (getPassword().length() == 0) {
addFieldError("password", getText("password.required"));
}else if (aunthatication == false) {
addFieldError("password", "Invalid UserName or Password");
}
}
public String execute() {
Map<String,String> userMap=userRegistrationDaoImpl.fetchUserMap(username) ;
sessionMap.put("userId", userMap.get("user_id"));
sessionMap.put("userName", userMap.get("userName"));
sessionMap.put("user_type", userMap.get("user_type"));
sessionMap.put("userType", "R");
return SUCCESS;
}
@Override
public void setSession(Map<String, Object> sessionMap) {
this.sessionMap = (SessionMap<String, Object>) sessionMap;
}
}<file_sep>/styrish/src/com/styrish/mocktest/action/TutorMockTestCreateAction.java
package com.styrish.mocktest.action;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.*;
import com.styrish.mocktest.dao.MockTestDaoImpl;
public class TutorMockTestCreateAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String courseId;
private String userId;
private String subCourseId;
private String mocktestName;
private String totalQuestions;
private String totalTime;
private String examGuidlines;
private String mocktestStatus;
private String mockTestId;
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getSubCourseId() {
return subCourseId;
}
public void setSubCourseId(String subCourseId) {
this.subCourseId = subCourseId;
}
public String getMocktestName() {
return mocktestName;
}
public void setMocktestName(String mocktestName) {
this.mocktestName = mocktestName;
}
public String getTotalQuestions() {
return totalQuestions;
}
public void setTotalQuestions(String totalQuestions) {
this.totalQuestions = totalQuestions;
}
public String getTotalTime() {
return totalTime;
}
public void setTotalTime(String totalTime) {
this.totalTime = totalTime;
}
public String getExamGuidlines() {
return examGuidlines;
}
public void setExamGuidlines(String examGuidlines) {
this.examGuidlines = examGuidlines;
}
public String getMocktestStatus() {
return mocktestStatus;
}
public void setMocktestStatus(String mocktestStatus) {
this.mocktestStatus = mocktestStatus;
}
public String getMockTestId() {
return mockTestId;
}
public void setMockTestId(String mockTestId) {
this.mockTestId = mockTestId;
}
public String execute() throws Exception {
MockTestDaoImpl mockTestDaoImpl=new MockTestDaoImpl();
HttpSession session=ServletActionContext.getRequest().getSession(false);
if(session.getAttribute("courseIdSession")!=null) {
courseId=(String) session.getAttribute("courseIdSession");
}
if(session.getAttribute("userId")!=null) {
userId=(String) session.getAttribute("userId");
}
mockTestDaoImpl.createMockTest(this);
Map<String,String> mockTestMap =mockTestDaoImpl.getMockTestByName(mocktestName, subCourseId);
mockTestId=mockTestMap.get("mocktest_id");
return "success";
}
}
<file_sep>/styrish/src/com/styrish/courses/dao/CourseTopicDaoImpl.java
package com.styrish.courses.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.styrish.connections.JDBCHelper;
public class CourseTopicDaoImpl {
public Map<String, List> getCourseTopicsVideos(String topicId) {
Map<String, List> courseTopicVideoMap = new HashMap<String, List>();
try {
Connection con = JDBCHelper.getConnection();
PreparedStatement ps = con.prepareStatement("select videos_title,videos_path,videos_description from videos where topic_id=?");
ps.setString(1, topicId);
ResultSet rs = ps.executeQuery();
List videopathList=new ArrayList();
List videoTitleList=new ArrayList();
List videoDescriptionList=new ArrayList();
while (rs.next()) {
videopathList.add(rs.getString("videos_path"));
videoTitleList.add(rs.getString("videos_title"));
videoDescriptionList.add(rs.getString("videos_description"));
}
courseTopicVideoMap.put("videoTitle", videoTitleList);
courseTopicVideoMap.put("videosPath", videopathList);
courseTopicVideoMap.put("videosDescription", videoDescriptionList);
} catch (Exception e) {
e.printStackTrace();
}
return courseTopicVideoMap;
}
public Map<String, List> getCourseTopicsContent(String topicId) {
Map<String, List> courseTopicContentMap = new HashMap<String, List>();
try {
Connection con = JDBCHelper.getConnection();
PreparedStatement ps = con.prepareStatement("select document_title,document_path,document_description from documents where topic_id=?");
ps.setString(1, topicId);
ResultSet rs = ps.executeQuery();
List contentpathList=new ArrayList();
List contentTitleList=new ArrayList();
List contentDescriptionList=new ArrayList();
while (rs.next()) {
contentpathList.add(rs.getString("document_path"));
contentTitleList.add(rs.getString("document_title"));
contentDescriptionList.add(rs.getString("document_description"));
}
courseTopicContentMap.put("contentTitle", contentTitleList);
courseTopicContentMap.put("contentPath", contentpathList);
courseTopicContentMap.put("contentDescription", contentDescriptionList);
} catch (Exception e) {
e.printStackTrace();
}
return courseTopicContentMap;
}
public List getCourseTopicsExercise(String topicId) {
List exercisesList=null;
try {
Connection con = JDBCHelper.getConnection();
PreparedStatement ps = con.prepareStatement("select question,optionA,optionB,optionC,optionD,correctOption,questionHint from exercises where topic_id=?");
ps.setString(1, topicId);
ResultSet rs = ps.executeQuery();
exercisesList=new ArrayList();
while (rs.next()) {
Map exerciseMap=new HashMap();
exerciseMap.put("question",rs.getString("question"));
exerciseMap.put("optionA",rs.getString("optionA"));
exerciseMap.put("optionB",rs.getString("optionB"));
exerciseMap.put("optionC",rs.getString("optionC"));
exerciseMap.put("optionD",rs.getString("optionD"));
exerciseMap.put("correctOption",rs.getString("correctOption"));
exerciseMap.put("questionHint",rs.getString("questionHint"));
exercisesList.add(exerciseMap);
}
} catch (Exception e) {
e.printStackTrace();
}
return exercisesList;
}
}
<file_sep>/styrish/src/com/styrish/mockvideo/action/TutorMockVideoUploadAction.java
package com.styrish.mockvideo.action;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.mockvideo.dao.MockVideoDaoImpl;
public class TutorMockVideoUploadAction extends ActionSupport implements ServletContextAware {
private static final long serialVersionUID = 1L;
private File document;
private String documentFileName;
private String documentContentType;
private String subcourseId;
private String courseId;
private String userId;
private String documentTitle;
private String documentDescription;
private String documentPath;
private ServletContext servletContext;
public void setServletContext(ServletContext context) {
servletContext=context;
}
public File getDocument() {
return document;
}
public void setDocument(File document) {
this.document = document;
}
public String getDocumentFileName() {
return documentFileName;
}
public void setDocumentFileName(String documentFileName) {
this.documentFileName = documentFileName;
}
public String getDocumentContentType() {
return documentContentType;
}
public void setDocumentContentType(String documentContentType) {
this.documentContentType = documentContentType;
}
public String getSubcourseId() {
return subcourseId;
}
public void setSubcourseId(String subcourseId) {
this.subcourseId = subcourseId;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getDocumentTitle() {
return documentTitle;
}
public void setDocumentTitle(String documentTitle) {
this.documentTitle = documentTitle;
}
public String getDocumentDescription() {
return documentDescription;
}
public void setDocumentDescription(String documentDescription) {
this.documentDescription = documentDescription;
}
public String getDocumentPath() {
return documentPath;
}
public void setDocumentPath(String documentPath) {
this.documentPath = documentPath;
}
public String execute() {
try {
MockVideoDaoImpl mockVideoDaoImpl=new MockVideoDaoImpl();
String documentAdditionPath=mockVideoDaoImpl.getMockVideoAdditionPath(subcourseId);
documentFileName=documentAdditionPath+"_"+documentFileName;
String targetPath = (String) servletContext.getInitParameter("host");
File fileToCreate = new File(targetPath, documentFileName);
setDocumentFileName(documentFileName);
FileUtils.copyFile(this.document, fileToCreate);
documentPath=targetPath+"/"+documentFileName;
HttpSession session=ServletActionContext.getRequest().getSession(false);
if(session.getAttribute("courseIdSession")!=null) {
courseId=(String) session.getAttribute("courseIdSession");
userId=(String) session.getAttribute("userId");
}
mockVideoDaoImpl.createMockVideo(this);
} catch (IOException e) {
addActionError(e.getMessage());
}
return "success";
}
}<file_sep>/styrish/src/com/styrish/shopping/action/ShoppingCartDetailAction.java
package com.styrish.shopping.action;
import com.opensymphony.xwork2.ActionSupport;
public class ShoppingCartDetailAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long ordersId;
@Override
public String execute() throws Exception {
return "success";
}
public Long getOrdersId() {
return ordersId;
}
public void setOrdersId(Long ordersId) {
this.ordersId = ordersId;
}
}
<file_sep>/styrish/src/com/styrish/mockvideo/dao/MockVideoDaoImpl.java
package com.styrish.mockvideo.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;
import com.styrish.connections.JDBCHelper;
import com.styrish.mockvideo.action.TutorMockVideoUploadAction;
public class MockVideoDaoImpl extends JDBCHelper{
protected static final String CLASSNAME = "MockVideoDaoImpl";
protected static final Logger LOGGER = Logger.getLogger(CLASSNAME);
public String getMockVideoAdditionPath(String subcourseId) {
final String METHODNAME = "getMockVideoAdditionPath";
Connection con = super.getConnection();
PreparedStatement ps = null;
ResultSet rs=null;
String videoAdditionPath=null;
try {
ps = con.prepareStatement("select co.course course,sub.subcourse subcourse from courses co inner join subcourses sub on(sub.courses_id=co.course_id) where sub.subcourses_id=?");
ps.setString(1, subcourseId);
rs = ps.executeQuery();
while (rs.next()) {
videoAdditionPath=rs.getString("course")+"_"+rs.getString("subcourse");
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
finally {
try {
if (con != null) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
}
return videoAdditionPath;
}
public int createMockVideo(TutorMockVideoUploadAction tutorMockVideoUploadAction) {
final String METHODNAME = "createMockVideo";
Connection con = super.getConnection();
PreparedStatement ps = null;
int status = 0;
try {
con = JDBCHelper.getConnection();
ps = con.prepareStatement(
"insert into mockvideos(course_id,subcourses_id,user_id,mockvideos_name,mockvideos_path,mockvideos_description)values(?,?,?,?,?,?)");
ps.setString(1, tutorMockVideoUploadAction.getCourseId());
ps.setString(2, tutorMockVideoUploadAction.getSubcourseId());
ps.setString(3, tutorMockVideoUploadAction.getUserId());
ps.setString(4, tutorMockVideoUploadAction.getDocumentTitle());
ps.setString(5, tutorMockVideoUploadAction.getDocumentPath());
ps.setString(6, tutorMockVideoUploadAction.getDocumentDescription());
status = ps.executeUpdate();
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
finally {
try {
if (con != null) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
}
return status;
}
}
<file_sep>/styrish/src/com/styrish/courses/subjects/actions/GetSubjectsByCourseAction.java
package com.styrish.courses.subjects.actions;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.courses.databean.CourseSubjectDataBean;
public class GetSubjectsByCourseAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = -5531712717328244660L;
protected List<Map<Long, String>> subjectList;
protected String courseId;
@Override
public String execute() throws Exception {
if (!StringUtils.isEmpty(courseId)) {
CourseSubjectDataBean coursesSubjectDataBean = new CourseSubjectDataBean();
coursesSubjectDataBean.setCourseId(getCourseId());
subjectList = coursesSubjectDataBean.getCourseSubjectsList();
setSubjectList(subjectList);
}
return "success";
}
public List<Map<Long, String>> getSubjectList() {
return subjectList;
}
public void setSubjectList(List<Map<Long, String>> subjectList) {
this.subjectList = subjectList;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
}
<file_sep>/styrish/src/com/styrish/users/action/AjaxUserRegistrationAction.java
package com.styrish.users.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.users.dao.UserRegistrationDaoImpl;
public class AjaxUserRegistrationAction extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
protected Map<String, Object> sessionMap;
private String mobileNumber;
private String otp;
private boolean otpValidated;
private boolean otpCreated;
private String password;
private String confirmPassword;
private String fullName;
private boolean isRegistered;
private List<String> validationMessages;
private String validationMessage;
private UserRegistrationDaoImpl userRegistrationDaoImpl;
private Long usersId;
protected String exceptionMessage;
protected String exceptionMessageKey;
@Override
public void setSession(Map<String, Object> sessionMap) {
this.sessionMap = sessionMap;
}
@Override
public String execute() throws Exception {
boolean userCreated = false;
if (StringUtils.isEmpty(getOtp())) {
Map<String, String> userParamMap = new HashMap<String, String>();
userParamMap.put("mobileNumber", mobileNumber);
userParamMap.put("password", <PASSWORD>);
userParamMap.put("confirmPassword", confirmPassword);
userParamMap.put("fullName", fullName);
if (getValidationMessages().isEmpty()) {
userCreated = getUserRegistrationDaoImpl().createInactiveUser(userParamMap);
}
if (userCreated || (getValidationMessages().size() == 1
&& getValidationMessages().contains("ERR_UNACTIVATED_ACCOUNT_EXISTS"))) {
// send otp to mobile for verifying mobile
CreateSendOTPTaskCmd createSendOTPTaskCmd = new CreateSendOTPTaskCmd();
createSendOTPTaskCmd.setMobileNumber(getMobileNumber());
createSendOTPTaskCmd.setActionType("GENERATEOTP");
createSendOTPTaskCmd.execute();
if (createSendOTPTaskCmd.getOtp() != null) {
setOtpCreated(true);
} else {
setExceptionMessage(createSendOTPTaskCmd.getExceptionMessage());
setExceptionMessageKey(createSendOTPTaskCmd.getExceptionMessageKey());
}
}
} else if (!StringUtils.isEmpty(this.getOtp())) {
// verify OTP
CreateSendOTPTaskCmd createSendOTPTaskCmd = new CreateSendOTPTaskCmd();
createSendOTPTaskCmd.setMobileNumber(getMobileNumber());
createSendOTPTaskCmd.setOtp(getOtp());
createSendOTPTaskCmd.setActionType("VERIFYOTP");
createSendOTPTaskCmd.execute();
if (!createSendOTPTaskCmd.isOtpValidated() && !createSendOTPTaskCmd.isOtpExpired()) {
String message = " Incorrect OTP, please try again !";
setExceptionMessage(message);
setExceptionMessageKey("ERR_INCORRECT_OTP");
} else if (createSendOTPTaskCmd.isOtpExpired()) {
String message = " OTP has been expired , please request a new one !";
setExceptionMessage(message);
} else if (createSendOTPTaskCmd.isOtpValidated()) {
setOtpValidated(true);
initiateSession();
getUserRegistrationDaoImpl().activateUser(Long.valueOf((String) sessionMap.get("userId")));
}
}
/*
* initiateSession(); if (sessionMap != null && !sessionMap.isEmpty()) {
* setRegistered(true); }
*/
return "success";
}
public void initiateSession() {
Map<String, String> userMap = getUserRegistrationDaoImpl().fetchUserMap(getMobileNumber());
sessionMap.put("userId", userMap.get("user_id"));
sessionMap.put("userName", userMap.get("userName"));
sessionMap.put("user_type", userMap.get("user_type"));
sessionMap.put("userType", "R");
setUsersId(Long.valueOf((String) sessionMap.get("userId")));
}
public UserRegistrationDaoImpl getUserRegistrationDaoImpl() {
if (userRegistrationDaoImpl == null) {
userRegistrationDaoImpl = new UserRegistrationDaoImpl();
}
return userRegistrationDaoImpl;
}
protected boolean checkIfAccountExists() throws Exception {
boolean accountExists = false;
Map<String, String> accountMap = getUserRegistrationDaoImpl().checkIfAccountExists(getMobileNumber());
if (accountMap != null && !accountMap.isEmpty()) {
String accountStatus = accountMap.get("user_status");
if (!StringUtils.isEmpty(accountStatus) && accountStatus.contentEquals("0")) {
getValidationMessages().add("ERR_UNACTIVATED_ACCOUNT_EXISTS");
}
}
return accountExists;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public String getExceptionMessageKey() {
return exceptionMessageKey;
}
public void setExceptionMessageKey(String exceptionMessageKey) {
this.exceptionMessageKey = exceptionMessageKey;
}
public Map<String, Object> getSessionMap() {
return sessionMap;
}
public void setSessionMap(Map<String, Object> sessionMap) {
this.sessionMap = sessionMap;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public boolean isRegistered() {
return isRegistered;
}
public void setRegistered(boolean isRegistered) {
this.isRegistered = isRegistered;
}
@Override
public void validate() {
List<String> validationMessages = new ArrayList<String>();
setValidationMessages(validationMessages);
try {
if (password != null && !password.isEmpty() && confirmPassword != null && !confirmPassword.isEmpty()) {
if (!password.equals(confirmPassword)) {
getValidationMessages().add("ERR_PASSWORD_NOT_MATCH");
}
}
checkIfAccountExists();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<String> getValidationMessages() {
return validationMessages;
}
public void setValidationMessages(List<String> validationMessages) {
this.validationMessages = validationMessages;
}
public String getValidationMessage() {
return validationMessage;
}
public void setValidationMessage(String validationMessage) {
this.validationMessage = validationMessage;
}
public Long getUsersId() {
return usersId;
}
public void setUsersId(Long usersId) {
this.usersId = usersId;
}
public void setUserRegistrationDaoImpl(UserRegistrationDaoImpl userRegistrationDaoImpl) {
this.userRegistrationDaoImpl = userRegistrationDaoImpl;
}
public String getOtp() {
return otp;
}
public void setOtp(String otp) {
this.otp = otp;
}
public boolean isOtpValidated() {
return otpValidated;
}
public void setOtpValidated(boolean otpValidated) {
this.otpValidated = otpValidated;
}
public boolean isOtpCreated() {
return otpCreated;
}
public void setOtpCreated(boolean otpCreated) {
this.otpCreated = otpCreated;
}
}
<file_sep>/styrish/src/com/styrish/shopping/beans/OrderDataBean.java
package com.styrish.shopping.beans;
import java.util.List;
import java.util.Map;
import com.styrish.commons.util.objects.CacheManager;
import com.styrish.commons.util.objects.CachedObject;
import com.styrish.shopping.dao.OrdersDAOImpl;
public class OrderDataBean {
protected Long ordersId;
protected List<OrderItemDataBean> orderItemDatabeans;
protected Long usersId;
protected Double orderTotal;
protected Double orderDiscount;
protected Double productTotal;
protected Double orderTax;
protected int noOfItemsInOrder;
protected List<OrderItemDataBean> ordItemDataBeans;
protected Map<Long,OrderDataBean> populateOrderDetails;
protected String accessProfile;
protected int itemCount;
protected char status;
public Long getOrdersId() {
return ordersId;
}
public void setOrdersId(Long ordersId) {
this.ordersId = ordersId;
}
public List<OrderItemDataBean> getOrderItemDatabeans() {
return orderItemDatabeans;
}
public void setOrderItemDatabeans(List<OrderItemDataBean> orderItemDatabeans) {
this.orderItemDatabeans = orderItemDatabeans;
}
public Long getUsersId() {
return usersId;
}
public void setUsersId(Long usersId) {
this.usersId = usersId;
}
public Double getOrderTotal() {
return orderTotal;
}
public void setOrderTotal(Double orderTotal) {
this.orderTotal = orderTotal;
}
public Double getOrderDiscount() {
return orderDiscount;
}
public void setOrderDiscount(Double orderDiscount) {
this.orderDiscount = orderDiscount;
}
public Double getOrderTax() {
return orderTax;
}
public void setOrderTax(Double orderTax) {
this.orderTax = orderTax;
}
public int getNoOfItemsInOrder() {
return noOfItemsInOrder;
}
public void setNoOfItemsInOrder(int noOfItemsInOrder) {
StringBuilder cacheIdentifier = new StringBuilder("noOfItemsInOrder").append("_")
.append(getUsersId());
Object identifierObj = cacheIdentifier.toString();
OrderDataBean orderDataBean = null;
CachedObject o = (CachedObject) CacheManager.getCache(identifierObj.toString());
if (o == null) {
OrdersDAOImpl ordersDAOImpl = new OrdersDAOImpl();
orderDataBean = ordersDAOImpl.findNumberOfItemsInCurrentShoppingCart(getUsersId());
CachedObject cachedObject = new CachedObject(orderDataBean, identifierObj, 180);
CacheManager.putCache(cachedObject);
} else {
orderDataBean = (OrderDataBean)o.object;
}
noOfItemsInOrder = orderDataBean.getItemCount();
this.setOrdersId(orderDataBean.getOrdersId());
this.noOfItemsInOrder = noOfItemsInOrder;
}
public List<OrderItemDataBean> getOrdItemDataBeans() {
return ordItemDataBeans;
}
public void setOrdItemDataBeans(List<OrderItemDataBean> ordItemDataBeans) {
this.ordItemDataBeans = ordItemDataBeans;
}
public Map<Long, OrderDataBean> getPopulateOrderDetails() {
return populateOrderDetails;
}
public void setPopulateOrderDetails(Map<Long, OrderDataBean> populateOrderDetails) {
OrdersDAOImpl ordersDAOImpl = new OrdersDAOImpl();
ordersDAOImpl.fetchOrderDetails(this);
OrderDataBean orderDataBean = ordersDAOImpl.getOrderDataBean();
if (orderDataBean != null) {
populateOrderDetails.put(orderDataBean.getOrdersId(), orderDataBean);
}
this.populateOrderDetails = populateOrderDetails;
}
public Double getProductTotal() {
return productTotal;
}
public void setProductTotal(Double productTotal) {
this.productTotal = productTotal;
}
public String getAccessProfile() {
return accessProfile;
}
public void setAccessProfile(String accessProfile) {
this.accessProfile = accessProfile;
}
public int getItemCount() {
return itemCount;
}
public void setItemCount(int itemCount) {
this.itemCount = itemCount;
}
public void resetOrderDataBean() {
setOrdersId(null);
setUsersId(null);
setOrderDiscount(null);
setOrderItemDatabeans(null);
setAccessProfile(null);
setItemCount(0);
setOrderTax(null);
setOrderTotal(null);
setProductTotal(null);
}
public char getStatus() {
return status;
}
public void setStatus(char status) {
this.status = status;
}
}
<file_sep>/styrish/src/com/styrish/student/dao/StudentMockTestDaoImpl.java
package com.styrish.student.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.logging.Logger;
import com.styrish.connections.JDBCHelper;
import com.styrish.student.action.StudentMockTestPaperSubmitAction;
public class StudentMockTestDaoImpl extends JDBCHelper{
protected static final String CLASSNAME = "StudentMockTestDaoImpl";
protected static final Logger LOGGER = Logger.getLogger(CLASSNAME);
protected static final String FETCH_MOCKTEST_BY_STUDENT="SELECT subcourses.subcourse,mocktest_id, mocktest_name,noOfQuestions,testTime from mocktest left join subcourses on(subcourses.subcourses_id=mocktest.subcourses_id) where mocktest_status='S' and course_id=?";
protected static final String SUBMIT_EXAM_BY_STUDENT="insert into StudentExam(user_id,course_id,mocktest_id,question_id,correct_option,studentexam_status)values(?,?,?,?,?,?)";
public List<Map<String,String>> getMockTestByStudent(String courseId) {
final String METHODNAME = "getMockTestByStudent";
Connection con = super.getConnection();
PreparedStatement ps = null;
ResultSet rs=null;
List<Map<String,String>> mockTestList =new ArrayList<Map<String,String>>();
try {
ps = con.prepareStatement(FETCH_MOCKTEST_BY_STUDENT);
ps.setString(1, courseId);
rs = ps.executeQuery();
while (rs.next()) {
Map<String,String> mocktestMap=new HashMap<String,String>();
mocktestMap.put("subcourse", rs.getString("subcourse"));
mocktestMap.put("mocktest_id", rs.getString("mocktest_id"));
mocktestMap.put("mocktest_name", rs.getString("mocktest_name"));
mocktestMap.put("noOfQuestions", rs.getString("noOfQuestions"));
mocktestMap.put("testTime", rs.getString("testTime"));
mockTestList.add(mocktestMap);
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
finally {
try {
if (con != null) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " + METHODNAME + " " + e);
}
}
return mockTestList;
}
/*
* public int submitExamByStudent(StudentMockTestPaperSubmitAction
* studentMockTestPaperSubmitAction) {
*
* final String METHODNAME = "submitExamByStudent"; Connection con =
* super.getConnection(); PreparedStatement ps = null; ResultSet rs=null;
* List<Map<String,String>> mockTestList =new ArrayList<Map<String,String>>();
* try { ps = con.prepareStatement(SUBMIT_EXAM_BY_STUDENT); // ps.setString(1,
* courseId);
*
* rs = ps.executeQuery();
*
* while (rs.next()) { Map<String,String> mocktestMap=new
* HashMap<String,String>(); mocktestMap.put("subcourse",
* rs.getString("subcourse")); mocktestMap.put("mocktest_id",
* rs.getString("mocktest_id")); mocktestMap.put("mocktest_name",
* rs.getString("mocktest_name")); mocktestMap.put("noOfQuestions",
* rs.getString("noOfQuestions")); mocktestMap.put("testTime",
* rs.getString("testTime"));
*
* mockTestList.add(mocktestMap); }
* System.out.println("mockTestList::"+mockTestList); } catch (SQLException e) {
* LOGGER.warning(" SQLException Occured :: " + CLASSNAME + " " + METHODNAME +
* " " + e); } finally {
*
* try { if (con != null) { con.close(); } if (ps != null) { ps.close(); }
*
* } catch (SQLException e) {
* LOGGER.warning(" SQLException Occured in finally :: " + CLASSNAME + " " +
* METHODNAME + " " + e); } } return null; }
*
*/
}
<file_sep>/styrish/src/com/styrish/shopping/action/OrderItemDeleteAction.java
package com.styrish.shopping.action;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.commons.util.objects.CommonUtils;
import com.styrish.shopping.beans.OrderDataBean;
import com.styrish.shopping.beans.OrderItemDataBean;
import com.styrish.shopping.dao.OrdersDAOImpl;
public class OrderItemDeleteAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
protected Long orderItemsId;
protected Long ordersId;
protected Long usersId;
public Long getOrderItemsId() {
return orderItemsId;
}
public void setOrderItemsId(Long orderItemsId) {
this.orderItemsId = orderItemsId;
}
public Long getOrdersId() {
return ordersId;
}
public void setOrdersId(Long ordersId) {
this.ordersId = ordersId;
}
@Override
public String execute() throws Exception {
OrderItemDataBean orderItemDataBean = new OrderItemDataBean();
orderItemDataBean.setOrderItemsId(getOrderItemsId());
OrderDataBean orderDataBean = new OrderDataBean();
orderDataBean.setOrdersId(getOrdersId());
removeOrderItem(orderItemDataBean, orderDataBean);
StringBuilder cacheIdentifier = new StringBuilder("noOfItemsInOrder").append("_")
.append(getUsersId());
CommonUtils.invalidateCache(cacheIdentifier);
return "success";
}
protected void removeOrderItem(OrderItemDataBean orderItemDataBean, OrderDataBean orderDataBean) {
OrdersDAOImpl ordersDAOImpl = new OrdersDAOImpl();
ordersDAOImpl.deleteOrderItem(orderItemDataBean);
ordersDAOImpl.refreshOrderAmounts(orderDataBean);
}
public Long getUsersId() {
return usersId;
}
public void setUsersId(Long usersId) {
this.usersId = usersId;
}
}
<file_sep>/styrish/src/com/styrish/student/databean/StudentMockTestPaperDataBean.java
package com.styrish.student.databean;
import java.util.List;
import java.util.Map;
import com.styrish.mocktest.dao.MockTestDaoImpl;
public class StudentMockTestPaperDataBean {
private String userId;
private String mockTestId;
private List<Map<String,String>> mockTestQuestionList;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getMockTestId() {
return mockTestId;
}
public void setMockTestId(String mockTestId) {
this.mockTestId = mockTestId;
}
public List<Map<String, String>> getMockTestQuestionList() {
MockTestDaoImpl mockTestDaoImpl =new MockTestDaoImpl();
mockTestQuestionList=mockTestDaoImpl.getMockTestQuestions(mockTestId);
return mockTestQuestionList;
}
public void setMockTestQuestionList(List<Map<String, String>> mockTestQuestionList) {
this.mockTestQuestionList = mockTestQuestionList;
}
}
<file_sep>/styrish/src/com/styrish/courses/subjects/databean/CourseSubjectDataBean.java
package com.styrish.courses.subjects.databean;
import java.util.*;
import com.styrish.courses.subjects.dao.CourseSubjectsDaoImpl;
public class CourseSubjectDataBean {
private String courseId;
private List<Map<String,String>> courseSubjectList;
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public List<Map<String, String>> getCourseSubjectList() {
return courseSubjectList;
}
public void setCourseSubjectList(List<Map<String, String>> courseSubjectList) {
CourseSubjectsDaoImpl courseSubjectsDaoImpl = new CourseSubjectsDaoImpl();
courseSubjectList=courseSubjectsDaoImpl.getCourseSubjectList(courseId);
this.courseSubjectList = courseSubjectList;
}
}
<file_sep>/styrish/src/com/styrish/users/action/UserRegistrationAction.properties
cpassword.required = Confirm password is required
cpassword.notmatch = Confirm password is not matched<file_sep>/styrish/src/com/styrish/mocktest/action/TutorMockTestFinalizeAction.java
package com.styrish.mocktest.action;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.mocktest.dao.MockTestDaoImpl;
public class TutorMockTestFinalizeAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String mockTestId;
public String getMockTestId() {
return mockTestId;
}
public void setMockTestId(String mockTestId) {
this.mockTestId = mockTestId;
}
public String execute() throws Exception {
MockTestDaoImpl mockTestDaoImpl=new MockTestDaoImpl();
mockTestDaoImpl.updateMockTest(mockTestId);
return "success";
}
}
<file_sep>/styrish/WebContent/js/LoginRegisterModalWindow.js
/**
*
*/
LoginRegisterModalWindowJS = {
enableOTPLoginArea : function() {
$("#exceptionMessage").html("");
$("#successMessage").html("");
$("#actionType").val("generateOTP");
$("#mobileNumberHidden").val("");
$("#mobileNumberArea").css("display", "block");
$("#otpArea").css("display", "none");
$("#loginWithAccountLink").css("display", "block");
$("#loginWithOtpLink").css("display", "none");
$("#loginPasswordField").css("display", "none");
$("#otploginButtonModalDiv").css("display", "block");
$("#loginButtonModalDiv").css("display", "none");
$("#registrationButtonModalDiv").css("display", "none");
$("#loginModalWindowFormId").attr('action', 'ajax/AjaxOTPLoginAction');
$("#otploginButtonModal").val("Send OTP");
$("#loginConfirmPasswordField").css("display", "none");
$("#fullNameField").css("display", "none");
$("#verifyOTPtoRegisterButtonModalDiv").css("display", "none");
},
enableOTPVerifyAreaForRegister : function() {
$("#exceptionMessage").html("");
$("#successMessage").html("");
$('#loadingmessage').hide();
$("#mobileNumberArea").css("display", "none");
$("#otpArea").css("display", "block");
$('.btn').show();
$("#actionType").val("verifyOTP");
$("#loginConfirmPasswordField").css("display", "none");
$("#loginPasswordField").css("display", "none");
$("#fullNameField").css("display", "none");
$("#registrationButtonModalDiv").css("display", "none");
$("#verifyOTPtoRegisterButtonModalDiv").css("display", "block");
},
enableAccountLoginArea : function() {
$("#exceptionMessage").html("");
$("#successMessage").html("");
$("#loginWithAccountLink").css("display", "none");
$("#loginWithOtpLink").css("display", "block");
$("#loginPasswordField").css("display", "block");
//$("#loginButtonModal").val("Login");
$("#otploginButtonModalDiv").css("display", "none");
$("#loginButtonModalDiv").css("display", "block");
$("#registrationButtonModalDiv").css("display", "none");
$("#loginModalWindowFormId").attr('action', 'AccountLoginAction');
$("#loginConfirmPasswordField").css("display", "none");
$("#fullNameField").css("display", "none");
$("#verifyOTPtoRegisterButtonModalDiv").css("display", "none");
},
enableRegistrationArea :function() {
$("#exceptionMessage").html("");
$("#successMessage").html("");
$("#loginConfirmPasswordField").css("display", "block");
$("#loginPasswordField").css("display", "block");
$("#fullNameField").css("display", "block");
$("#registrationButtonModalDiv").css("display", "block");
$("#otploginButtonModalDiv").css("display", "none");
$("#loginButtonModalDiv").css("display", "none");
$("#forgotPasswordLink").css("display", "none");
$("#verifyOTPtoRegisterButtonModalDiv").css("display", "none");
},
populateMobileHiddenField : function (mobileNumber,actionType) {
if(actionType == "generateOTP") {
$("#mobileNumberHidden").val(mobileNumber);
}
},
setRedirectURL : function (redirectURL) {
$("#loginRedirectURL").val(redirectURL);
}
}<file_sep>/styrish/WebContent/js/javascript.js
var globalData=[];
var totalQuestion=[];
var currentQuestion=0;
var selected=[];
var header="";
function response(){
var skip=0;
var total=globalData.length;
for(i=1;i<selected.length;i++)
{
if(selected[i].length==0)
skip++;
}
var notvisited=total-currentQuestion;
if(selected.length>0)
var attempt=selected.length-1-skip;
else
var attempt=0;
var body= `<table id="summary" style="width:100%" class="table table-bordered summary">
<thead class="summary_thead">
<tr>
<td>Section</td>
<td>Attempted</td>
<td>Skipped</td>
<td>Not Visited</td>
<td>Total</td>
</tr>
</thead>
<tbody>
<tr>
<td>${header}</td>
<td>${attempt}</td>
<td>${skip}</td>
<td>${notvisited}</td>
<td>${total}</td>
</tr>
</tbody>
</table>`;
$("#response").append(body);
}
function endTest(){
if(confirm("Are you sure to submit test?"))
{
$.ajax({
type: "POST",
url: "http://fakerestapi.azurewebsites.net",
dataType: "jsonp",
data : JSON.stringify(selected),
success: function(data) {
console.log(data);
document.getElementById("openModel").click();
response();
},
complete:function(){
document.getElementById("openModel").click();
response();
}
});
}
}
function next(){
choices=globalData[currentQuestion]['choices'];
choosen=[];
for(i=0;i<choices.length; i++){
id="choice_"+(i+1);
v= document.getElementById(id).checked;
if(v)
choosen.push(i+1);
}
selected[currentQuestion+1]=choosen;
currentQuestion++;
if(globalData.length<=currentQuestion)
{
document.getElementById("next").disabled = true;
return;
}
getQuestion();
}
function setHeader(header)
{
document.getElementById("subject_header").innerHTML=header;
document.getElementById("subject_header").style.display="block";
}
function getQuestion(){
$("#frame").empty();
document.getElementById("frame").style.display="block";
var body=`<div id="question_div"><table id="question"><tr><td><b> Question ${currentQuestion+1}.</b></td></tr><tr>`;
body+=`<td id ="question_td">${globalData[currentQuestion]['question']}</td>`;
body+=`<td id = "choices_td">`;
id="choice-block-" + (currentQuestion+1);
body+=`<table id=${id} class="mcq_choice">`;
choices=globalData[currentQuestion]['choices'];
for(i=0;i<choices.length; i++)
body+=`<tr><td data-index=${i+1} class="choice"><label><input type="checkbox" id=choice_${i+1}>${choices[i]}</label></td></tr>`;
body+=`</table></td></tr></table>
<p class="warning">Choose more than one option and then select <b>Done</b>. To deselect an option, choose it a second time.</p>
</div><div><center class="done-btn"><button class="btn btn-info" id="next" onclick="next()">Done</button></center>
</div>`;
$("#frame").append(body);
}
function getapidata(){
$.ajax({
type: "GET",
url: "http://www.mocky.io/v2/5e09c98830000057002444a9",
crossDomain: true,
dataType: "jsonp",
success: function(data) {
setHeader(data[0]["subject"]);
header=data[0]["subject"];
globalData=data[1];
totalQuestion= globalData.length;
getQuestion();
}
});
}
jQuery(document).ready(function($){
document.getElementById("subject_header").style.display="none";
document.getElementById("frame").style.display="none";
getapidata();
});
<file_sep>/styrish/src/com/styrish/courses/topics/action/TopicDeleteExerciseAction.java
package com.styrish.courses.topics.action;
import com.opensymphony.xwork2.ActionSupport;
public class TopicDeleteExerciseAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String questionId;
public String getQuestionId() {
return questionId;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public String execute() throws Exception {
return SUCCESS;
}
}
<file_sep>/styrish/src/com/styrish/courses/topics/action/TopicDisplayDetailsAction.java
package com.styrish.courses.topics.action;
import java.util.*;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.courses.topics.dao.CourseTopicsDaoImpl;
public class TopicDisplayDetailsAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private List<Map<String,String>> videoList;
private List<Map<String,String>> contentList;
private List<Map<String,String>> exerciseList;
private String topicId;
private String topicName;
public List<Map<String, String>> getVideoList() {
return videoList;
}
public void setVideoList(List<Map<String, String>> videoList) {
this.videoList = videoList;
}
public List<Map<String, String>> getContentList() {
return contentList;
}
public void setContentList(List<Map<String, String>> contentList) {
this.contentList = contentList;
}
public List<Map<String, String>> getExerciseList() {
return exerciseList;
}
public void setExerciseList(List<Map<String, String>> exerciseList) {
this.exerciseList = exerciseList;
}
public String getTopicId() {
return topicId;
}
public void setTopicId(String topicId) {
this.topicId = topicId;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String execute() {
CourseTopicsDaoImpl courseTopicsDaoImpl = new CourseTopicsDaoImpl();
Map topicMap=courseTopicsDaoImpl.getCourseTopicByTopicId(topicId);
if(topicMap.get("topic_name")!=null) {
topicName=(String) topicMap.get("topic_name");
setTopicName(topicName);
}
return SUCCESS;
}
}
<file_sep>/styrish/src/com/styrish/courses/topics/action/TopicUploadContentAction.java
package com.styrish.courses.topics.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.courses.topics.dao.CourseTopicsDaoImpl;
public class TopicUploadContentAction extends ActionSupport implements ServletContextAware {
private static final long serialVersionUID = 1L;
private File userImage;
private String userImageContentType;
private String userImageFileName;
private String courseTopicChoice;
private String courseId;
private String userId;
private ServletContext servletContext;
private String documentTitle;
private String documentDescription;
private String documentPath;
private InputStream inputStream;
private String fileName;
private long contentLength;
public void setServletContext(ServletContext context) {
servletContext=context;
}
public File getUserImage() {
return userImage;
}
public void setUserImage(File userImage) {
this.userImage = userImage;
}
public String getUserImageContentType() {
return userImageContentType;
}
public void setUserImageContentType(String userImageContentType) {
this.userImageContentType = userImageContentType;
}
public String getUserImageFileName() {
return userImageFileName;
}
public void setUserImageFileName(String userImageFileName) {
this.userImageFileName = userImageFileName;
}
public String getDocumentPath() {
return documentPath;
}
public void setDocumentPath(String documentPath) {
this.documentPath = documentPath;
}
public String getCourseTopicChoice() {
return courseTopicChoice;
}
public void setCourseTopicChoice(String courseTopicChoice) {
this.courseTopicChoice = courseTopicChoice;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getDocumentTitle() {
return documentTitle;
}
public void setDocumentTitle(String documentTitle) {
this.documentTitle = documentTitle;
}
public String getDocumentDescription() {
return documentDescription;
}
public void setDocumentDescription(String documentDescription) {
this.documentDescription = documentDescription;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public long getContentLength() {
return contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public String execute() {
try {
CourseTopicsDaoImpl courseTopicsDaoImpl=new CourseTopicsDaoImpl();
String filePath = (String) servletContext.getInitParameter("host");
String documentAdditionPath=courseTopicsDaoImpl.getDocumentAdditionPath(courseTopicChoice);
userImageFileName=documentAdditionPath+"_"+userImageFileName;
File fileToCreate = new File(filePath, userImageFileName);
FileUtils.copyFile(this.userImage, fileToCreate);
setUserImageFileName(userImageFileName);
documentPath=filePath+"/"+userImageFileName;
HttpSession session=ServletActionContext.getRequest().getSession(false);
if(session.getAttribute("courseIdSession")!=null) {
courseId=(String) session.getAttribute("courseIdSession");
userId=(String) session.getAttribute("userId");
}
int i=courseTopicsDaoImpl.insertDocuments(this);
File fileToDownload = new File(documentPath);
fileName = fileToDownload.getName();
inputStream=new FileInputStream(fileToDownload);
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
}<file_sep>/styrish/src/com/styrish/mocktest/action/TutorMockTestDeleteQuestionsAction.java
package com.styrish.mocktest.action;
import com.opensymphony.xwork2.ActionSupport;
import com.styrish.mocktest.dao.MockTestDaoImpl;
public class TutorMockTestDeleteQuestionsAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String mockTestId;
private String questionId;
public String getMockTestId() {
return mockTestId;
}
public void setMockTestId(String mockTestId) {
this.mockTestId = mockTestId;
}
public String getQuestionId() {
return questionId;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public String execute() throws Exception {
MockTestDaoImpl mockTestDaoImpl=new MockTestDaoImpl();
int status=mockTestDaoImpl.deleteQuestion(questionId);
return "success";
}
}
<file_sep>/styrish/src/com/styrish/mocktest/bean/MockTestQuestionsDataBean.java
package com.styrish.mocktest.bean;
import java.util.*;
import com.styrish.mocktest.dao.MockTestDaoImpl;
public class MockTestQuestionsDataBean {
private List<Map<String,String>> mockQuestionsList;
private Map<String,String> mockQuestionsMap;
private String mockTestId;
private String mockTestStatus;
private String questionId;
MockTestDaoImpl mockTestDaoImpl=new MockTestDaoImpl();
public String getMockTestId() {
return mockTestId;
}
public void setMockTestId(String mockTestId) {
this.mockTestId = mockTestId;
}
public String getMockTestStatus() {
return mockTestStatus;
}
public void setMockTestStatus(String mockTestStatus) {
this.mockTestStatus = mockTestStatus;
}
public String getQuestionId() {
return questionId;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public Map<String, String> getMockQuestionsMap() {
mockQuestionsMap=mockTestDaoImpl.getQuestion(questionId);
return mockQuestionsMap;
}
public void setMockQuestionsMap(Map<String, String> mockQuestionsMap) {
this.mockQuestionsMap = mockQuestionsMap;
}
public List<Map<String, String>> getMockQuestionsList() {
mockQuestionsList=mockTestDaoImpl.getMockTestQuestions(mockTestId);
return mockQuestionsList;
}
public void setMockQuestionsList(List<Map<String, String>> mockQuestionsList) {
this.mockQuestionsList = mockQuestionsList;
}
}
| 7af4f41dce92faf62134ce6588559ad3a43722e2 | [
"JavaScript",
"Java",
"INI"
] | 38 | Java | contactravi676/styrish_eseizers | 6bf0803462fd93941cb1bdb7856d3b2b937d3d60 | 6b3c105050e4e046bf71130be89e5c56f47c4ed6 |
refs/heads/master | <file_sep># Introduce
INTRODUCING, ORWTMC INCORPORATED, FIRST LARGE PROJECT -------ORSH.
This is a 'shell', to simulate a linux terminal
# Errors
If you see the Traceback or any unexpected error, please send an email to <a href="mailto:<EMAIL>?subject=ORSH error report">me</a>, and please give me the log files. These thing is in /proc folder. You should send ".ohsh_history" and "log.conf". You can also send a zip file including this entire software.
# Credential
Username is 'root', you can change this in this shell: sudo user
Password is blank, you shouldn't enter anything.
# Commands
shutdown: Shutdown Shell.
passwd: Change password.
reboot: Reboot Shell.
browser: Request a web page.
user: Change username.
switchuser: Switch user.
time: Get time.
useradd: Add a new user.
userdel: Delete a user permanently without a backup.
surl: URL Shortener.
chost: Change hostname.
morse: Morse Encrypt/Decrypt.
dict: Dictionary creation.
sudo : Sudo mode. e.g. sudo passwd (Change root's password)
# Cautions
/proc is temporary files, but you shouldn't delete them.
/tmp is temporary files too, you can delete them.
/etc is system files, if you delete them, the program will crash immediately.
<file_sep># coding=gbk
import os
import json
import time
import datetime
import sys
import requests
def printf(req):
with open("./proc/log.conf", 'a') as fp:
fp.write("\n")
fp.write(req)
print(req)
return True
def delay(req):
timed = int(req)
time.sleep(timed)
return True
def bye(req, usr):
if usr != "root":
printf("Process 'System' cannot be terminated by a normal user.")
printf("Please switch to root.")
return False
else:
pass
printf("Shutting down...")
delay(req)
sys.exit(0)
def reboot(req, usr):
if usr != "root":
printf("Process 'System' cannot be terminated by a normal user.")
printf("Please switch to root.")
return False
else:
pass
printf("Rebooting...")
delay(req)
os.system("main.py")
sys.exit(0)
def jsonf(locat, opt, txt):
if opt == "read":
o = 'r'
elif opt == "ovwrite":
o = 'w'
elif opt == "write":
o = 'a'
else:
return False
if o == 'r':
with open(locat, 'r') as fp:
ret = json.load(fp)
return ret
elif o == 'w':
with open(locat, 'w') as fp:
json.dump(txt, fp)
return True
elif o == 'a':
with open(locat, 'a') as fp:
json.dump(txt, fp)
return True
else:
return False
printf("Process ended with True")
def gettime():
data = datetime.datetime.now()
yar = data.year
mon = data.month
day = data.day
hrs = data.hour
miu = data.minute
sec = data.second
dat = str(yar) + "-" + str(mon) + "-" + str(day) + " " + str(hrs) + ":" + str(miu) + ":" + str(sec)
return dat
def files(locat, opt, txt):
if opt == "read":
o = 'r'
elif opt == "ovwrite":
o = 'w'
elif opt == "write":
o = 'a'
else:
return False
if o == 'r':
with open(locat, 'r') as fp:
ret = fp.read()
return ret
elif o == 'w':
with open(locat, 'w') as fp:
fp.write(txt)
return True
elif o == 'a':
with open(locat, 'a') as fp:
fp.write(txt)
return True
else:
return False
printf("Process ended with True")
def termprepare(req):
files("proc/username", "ovwrite", req)
return True
def tty():
data = datetime.datetime.now()
yar = data.year
mon = data.month
day = data.day
hrs = data.hour
miu = data.minute
sec = data.second
dat = str(yar) + "-" + str(mon) + "-" + str(day) + " " + str(hrs) + ":" + str(miu) + ":" + str(sec)
printf("ORSH 1.0.0 login on tty " + dat)
usr = input("\nUsername: ")
psk = input("\nPassword: ")
sam = jsonf("etc/auth/tty.sam", "read", "")
for cu in sam.keys():
if usr != cu:
f = False
pass
else:
f = True
break
if f == False:
printf("User not exist!")
return False
else:
pass
for cp in sam.values():
if psk != cp:
f = False
pass
else:
f = True
if cp == '':
wp = True
else:
wp = False
break
if f == True:
printf("Correct credential.")
printf("Preparing terminal...")
if wp == True:
printf("Weak password detected! Please change your password immediately!")
else:
pass
termprepare(usr)
return True
else:
printf("The credential you gave is invalid.")
return False
if a != True:
printf("Illegal login! Shutting down...")
time.sleep(2)
sys.exit(0)
else:
printf("Access Granted, preparing main frame...")
return True
def passwd(req):
printf("You are " + req)
opsk = input("Old password: ")
f = jsonf("etc/auth/tty.sam", "read", "")
u = f[req]
if opsk != u:
printf("Old password wrong! Please try to remember that.")
return False
else:
pass
npsk = input("New password: ")
rpsk = input("Repeat new password: ")
if npsk != rpsk:
printf("Password not match.")
return False
else:
pass
printf("Nothing there buds.")
f[req] = npsk
jsonf("etc/auth/tty.sam", "ovwrite", f)
printf("Done!")
printf("Now user: " + req + "'s password changed from " + opsk + " to " + npsk + ".")
return True
def wbrows():
printf("Loaded")
url = input("Web Link(Including http:// or https://): ")
get = requests.get(url)
sc = get.status_code
printf("Status code: " + str(sc))
printf("Tip: If the status code is not equal to 200, there is something wrong.")
printf("301/302: The address pointed to is redirected and there is generally no problem. Go where the link point.")
printf("401: This server needs credential. Unauthorized.")
printf("404: The address pointed to does not exist.")
printf("500: The other's server has a problem.")
if str(sc) != "200":
printf("Error.")
return False
else:
pass
json = input("Is this a json file?(yes/no): ")
if json == "yes":
printf("Loading..")
txt = get.json()
printf(txt)
printf("\n\n\n")
u = input("Do you want to save to file?(yes/no): ")
if u == "yes":
printf("Saved to /tmp/get.json")
files("tmp/get.json", "write", txt)
else:
pass
else:
printf("Loading...")
obj = get.text
printf(obj)
printf("\n\n\n")
u = input("Do you want to save to file?(yes/no): ")
if u == "yes":
printf("Saved to /tmp/get.txt")
files("tmp/get.json", "write", obj)
return True
def usrcgr():
ousr = input("Old username: ")
nusr = input("New username: ")
sam = jsonf("etc/auth/tty.sam", "read", "")
for username in sam.keys():
if ousr == username:
printf("Executing..")
f = True
break
else:
f = False
pass
if f != True:
printf("Old user don't exist.")
return False
else:
pass
printf("Changing " + ousr + " to " + nusr)
usrpsk = sam[ousr]
del sam[ousr]
sam[nusr] = usrpsk
jsonf("etc/auth/tty.sam", "ovwrite", sam)
printf("Done!")
return True
def switchusr(c):
t = input("You want to switch to: ")
sam = jsonf("etc/auth/tty.sam", "read", "")
p = input(t + "'s password: ")
for key in sam.keys():
if t == key:
y = True
break
else:
y = False
pass
if y == False:
printf("The user '" + t + "' doesn't exist.")
return False
else:
pass
for value in sam.values():
if p == value:
y = True
break
else:
y = False
pass
if y == False:
printf("Access denied")
return False
else:
printf("Access Granted.")
pass
files("proc/username", "ovwrite", t)
printf("Switched to user " + t)
return True
def sudo(pwd):
sam = jsonf("etc/auth/tty.sam", "read", "")
p = sam["root"]
if pwd == p:
printf("sudo mode activated instantly.")
return True
else:
printf("Permission denied.")
return False
def gtime():
printf(gettime())
return True
def cusr(usr):
if usr != "root":
printf("User Creation cannot be executed by a normal user.")
printf("Please switch to root or run as sudo.")
return False
else:
pass
un = input("Username: ")
f = jsonf("etc/auth/tty.sam", "read", "")
for eu in f.keys():
if un == eu:
printf("User Exists!")
return False
else:
pass
printf("Creating..")
ps = input("Password for " + un + ": ")
if ps == '':
printf("You did't set a password, it's very danger, and it means everyone can login to your account. You should change your password when next login!")
else:
pass
f[un] = ps
jsonf("etc/auth/tty.sam", "ovwrite", f)
return True
def dusr(usr):
if usr != "root":
printf("User Deletion cannot be executed by a normal user.")
printf("Please switch to root or run as sudo.")
return False
else:
pass
printf("You are entering destroy mode.")
printf("You should make sure you know what are you doing right now.")
un = input("Username: ")
f = jsonf("etc/auth/tty.sam", "read", "")
for eu in f.keys():
if un != eu:
fo = False
else:
fo = True
break
if fo != True:
printf("User not exist!")
return False
else:
pass
cfm = input("You will delete user " + un + " permanently and unrecoverable! We will delete all data associated to this user! Type he/she's username to confirm: ")
if cfm == un:
pass
else:
printf("Operation timeout.")
return False
del f[un]
jsonf("etc/auth/tty.sam", "ovwrite", f)
printf("User " + un + " has been terminated and deleted from this system. You never find him/her until you create again!")
return True
def cacheclean():
with open("proc/username", 'w') as cc:
cc.write("")
def urlshortener():
try:
import requests
except ImportError:
printf("Libraries missing.")
return False
def apikey():
ret = "<KEY>"
return ret
def save(raw, surl):
n = datetime.datetime.now()
y = n.year
m = n.month
d = n.day
h = n.hour
mi = n.minute
s = n.second
da = "-"
string = str(y)+da+str(m)+da+str(d)+da+str(h)+da+str(mi)+da+str(s)+" "+str(raw)+" -> "+str(surl)
string = str(string)
with open("history.txt", 'a') as f:
f.write(string)
f.write("\n")
print("URL Shortener customize for ORSH(TM)")
print("We used suo.im's api!")
while True:
raw = input("URL(Enter 'q' to quit): ")
if raw == "q":
return True
print("Running quietly..")
sapikey = "<KEY>"
# if "http" in url:
# pass
# else:
# print("The URL must include http:// or https://")
# return False
address = "http://suo.im/api.htm?url=" + raw + "&key=" + sapikey + "&format=json&expireDate=2099-12-31"
req = requests.get(address)
res = req.json()
err = res['err']
surl = res['url']
if err == '':
pass
else:
print("Something went wrong...")
print(err)
continue
if surl == raw:
print("Shorten failed.")
print("Check your URL exist or this URL didn't supported.")
continue
else:
pass
printf("Shorten successful!")
printf("\n\n\n")
printf(surl)
return True
def ch(usr):
if usr != "root":
printf("Hostname Change cannot be executed by a normal user.")
printf("Please switch to root or run as sudo.")
return False
else:
pass
nh = input("New hostname: ")
h = files("etc/whoami", "read", "")
if nh == h:
printf("Same hostname!")
return False
else:
pass
printf("Changing hostname..")
files("etc/whoami", "ovwrite", nh)
printf("Applying Changes..")
printf("Reboot the system to apply changes!")
return True
def libmorse_e():
printf("Type the raw text(All lowercase will be turned to uppercase.Please not using any symbols.):")
rawtext = input("")
try:
printf("\n\n\nEncrypting...")
db = jsonf("etc/morse/dat.json", "read", "")
prc = rawtext.upper()
stage_1 = prc.split()
stg1_length = len(stage_1)
if stg1_length <= 1:
st = True
else:
st = False
files("proc/morse_code.tmp", "ovwrite", "")
if st == True:
stage_2 = stage_1[0]
stage_3 = stage_2[:]
for stage_4 in stage_3:
cur = db[stage_4]
files("proc/morse_code.tmp", "write", cur)
files("proc/morse_code.tmp", "write", "/")
printf(files("proc/morse_code.tmp", "read", ""))
return True
elif st == False:
for stage_2 in stage_1:
current = 0
while True:
global stg2_length
stg2_length = len(stage_2)
# printf(stg2_length)
# printf(current)
if current >= stg2_length:
break
cur = db[stage_2[current]]
files("proc/morse_code.tmp", "write", cur)
files("proc/morse_code.tmp", "write", "/")
current = current + 1
printf(files("proc/morse_code.tmp", "read", ""))
except KeyError:
printf("I said don't use any symbols. Idiot!")
return False
return True
def libmorse_d():
files("proc/morse_code.tmp", "ovwrite", "")
dic = jsonf("etc/morse/dat.json", "read", "")
printf("Type the encrypted string(such as ./../..-../.): ")
rawtext = input("")
printf("Decrypting...")
s1 = rawtext.split()
s2 = s1[0]
length = len(s2)
length = length - 1
global c
ss3 = ''
c = 0
while True:
if c > length:
break
s3 = s2[c]
if s3 == '/':
c = c + 1
try:
plain = list (dic.keys()) [list (dic.values()).index (ss3)]
except KeyError:
printf("Are you sure your code is correct?")
return False
files("proc/morse_code.tmp", "write", plain)
ss3 = ''
continue
ss3 += s3
c = c + 1
print(files("proc/morse_code.tmp", "read", ""))
return True
def morse():
printf("International Morse Code")
printf("What do you want to do?")
printf("1. Encrypt")
printf("2. Decrypt")
o = input("> ")
if o == '1':
libmorse_e()
return True
elif o == '2':
libmorse_d()
return True
else:
return False
def dictionary():
print("Dict create")
n = 1
na = input("Name: ")
di = {}
while True:
printf("Enter 'goodbye' in key to exit and save.")
k = input("Key: ")
if k == 'goodbye':
printf("Byebye!")
break
v = input("Value: ")
kv = "Key: " + str(k) + " Value: " + str(v)
printf(kv)
di[k] = v
ok = "Created. Number: " + str(n)
printf(ok)
printf("\n")
n = n + 1
kc = "Key count: " + str(n)
printf(kc)
printf("Saving...")
fn = "dat/" + na + ".json"
with open(fn, 'w') as j:
json.dump(di, j)
printf("\n\n\nWrote.")
printf("Waiting for file..")
time.sleep(1)
printf("\n\n")
printf("Dictionary: \n\n")
for key, value in di.items():
stri = str(key) + " " + str(value)
printf(stri)
printf("\n")
printf("File: " + fn)
printf("\n\n\n")
printf("Press any key.")
q = input("")
return True
<file_sep>import func as lib
import os
import json
import time
import sys
lib.cacheclean()
status = lib.tty()
if status == True:
pass
else:
lib.printf("Illegal login, shutting down...")
lib.delay(1)
sys.exit(0)
hostname = lib.files("etc/whoami", "read", "")
while True:
sudo = False
username = lib.files("proc/username", "read", "")
prt = username + "@" + hostname + ": ~ $ "
cmd = input(prt)
lib.files("proc/.ohsh_history", "write", "\n")
lib.files("proc/.ohsh_history", "write", username)
lib.files("proc/.ohsh_history", "write", ": ")
if "sudo" in cmd:
lib.printf("You are entering sudo mode.")
lib.printf("You should know what are you doing right now.")
lib.printf("sudo mode = run as 'root'")
psk = input("root's password: ")
ss = lib.sudo(psk)
if ss == True:
username = "root"
sudo = True
lib.files("proc/.ohsh_history", "write", "\nsudo mode activated.\n")
else:
lib.files("proc/.ohsh_history", "write", "\nTrying to switch root, permission denied.\n")
lib.printf("\nYou are currently running at normal user mode.")
pass
sp = cmd.split()
try:
cmd = sp[1]
except IndexError:
lib.printf("sudo: empty argument.")
continue
lib.files("proc/.ohsh_history", "write", cmd)
if cmd == "shutdown":
lib.bye(2, username)
elif cmd == "rm -rf /":
lib.printf("You can't do that! That will destroy the entire system.")
lib.printf("To keep safe, we are going to shutdown..")
lib.bye(5, username)
elif cmd == "rm -rf /*":
lib.printf("You can't do that! That will destroy the entire system.")
lib.printf("To keep safe, we are going to shutdown..")
lib.bye(5, username)
elif cmd == "passwd":
lib.printf("Starting password change...")
status = lib.passwd(username)
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
elif cmd == "reboot":
lib.reboot(2, username)
elif cmd == "browser":
lib.printf("Loading...")
status = lib.wbrows()
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
elif cmd == "user":
lib.printf("Loading...")
status = lib.usrcgr()
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
elif cmd == "switchuser":
lib.printf("Loading...")
status = lib.switchusr(username)
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
elif cmd == "time":
lib.printf("Loading..")
status = lib.gtime()
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
elif cmd == "useradd":
lib.printf("Loading..")
status = lib.cusr(username)
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
elif cmd == "userdel":
lib.printf("Loading..")
status = lib.dusr(username)
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
elif cmd == "surl":
lib.printf("Loading..")
status = lib.urlshortener()
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
elif cmd == "chost":
lib.printf("Loading...")
status = lib.ch(username)
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
elif cmd == "morse":
lib.printf("Loading...")
status = lib.morse()
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
elif cmd == "dict":
lib.printf("Loading...")
status = lib.dictionary()
if status != True:
lib.printf("Something went wrong.")
lib.printf("Operation cancelled.")
else:
lib.printf("Operation Executed.")
else:
lib.printf("orsh: command not found.")
if status == True:
lib.files("proc/.ohsh_history", "write", ": Successful.")
elif status == False:
lib.files("proc/.ohsh_history", "write", ": Failed.")
else:
lib.files("proc/.ohsh_history", "write", ": No report.")
if sudo == True:
lib.files("proc/.ohsh_history", "write", " sudo mode.")
else:
pass
| 476f6aab208204c7d8e1649ab6d41a2b36ea79ce | [
"Markdown",
"Python"
] | 3 | Markdown | shuairuan/orsh | 886f0f1b2b45c66145d71ef9ee60ef8688d68864 | 801f174b8265c09ceea49e584bf370096733361d |
refs/heads/master | <repo_name>Zumek1/CRM_Budget<file_sep>/src/main/java/pl/robert/allegrodemo/HomeController.java
package pl.robert.allegrodemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import pl.robert.allegrodemo.entity.User;
import pl.robert.allegrodemo.service.UserService;
import javax.servlet.http.HttpSession;
@Controller
@SessionAttributes("userSession")
public class HomeController {
@Autowired
UserService userService;
@GetMapping("/")
public String home(){
return "LoginPage";
}
@PostMapping("/")
public String loginPage(@RequestParam String username, @RequestParam String password, Model model, HttpSession session){
User user = userService.userByEmail(username);
model.addAttribute("isLogged", false);
if (user == null) {
return "LoginPage";
}
if (user.getPassword().equals(password)) {
model.addAttribute("userSession",user);
model.addAttribute("isLogged", true);
return "redirect:/" + "Start";
}
return "LoginPage";
}
}
<file_sep>/src/main/java/pl/robert/allegrodemo/service/CostsService.java
package pl.robert.allegrodemo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.SessionAttributes;
import pl.robert.allegrodemo.entity.Costs;
import pl.robert.allegrodemo.repo.CostsRepo;
import pl.robert.allegrodemo.repo.UserRepo;
import java.util.List;
@Service
@Transactional
@SessionAttributes
public class CostsService {
@Autowired
CostsRepo costsRepo;
@Autowired
UserRepo userRepo;
public void updateCosts(Costs costs){costsRepo.save(costs);}
public List<Costs> costsByUser(Long id){
List<Costs> costsList = costsRepo.findAllByUserID(id);
return costsList;
}
}
| a107949f24cc5ff5a23061680985c441633d9a27 | [
"Java"
] | 2 | Java | Zumek1/CRM_Budget | d57129a9cc92e5053a8e1a48474f269fde392237 | 944c8524dc750be32c7121b2e73924cd60b00677 |
refs/heads/master | <repo_name>jrialland/riversql<file_sep>/src/main/java/com/riversql/actions/GetFK.java
package com.riversql.actions;
import com.riversql.IDManager;
import com.riversql.JSONAction;
import com.riversql.dbtree.TableNode;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
public class GetFK implements JSONAction {
String id;
public void setId(String id) {
this.id = id;
}
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
JSONObject results = new JSONObject();
JSONArray meta = new JSONArray();
JSONArray data = new JSONArray();
//String id=request.getParameter("id");
Object obj = IDManager.get().get(id);
if (obj != null && obj instanceof TableNode) {
String[] strs = {"Foreign Key Name", "Primary Key Catalog", "Primary Key Schema",
"Primary Key Table", "Primary Key Column", "Foreign Key Column",
"Key Sequence", "Update Rule", "Delete Rule", "Primary Key Name", "Deferrability"};
for (int i = 0; i < strs.length; i++) {
meta.put(strs[i]);
}
TableNode table = ((TableNode) obj);
ResultSet rs = null;
try {
rs = table.getFK();
while (rs.next()) {
String fkName = rs.getString("FK_NAME");
String pkCat = rs.getString("PKTABLE_CAT");
String pkSchema = rs.getString("PKTABLE_SCHEM");
String pkTable = rs.getString("PKTABLE_NAME");
String pkColumnName = rs.getString("PKCOLUMN_NAME");
String fkColumnName = rs.getString("FKCOLUMN_NAME");
String key_seq = rs.getString("KEY_SEQ");
short update_rule = rs.getShort("UPDATE_RULE");
String update_rule_s = "";
if (update_rule == DatabaseMetaData.importedKeyNoAction) {
update_rule_s = "No Action";
} else if (update_rule == DatabaseMetaData.importedKeyCascade) {
update_rule_s = "Key Cascade";
} else if (update_rule == DatabaseMetaData.importedKeySetNull) {
update_rule_s = "Key Set Null";
} else if (update_rule == DatabaseMetaData.importedKeySetDefault) {
update_rule_s = "Key Set Default";
} else if (update_rule == DatabaseMetaData.importedKeyRestrict) {
update_rule_s = "Key Restrict";
}
String delete_rule_s = "";
short deleteRule = rs.getShort("DELETE_RULE");
if (deleteRule == DatabaseMetaData.importedKeyNoAction) {
delete_rule_s = "No Action";
} else if (deleteRule == DatabaseMetaData.importedKeyCascade) {
delete_rule_s = "Key Cascade";
} else if (deleteRule == DatabaseMetaData.importedKeySetNull) {
delete_rule_s = "Key Set Null";
} else if (deleteRule == DatabaseMetaData.importedKeyRestrict) {
delete_rule_s = "Key Restrict";
} else if (deleteRule == DatabaseMetaData.importedKeySetDefault) {
delete_rule_s = "Key Set Default";
}
String pkName = rs.getString("PK_NAME");
short deferrability = rs.getShort("DEFERRABILITY");
String deferrability_s = "";
if (deferrability == DatabaseMetaData.importedKeyInitiallyDeferred) {
deferrability_s = "Initially Deferred";
} else if (deferrability == DatabaseMetaData.importedKeyInitiallyImmediate) {
deferrability_s = "Initially Immediate";
} else if (deferrability == DatabaseMetaData.importedKeyNotDeferrable) {
deferrability_s = "Not Deferrable";
}
if (fkName != null) {
JSONArray record = new JSONArray();
record.put(fkName);
record.put(pkCat);
record.put(pkSchema);
record.put(pkTable);
record.put(pkColumnName);
record.put(fkColumnName);
record.put(key_seq);
record.put(update_rule_s);
record.put(delete_rule_s);
record.put(pkName);
record.put(deferrability_s);
data.put(record);
}
}
} finally {
if (rs != null)
rs.close();
}
}
results.put("meta", meta);
results.put("data", data);
return results;
}
}
<file_sep>/src/main/java/com/riversql/actions/ExecuteSQL.java
package com.riversql.actions;
import com.riversql.IDManager;
import com.riversql.JSONAction;
import com.riversql.WebSQLSession;
import com.riversql.dbtree.SQLSession;
import com.riversql.sql.QueryTokenizer;
import com.riversql.sql.SQLConnection;
import com.riversql.utils.SQLExecutor;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ExecuteSQL implements JSONAction {
String sql, sessionid;
public void setSql(String sql) {
this.sql = sql;
}
public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
SQLConnection conn = null;
if (sessionid != null) {
SQLSession sqlsession = (SQLSession) IDManager.get().get(sessionid);
if (sqlsession == null) {
sqlsession = null;//GetTree.createSQLSession(request, em,sessionid);
}
if (sqlsession != null)
conn = sqlsession.getConn();
}
JSONArray info = new JSONArray();
long init = 0;
init = System.nanoTime();
JSONArray resultSets = new JSONArray();
QueryTokenizer qt = new QueryTokenizer(";", "--", false);
qt.setScriptToTokenize(sql);
String nextQuery = null;
int limit = 10;
int maxLimit = 5000;
HttpSession session = request.getSession(true);
WebSQLSession sessions = (WebSQLSession) session.getAttribute("sessions");
while (qt.hasQuery()) {
nextQuery = qt.nextQuery();
SQLExecutor he = new SQLExecutor(conn, limit, maxLimit, nextQuery);
sessions.getExecutors().add(he);
JSONObject resultSet = new JSONObject();
JSONArray meta = new JSONArray();
JSONArray data = new JSONArray();
JSONArray info2 = new JSONArray();
try {
he.executeQuery(data, meta, info2);
info2.put(true);
} catch (Exception e) {
info2.put(false);
info2.put(e.getMessage());
}
resultSet.put("meta", meta);
resultSet.put("data", data);
resultSet.put("info", info2);
resultSets.put(resultSet);
}
long end = System.nanoTime();
info.put((end - init) / 1000000);
JSONObject ret = new JSONObject();
ret.put("info", info);
ret.put("resultSets", resultSets);
return ret;
}
}
<file_sep>/src/main/java/com/riversql/dbtree/DBNode.java
package com.riversql.dbtree;
import com.riversql.IDManager;
import com.riversql.sql.SQLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public abstract class DBNode implements IStructureNode {
private static final Logger LOGGER = LoggerFactory.getLogger(DBNode.class);
protected List<IStructureNode> children = new ArrayList<IStructureNode>();
protected String id;
protected SQLConnection conn;
private boolean loaded;
public DBNode(SQLConnection conn) {
this.id = IDManager.get().nextID();
IDManager.get().put(id, this);
this.conn = conn;
}
public void refresh() {
loaded = false;
children.clear();
}
public String getId() {
return id;
}
final public SQLConnection getConn() {
return conn;
}
final public JSONObject getChildrenToJSon() {
try {
load();
} catch (SQLException e1) {
LOGGER.error("getChildrenToJSon", e1);
}
JSONObject js = new JSONObject();
try {
JSONArray arr = new JSONArray();
for (int i = 0; i < children.size(); i++) {
JSONObject obj = new JSONObject();
IStructureNode is = children.get(i);
obj.put("text", is.getName());
obj.put("id", is.getId());
obj.put("leaf", is.isLeaf());
obj.put("type", is.getType());
obj.put("cls", is.getCls());
obj.put("qname", is.getQualifiedName());
arr.put(obj);
}
js.put("nodes", arr);
} catch (JSONException e) {
LOGGER.error("getChildrenToJSon", e);
}
return js;
}
public String getQualifiedName() {
return null;
}
abstract protected void nodeLoad() throws SQLException;
final public void load() throws SQLException {
if (loaded) return;
nodeLoad();
loaded = true;
}
final public List<IStructureNode> getChildren() {
try {
load();
} catch (SQLException e1) {
LOGGER.error("getChildren", e1);
}
return children;
}
public IStructureNode getChildrenByName(String nodeName) throws SQLException {
load();
IStructureNode childNode = null;
for (int i = 0; i < children.size(); i++) {
childNode = children.get(i);
if (childNode.getName().equalsIgnoreCase(nodeName)) {
return childNode;
}
}
return childNode;
}
}
<file_sep>/src/main/java/com/riversql/plugins/mysql/actions/ShowCharacterSets.java
package com.riversql.plugins.mysql.actions;
import com.riversql.sql.SQLConnection;
public class ShowCharacterSets extends Show {
public ShowCharacterSets(SQLConnection conn) {
super(conn);
}
@Override
public String getShowString() {
return "SHOW CHARACTER SET";
}
}
<file_sep>/src/main/java/com/riversql/databases/MSSQLSyntaxGenerator.java
package com.riversql.databases;
import java.util.List;
public class MSSQLSyntaxGenerator implements ISyntaxGenerator {
static final String GO = "GO";
public void changeColumn(StringBuilder sb, String tableQualifiedName,
String oldColumnName, String columnName, String type, String size,
String decDigits, String remarks, String defValue,
boolean acceptNull, boolean acceptNullOldValue) {
sb.append("ALTER TABLE ").append(tableQualifiedName).append(sep);
sb.append("ALTER COLUMN ").append(generateModifyColumn(columnName, oldColumnName, type, size, decDigits, remarks, defValue, acceptNull, acceptNullOldValue)).append(sep).append(GO).append(sep);
}
private Object generateModifyColumn(String columnName,
@SuppressWarnings("unused") String oldColumnName, String type, String size, String decDigits,
@SuppressWarnings("unused") String remarks, @SuppressWarnings("unused") String defValue, boolean acceptNull,
boolean acceptNullOldValue) {
StringBuffer result = new StringBuffer(" " + columnName + " " + type + "");
size = size.trim();
String prec = decDigits.trim();
if (type.equals("NVARCHAR")
|| type.equals("NCHAR")
|| type.equals("VARBINARY")
|| type.equals("BINARY")
|| type.equals("CHAR")
|| type.equals("VARCHAR")
) {
if (size.length() > 0) {
result.append("(" + size + ") ");
}
} else if ((type.equals("NUMERIC")) || (type.equals("DECIMAL"))) {
if (size.length() > 0) {
result.append("(" + size);
if (prec.length() > 0)
result.append("," + prec);
result.append(") ");
}
}
if (!acceptNull && acceptNull != acceptNullOldValue)
result.append(" NOT NULL ");
else if (acceptNull && acceptNull != acceptNullOldValue)
result.append(" NULL ");
return result.toString();
}
public void dropColumn(StringBuilder sb, String tableQualifiedName,
String droppedColumn) {
sb.append("ALTER TABLE ").append(tableQualifiedName).append(sep);
sb.append("DROP COLUMN ").append(droppedColumn).append(sep).append(GO).append(sep);
}
public void dropIndex(StringBuilder strbuilder, String qualifiedName,
String indexName) {
strbuilder.append(" DROP INDEX ").append(indexName).append(" ON ").append(qualifiedName).append(sep).append(GO).append(sep);
}
public void dropPK(StringBuilder strbuilder, String qualifiedName,
String droppedPK) {
strbuilder.append("ALTER TABLE ").append(qualifiedName);
strbuilder.append(" DROP CONSTRAINT ").append(droppedPK).append(sep).append(GO).append(sep);
}
public void newColumn(StringBuilder sb, String tableQualifiedName,
String columnName, String type, String size, String decDigits,
String remarks, String defValue, boolean acceptNull) {
sb.append("ALTER TABLE ").append(tableQualifiedName).append(sep);
sb.append("ADD ").append(generateAddColumn(columnName, type, size, decDigits, defValue, acceptNull)).append(sep).append(GO).append(sep);
}
public void newIndex(StringBuilder strbuilder, String qualifiedName,
String indexName, boolean unique, List<String> cols) {
strbuilder.append("CREATE ");
if (unique)
strbuilder.append("UNIQUE ");
strbuilder.append("INDEX ");
strbuilder.append(indexName);
strbuilder.append(" ON ").append(qualifiedName);
strbuilder.append("(");
int sz = cols.size();
for (int j = 0; j < sz; j++) {
String nm = cols.get(j);
strbuilder.append(nm);
if (j < sz - 1)
strbuilder.append(",");
}
strbuilder.append(")").append(sep).append(GO).append(sep);
}
public void newPK(StringBuilder strbuilder, String qualifiedName,
String pkname, List<String> lsCols) {
if (pkname != null && pkname.trim().length() > 0) {
strbuilder.append("ALTER TABLE ").append(qualifiedName).append(" ADD ");
strbuilder.append(" CONSTRAINT ").append(pkname.trim());
}
strbuilder.append(" PRIMARY KEY (");
for (int i = 0; i < lsCols.size(); i++) {
strbuilder.append(lsCols.get(i));
if (i < lsCols.size() - 1)
strbuilder.append(",");
}
strbuilder.append(")").append(sep).append(GO).append(sep);
}
public void renameColumn(StringBuilder sb, String tableQualifiedName,
String oldColumnName, String columnName) {
sb.append("EXEC sp_rename '").append(tableQualifiedName).append(".").append(oldColumnName).append("', '" + columnName + "', 'COLUMN'").append(sep).append(GO).append(sep);
}
private String generateAddColumn(String columnName, String type, String size, String prec, String defValue, boolean nullAccepted) {
StringBuffer sb = new StringBuffer();
sb.append(" " + columnName + " " + type + " ");
size = size.trim();
prec = prec.trim();
defValue = defValue.trim();
//String comment=cm.comment.trim();
if (type.equals("NVARCHAR")
|| type.equals("NCHAR")
|| type.equals("VARBINARY")
|| type.equals("BINARY")
|| type.equals("CHAR")
|| type.equals("VARCHAR")
) {
if (size.length() > 0) {
sb.append("(" + size + ") ");
}
} else if ((type.equals("NUMERIC")) || (type.equals("DECIMAL"))) {
if (size.length() > 0) {
sb.append("(" + size);
if (prec.length() > 0)
sb.append("," + prec);
sb.append(") ");
}
} else if (type.equals("")) {//Size obbligatoria
sb.append("(" + size + ") ");
}
if (!nullAccepted)
sb.append(" NOT NULL ");
if (defValue.length() > 0)
sb.append(" DEFAULT " + escapeString(type, defValue) + " ");
return sb.toString();
//if(comment.length()>0)
// result.append(" "+comment+" ");
}
private String escapeString(@SuppressWarnings("unused") String type, String defValue) {
return "'" + defValue + "'";
}
}
<file_sep>/src/main/java/com/riversql/plugins/mysql/TriggerNode.java
package com.riversql.plugins.mysql;
import com.riversql.plugin.BasePluginType;
import com.riversql.sql.SQLConnection;
public class TriggerNode extends BasePluginType {
public TriggerNode(TriggersNode triggersNode, String name,
SQLConnection conn) {
super(name, triggersNode, conn);
}
@Override
public void load() {
}
public String getCls() {
return "obj";
}
public String getType() {
return "mysql_trigger";
}
public boolean isLeaf() {
return true;
}
}
<file_sep>/src/main/java/com/riversql/plugins/mysql/actions/ShowProcesses.java
package com.riversql.plugins.mysql.actions;
import com.riversql.sql.SQLConnection;
public class ShowProcesses extends Show {
public ShowProcesses(SQLConnection conn) {
super(conn);
}
@Override
public String getShowString() {
return "SHOW FULL PROCESSLIST";
}
}
<file_sep>/deploy/zeitnow.sh
#!/bin/bash
set -euo pipefail
thisscript=$(readlink -m $0)
thisdir=$(dirname $thisscript)
basedir=$(readlink -m $thisdir/..)
warfile=$(find $basedir/target -type f -name "*.war" |head -1)
if [ "$warfile" == "" ]; then
pushd $basedir
mvn clean package
popd
warfile=$(find $basedir/target -type f -name "*.war" |head -1)
fi
exploded=$(echo $warfile|sed s/.war//)
rm ./ROOT -rf
cp $exploded ./ROOT -R
projectname=$(git config --local remote.origin.url | sed s_^.*github.com/__ | sed s-/-_-)
projectname=$(echo $projectname |sed s/.git//)
cat > now.json << EOF
{
"name": "$projectname",
"alias": "$projectname"
}
EOF
now --public --token $NOW_TOKEN && now alias --token $NOW_TOKEN
<file_sep>/src/main/java/com/riversql/actions/GetDrivers.java
package com.riversql.actions;
import com.riversql.JSONAction;
import com.riversql.dao.DriversDAO;
import com.riversql.entities.Driver;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetDrivers implements JSONAction {
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
JSONArray arr = new JSONArray();
for (Driver drv : DriversDAO.getDrivers(em, "")) {//sessions.getUser())){
JSONObject obj = new JSONObject();
obj.put("id", drv.getId());
obj.put("drvname", drv.getDriverName());
obj.put("drvclassname", drv.getDriverClassName());
obj.put("exampleurl", drv.getExampleUrl());
obj.put("valid", drv.isValid());
obj.put("icon", drv.getIconurl());
arr.put(obj);
}
JSONObject ret = new JSONObject();
ret.put("drivers", arr);
return ret;
}
}
<file_sep>/src/main/java/com/riversql/plugins/oracle/actions/DependentObjects.java
package com.riversql.plugins.oracle.actions;
import com.riversql.IDManager;
import com.riversql.dbtree.TableNode;
import com.riversql.dbtree.TablesNode;
import com.riversql.plugin.BasePluginType;
import com.riversql.plugins.oracle.FunctionNode;
import com.riversql.plugins.oracle.PackageNode;
import com.riversql.plugins.oracle.ProcedureNode;
import com.riversql.sql.SQLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DependentObjects {
private String id;
public DependentObjects(String id) {
this.id = id;
}
public JSONObject execute() throws Exception {
JSONObject results = new JSONObject();
JSONArray meta = new JSONArray();
JSONArray data = new JSONArray();
Object obj = IDManager.get().get(id);
String[] strs = {"Owner", "Type", "Name"};
for (int i = 0; i < strs.length; i++) {
meta.put(strs[i]);
}
String type = "";
SQLConnection conn = null;
String owner = null;
String objectname = null;
if (obj instanceof BasePluginType) {
BasePluginType bot = (BasePluginType) obj;
conn = bot.getConn();
BasePluginType tot = (BasePluginType) bot.getParent();
owner = tot.getParent().getName();
if (bot instanceof PackageNode) {
type = "PACKAGE";
} else if (bot instanceof ProcedureNode) {
type = "PROCEDURE";
} else if (bot instanceof FunctionNode) {
type = "FUNCTION";
}
} else if (obj instanceof TableNode) {
TableNode tn = (TableNode) obj;
objectname = tn.getName();
conn = tn.getConn();
TablesNode parent = tn.getParent();
owner = parent.getParent().getName();
type = parent.getName();
}
String sql = "select owner,type,name from sys.ALL_DEPENDENCIES " +
" where referenced_owner=? and referenced_name=? " +
" and referenced_type=? order by owner,type,name";
ResultSet rs = null;
PreparedStatement ps = null;
try {
if (conn == null)
return results;
ps = conn.prepareStatement(sql);
ps.setString(1, owner);
ps.setString(2, objectname);
ps.setString(3, type);
rs = ps.executeQuery();
while (rs.next()) {
JSONArray record = new JSONArray();
for (int i = 0; i < strs.length; i++) {
record.put(rs.getString(i + 1));
}
data.put(record);
}
} catch (Exception e) {
} finally {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
if (ps != null)
ps.close();
} catch (Exception e) {
}
}
results.put("meta", meta);
results.put("data", data);
return results;
}
}
<file_sep>/pom.xml
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.riversql</groupId>
<artifactId>riversql</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>RiverSQL</name>
<inceptionYear>2018</inceptionYear>
<url>http://github.com/jrialland/riversql</url>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>jrialland</id>
<name><NAME></name>
<email>http://pastebin.com/raw.php?i=iGLvAQvM</email>
<roles>
<role>King of the hill</role>
</roles>
</developer>
</developers>
<scm>
<url>http://github.com/jrialland/riversql</url>
<connection>scm:git:git://github.com/jrialland/riversql.git</connection>
<developerConnection>scm:git:ssh://git@github.com/jrialland/riversql.git</developerConnection>
</scm>
<properties>
<project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<slf4j.version>1.7.25</slf4j.version>
</properties>
<repositories>
<repository>
<id>jcenter</id>
<url>http://jcenter.bintray.com/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>toplink.essentials</groupId>
<artifactId>toplink-essentials</artifactId>
<version>2.1-03</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.5-FINAL</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.6</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.14.1.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
<dependency>
<groupId>com.yahoo.platform.yui</groupId>
<artifactId>yuicompressor</artifactId>
<version>2.4.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<showWarnings>true</showWarnings>
<compilerArgs>
<arg>-Werror</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version>
<configuration>
<quiet>true</quiet>
<formats>
<format>html</format>
<format>xml</format>
</formats>
<check/>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.6</version>
<configuration>
<locales>en</locales>
<stagingDirectory>/tmp/riversql-site</stagingDirectory>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<!-- Normally, we take off the dependency report, saves time. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.7</version>
<configuration>
<dependencyLocationsEnabled>false</dependencyLocationsEnabled>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.6</version>
<configuration>
<formats>
<format>html</format>
<format>xml</format>
</formats>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
</plugins>
</reporting>
</project>
<file_sep>/src/main/java/com/riversql/actions/export/impl/CSVTableExporter.java
package com.riversql.actions.export.impl;
import com.itextpdf.text.Element;
import com.riversql.actions.export.IColumnFormatter;
import com.riversql.actions.export.ITableExporter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.ResultSetMetaData;
import java.sql.Types;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class CSVTableExporter implements ITableExporter {
private final String qualifiedName;
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 1024);
IColumnFormatter formatters[];
private int row = 1;
private int column = 0;
private int columnCount = 0;
private StringBuffer sb = null;
private char separator = ',';
public CSVTableExporter(String qualifiedName) {
this.qualifiedName = qualifiedName;
this.sb = new StringBuffer();
}
public CSVTableExporter(int columnCount, JSONArray meta) {
this("");
formatters = new IColumnFormatter[columnCount];
for (int i = 0; i < columnCount; i++) {
try {
JSONObject row = meta.getJSONObject(i);
String label = row.getString("l");
sb.append(label);
final String align = row.getString("al");
formatters[i] = new IColumnFormatter() {
public Object format(Object obj) {
if (obj != null)
return obj.toString();
return null;
}
public int getAlign() {
if ("right".equals(align))
return Element.ALIGN_RIGHT;
return Element.ALIGN_LEFT;
}
};
} catch (JSONException e) {
}
if (i == columnCount - 1) {
sb.append("\n");
} else {
sb.append(separator);
}
}
}
public void configure(ResultSetMetaData rsmd) {
try {
columnCount = rsmd.getColumnCount();
formatters = new IColumnFormatter[columnCount];
for (int i = 0; i < columnCount; i++) {
int type = rsmd.getColumnType(i + 1);
switch (type) {
case Types.DATE:
formatters[i] = new IColumnFormatter() {
DateFormat sdfdate = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH);
public String format(Object obj) {
return sdfdate.format((java.sql.Date) obj);
}
public int getAlign() {
return Element.ALIGN_LEFT;
}
};
break;
case Types.TIME:
formatters[i] = new IColumnFormatter() {
DateFormat sdfdate = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ENGLISH);
public String format(Object obj) {
return sdfdate.format((java.sql.Time) obj);
}
public int getAlign() {
return Element.ALIGN_LEFT;
}
};
break;
case Types.TIMESTAMP:
case -101: // Oracle's 'TIMESTAMP WITH TIME ZONE' == -101
case -102:
formatters[i] = new IColumnFormatter() {
DateFormat sdfdate = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.ENGLISH);
public String format(Object obj) {
return sdfdate.format((java.sql.Timestamp) obj);
}
public int getAlign() {
return Element.ALIGN_LEFT;
}
};
break;
case Types.DOUBLE:
case Types.FLOAT:
case Types.REAL:
formatters[i] = new IColumnFormatter() {
DecimalFormat df = new DecimalFormat("#####################0.00", new DecimalFormatSymbols(Locale.ENGLISH));
public String format(Object obj) {
Double d = (Double) obj;
return df.format(d);
}
public int getAlign() {
return Element.ALIGN_RIGHT;
}
};
break;
case Types.DECIMAL:
case Types.NUMERIC:
formatters[i] = new IColumnFormatter() {
DecimalFormat df = new DecimalFormat("#####################0.00", new DecimalFormatSymbols(Locale.ENGLISH));
public String format(Object obj) {
BigDecimal d = (BigDecimal) obj;
return df.format(d);
}
public int getAlign() {
return Element.ALIGN_RIGHT;
}
};
break;
case Types.BIGINT:
formatters[i] = new IColumnFormatter() {
public String format(Object obj) {
return obj.toString();
}
public int getAlign() {
return Element.ALIGN_RIGHT;
}
};
break;
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
formatters[i] = new IColumnFormatter() {
public String format(Object obj) {
return obj.toString();
}
public int getAlign() {
return Element.ALIGN_RIGHT;
}
};
break;
}
sb.append(rsmd.getColumnLabel(i + 1));
if (i == columnCount - 1) {
sb.append("\n");
} else {
sb.append(separator);
}
}
} catch (Exception e) {
}
}
public void newCell(Object obj) {
column++;
if (obj != null) {
IColumnFormatter iformatter = formatters[column - 1];
sb.append(obj.toString());
} else
sb.append("null");
if (column != columnCount) {
sb.append(separator);
}
}
public void newLine() {
if (row != 1) {
sb.append("\n");
}
column = 0;
row++;
}
public void copyTo(OutputStream os) {
try {
baos.writeTo(os);
} catch (IOException e) {
}
}
public int getContentSize() {
return baos.size();
}
public String getMimeType() {
return "application/vnd.ms-excel";
}
public void finish() {
try {
baos.write(sb.toString().getBytes());
} catch (IOException ex) {
//Logger.getLogger(CSVTableExporter.class.getName()).log(Level.SEVERE, null, ex);
}
sb = null;
}
}
<file_sep>/src/main/java/com/riversql/dao/SourcesDAO.java
package com.riversql.dao;
import com.riversql.entities.Source;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.Date;
import java.util.List;
public class SourcesDAO {
@SuppressWarnings("unchecked")
public static List<Source> getSources(EntityManager em) {
Query q = em.createNamedQuery("Source.selectAll");
List<Source> ls = q.getResultList();
return ls;
}
public static void deleteAllSources(EntityManager em) {
//Query q=em.createNamedQuery("Source.deleteAll");
//q.executeUpdate ();
for (Source source : SourcesDAO.getSources(em)) {
em.remove(source);
}
}
public static void addSource(EntityManager em, String sourcename, String jdbcUrl, int driverID, String userName) {
Source al = createSource(sourcename, jdbcUrl, driverID, userName);
em.persist(al);
}
private static Source createSource(String sourcename, String jdbcUrl, int driverID, String userName) {
Source al = new Source();
al.setSourceName(sourcename);
al.setDriverid(driverID);
al.setJdbcUrl(jdbcUrl);
al.setUserName(userName);
al.setCreationDate(new Date());
return al;
}
public static void updateSource(EntityManager em, int sourceid, String jdbcUrl, int driverid, String user, String sourcename) {
Source as = em.find(Source.class, sourceid);
as.setUserName(user);
as.setDriverid(driverid);
as.setJdbcUrl(jdbcUrl);
as.setSourceName(sourcename);
em.merge(as);
}
public static Source getSource(EntityManager em, int sourceid) {
Source source = em.find(Source.class, Integer.valueOf(sourceid));
return source;
}
public static void deleteSource(EntityManager em, int id) {
Source as = em.find(Source.class, id);
em.remove(as);
}
}
<file_sep>/src/main/java/com/riversql/plugins/mysql/ProcedureNode.java
package com.riversql.plugins.mysql;
import com.riversql.plugin.BasePluginType;
import com.riversql.sql.SQLConnection;
public class ProcedureNode extends BasePluginType {
public ProcedureNode(ProcedureTypeNode procTypeNode, String name,
SQLConnection conn) {
super(name, procTypeNode, conn);
}
@Override
public void load() {
}
public String getCls() {
return "obj";
}
public String getType() {
return "mysql_proc";
}
public boolean isLeaf() {
return true;
}
}
<file_sep>/src/main/java/com/riversql/databases/DBSyntaxGeneratorFactory.java
package com.riversql.databases;
import com.riversql.sql.SQLConnection;
public class DBSyntaxGeneratorFactory {
private DBSyntaxGeneratorFactory() {
}
public static ISyntaxGenerator getSyntaxGenerator(SQLConnection conn) {
if (DialectFactory.isOracle(conn)) {
return new OracleSyntaxGenerator();
} else if (DialectFactory.isMySQL(conn)) {
return new MySqlSyntaxGenerator();
} else if (DialectFactory.isMSSQL(conn)) {
return new MSSQLSyntaxGenerator();
} else if (DialectFactory.isPostgreSQL(conn))
return new PostgreSQLSyntaxGenerator();
return null;
}
}
<file_sep>/src/main/java/com/riversql/plugins/oracle/OraclePlugin.java
package com.riversql.plugins.oracle;
import com.riversql.databases.DialectFactory;
import com.riversql.dbtree.CatalogNode;
import com.riversql.dbtree.IStructureNode;
import com.riversql.dbtree.SchemaNode;
import com.riversql.plugin.Plugin;
import com.riversql.plugins.oracle.actions.*;
import com.riversql.sql.SQLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class OraclePlugin implements Plugin {
public List<IStructureNode> getSchemaAddedChildren(SchemaNode schemaNode, SQLConnection conn) {
List<IStructureNode> added = new ArrayList<IStructureNode>();
if (isOracle(conn)) {
added.add(new PackageTypeNode(schemaNode, conn));
added.add(new PackageBodyTypeNode(schemaNode, conn));
added.add(new SequenceTypeNode(schemaNode, conn));
added.add(new FunctionTypeNode(schemaNode, conn));
added.add(new ProcedureTypeNode(schemaNode, conn));
added.add(new TriggerTypeNode(schemaNode, conn));
added.add(new JavaTypeNode(schemaNode, conn));
added.add(new JavaResourceTypeNode(schemaNode, conn));
added.add(new JavaClassTypeNode(schemaNode, conn));
added.add(new ObjectTypeNode(schemaNode, conn));
added.add(new ObjectTypeBodyNode(schemaNode, conn));
added.add(new LibraryTypeNode(schemaNode, conn));
added.add(new DirectoryTypeNode(schemaNode, conn));
}
return added;
}
private boolean isOracle(SQLConnection conn) {
return DialectFactory.isOracle(conn);
}
private boolean isUpperOracle9(SQLConnection conn) {
final String ORACLE9 = "oracle9";
final String ORACLE10 = "oracle database 10";
String dbms = null;
try {
dbms = conn.getSQLMetaData().getDatabaseProductVersion();
} catch (SQLException ex) {
}
return dbms != null && (dbms.toLowerCase().startsWith(ORACLE9) || dbms.toLowerCase().startsWith(ORACLE10));
}
public JSONArray[] getContextMenu(SQLConnection conn, String nodeType) {
List<JSONArray> ls = new ArrayList<JSONArray>();
if (isOracle(conn)) {
if ("tb".equals(nodeType)
|| "ora_pkg".equals(nodeType)
|| "ora_seq".equals(nodeType)
|| "ora_trig".equals(nodeType)
|| "ora_funct".equals(nodeType)
|| "ora_proc".equals(nodeType)
|| "ora_pkgbody".equals(nodeType)
) {
if (isUpperOracle9(conn)) {
JSONArray obj = new JSONArray();
obj.put("Extract DDL");
obj.put("icons/lightning.png");
obj.put("getTextAndOpenEditor('do?action=pluginAction&pluginName=OraclePlugin&method=extractDDL&nodeid='+menuTreeC.nodeid.id)");
ls.add(obj);
}
}
}
return ls.toArray(new JSONArray[0]);
}
public JSONObject executeAction(HttpServletRequest request,
HttpServletResponse response,
EntityManager em, EntityTransaction et) throws Exception {
String nodeid = request.getParameter("nodeid");
String id = request.getParameter("id");
String method = request.getParameter("method");
// if("extractDDL".equals(method)){
// return new ExtractDLL(nodeid).execute();
// }
// else
if ("triggerInfo".equals(method)) {
return new TriggerInfo(id).execute();
} else if ("procInfo".equals(method)) {
return new ProcInfo(id).execute();
} else if ("procParameters".equals(method)) {
return new ProcedureParametersDetail(id).execute();
} else if ("functInfo".equals(method)) {
return new FunctInfo(id).execute();
} else if ("javaInfo".equals(method)) {
return new JavaInfo(id).execute();
} else if ("functParameters".equals(method)) {
return new FunctionParametersDetail(id).execute();
} else if ("pkgInfo".equals(method)) {
return new PkgInfo(id).execute();
} else if ("pkgBodyInfo".equals(method)) {
return new PkgBodyInfo(id).execute();
} else if ("seqInfo".equals(method)) {
return new SeqInfo(id).execute();
} else if ("seqDetail".equals(method)) {
return new SeqDetail(id).execute();
} else if ("triggerDetail".equals(method)) {
return new TriggerDetail(id).execute();
} else if ("triggers".equals(method)) {
return new Triggers(id).execute();
} else if ("procedures".equals(method)) {
return new Procedures(id).execute();
} else if ("functions".equals(method)) {
return new Functions(id).execute();
} else if ("packages".equals(method)) {
return new Packages(id).execute();
} else if ("packagebs".equals(method)) {
return new PackageBodys(id).execute();
} else if ("sequences".equals(method)) {
return new Sequences(id).execute();
} else if ("types".equals(method)) {
return new ObjectTypes(id).execute();
} else if ("bodytypes".equals(method)) {
return new ObjectBodyTypes(id).execute();
} else if ("javas".equals(method)) {
return new JavaSources(id).execute();
} else if ("systemOptions".equals(method)) {
return new SystemOptions(id).execute();
} else if ("depObjs".equals(method)) {
return new DependentObjects(id).execute();
} else if ("objectTypeInfo".equals(method)) {
return new ObjectTypeInfo(id).execute();
} else if ("bodyTypeInfo".equals(method)) {
return new ObjectBodyTypeInfo(id).execute();
} else if ("javaress".equals(method)) {
return new JavaResources(id).execute();
} else if ("javaclasses".equals(method)) {
return new JavaClasses(id).execute();
} else if ("javaResInfo".equals(method)) {
return new JavaResInfo(id).execute();
} else if ("javaClassInfo".equals(method)) {
return new JavaClassInfo(id).execute();
} else if ("libraries".equals(method)) {
return new Libraries(id).execute();
} else if ("directories".equals(method)) {
return new Directories(id).execute();
} else if ("libraryInfo".equals(method)) {
return new LibraryInfo(id).execute();
} else if ("directoryInfo".equals(method)) {
return new DirectoryInfo(id).execute();
}
return new JSONObject();
}
public JSONArray[] getAddedTabs(SQLConnection conn, String nodeType) {
if (isOracle(conn)) {
List<JSONArray> ls = new ArrayList<JSONArray>();
if ("tb".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Dependent Objects");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=depObjs");
ls.add(record);
}
if ("dtbs".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("System Options");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=systemOptions");
ls.add(record);
}
if ("ora_trig".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Trigger Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=triggerInfo");
ls.add(record);
record = new JSONArray();
record.put("Trigger Detail");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=triggerDetail");
ls.add(record);
} else if ("ora_proc".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Procedure Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=procInfo");
ls.add(record);
record = new JSONArray();
record.put("Procedure Parameters");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=procParameters");
ls.add(record);
record = new JSONArray();
record.put("Dependent Objects");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=depObjs");
ls.add(record);
} else if ("ora_funct".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Function Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=functInfo");
ls.add(record);
record = new JSONArray();
record.put("Function Parameters");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=functParameters");
ls.add(record);
record = new JSONArray();
record.put("Dependent Objects");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=depObjs");
ls.add(record);
} else if ("ora_pkg".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Package Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=pkgInfo");
ls.add(record);
record = new JSONArray();
record.put("Dependent Objects");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=depObjs");
ls.add(record);
} else if ("ora_pkgbody".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Package Body Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=pkgBodyInfo");
ls.add(record);
} else if ("ora_seq".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Sequence Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=seqInfo");
ls.add(record);
record = new JSONArray();
record.put("Sequence Detail");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=seqDetail");
ls.add(record);
} else if ("ora_trgs".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Triggers");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=triggers");
ls.add(record);
} else if ("ora_procs".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Procedures");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=procedures");
ls.add(record);
} else if ("ora_functs".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Functions");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=functions");
ls.add(record);
} else if ("ora_pkgs".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Packages");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=packages");
ls.add(record);
} else if ("ora_pkgbodys".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Package Body");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=packagebs");
ls.add(record);
} else if ("ora_seqs".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Sequences");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=sequences");
ls.add(record);
} else if ("ora_types".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Object Types");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=types");
ls.add(record);
} else if ("ora_bodytypes".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Object Type Bodies");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=bodytypes");
ls.add(record);
} else if ("ora_bodytype".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Object Type Body Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=bodyTypeInfo");
ls.add(record);
} else if ("ora_type".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Object Type Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=objectTypeInfo");
ls.add(record);
} else if ("ora_javas".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Java Sources");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=javas");
ls.add(record);
} else if ("ora_java".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Java Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=javaInfo");
ls.add(record);
} else if ("ora_javaress".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Java Resources");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=javaress");
ls.add(record);
} else if ("ora_javares".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Java Resource Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=javaResInfo");
ls.add(record);
} else if ("ora_javaclasses".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Java Classes");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=javaclasses");
ls.add(record);
} else if ("ora_libraries".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Libraries");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=libraries");
ls.add(record);
} else if ("ora_directories".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Directories");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=directories");
ls.add(record);
} else if ("ora_javaclass".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Java Class Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=javaClassInfo");
ls.add(record);
} else if ("ora_library".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Java Class Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=libraryInfo");
ls.add(record);
} else if ("ora_directory".equals(nodeType)) {
JSONArray record = new JSONArray();
record.put("Directory Info");
record.put("do?action=pluginAction&pluginName=OraclePlugin&method=directoryInfo");
ls.add(record);
}
return ls.toArray(new JSONArray[0]);
}
return null;
}
public List<IStructureNode> getCatalogAddedChildren(CatalogNode c,
SQLConnection conn) {
// TODO Auto-generated method stub
return null;
}
public JSONArray[] getDynamicPluginScripts(SQLConnection conn) {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>/src/main/java/com/riversql/IFileUploadAction.java
package com.riversql;
import org.apache.commons.fileupload.FileItem;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public interface IFileUploadAction {
public void execute(Map<String, FileItem> fileMap, Map<String, String> parameterMap, HttpServletResponse response, EntityManager em, EntityTransaction et) throws Exception;
}
<file_sep>/readme.md
[](https://travis-ci.org/jrialland/riversql)
Some evolutions around the original RiverSQL code, so I may use it in 2018.
- Build using maven
- Travis-ci
- Compiles & run on java8/tomcat8
- Use of slf4j for logging
- Can Now start "configuration-free" (changed configuration storage database to hsql)
=> [Live demo here](https://jriallandriversql-mxdishptat.now.sh) <=

<file_sep>/src/main/java/com/riversql/Request.java
package com.riversql;
import org.json.JSONException;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
@SuppressWarnings("serial")
public class Request extends DoServlet {
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp, EntityManager em, EntityTransaction et) throws Exception {
String className = req.getParameter("class");
Class jasonActionClass = Class.forName("com.riversql.actions." + className);
JSONDispatchAction jsonDispatchAction = (JSONDispatchAction) jasonActionClass.newInstance();
JSONObject obj = new JSONObject();
PrintWriter writer = resp.getWriter();
try {
JSONObject objsr = null;
et = em.getTransaction();
et.begin();
objsr = jsonDispatchAction.dispatch(req, resp, em, et);
if (et.isActive())
et.commit();
resp.setHeader("Content-Type", "text/html;charset=ISO-8859-1");
obj.put("success", true);
if (objsr != null)
obj.put("result", objsr);
} catch (Exception e) {
String errorMsg = "";
if (e instanceof InvocationTargetException) {
Throwable targetEx = ((InvocationTargetException) e).getTargetException();
if (targetEx != null) {
errorMsg = targetEx.toString();
}
} else {
errorMsg = e.toString();
}
if (et != null && et.isActive())
et.rollback();
try {
obj.put("success", false);
obj.put("error", errorMsg);
} catch (JSONException e1) {
}
} finally {
IDManager.set(null);
if (em != null)
em.close();
}
writer.write(obj.toString());
}
}
<file_sep>/src/main/java/com/riversql/actions/GenerateDDLCreateTable.java
package com.riversql.actions;
import com.riversql.IDManager;
import com.riversql.JSONAction;
import com.riversql.databases.DBSyntaxGeneratorFactory;
import com.riversql.databases.ISyntaxGenerator;
import com.riversql.dbtree.DBNode;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
public class GenerateDDLCreateTable implements JSONAction {
String tableid;
String schemaname;
String tablename;
String newCols;
String newIdxs;
String newPKs;
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
DBNode dbNode = (DBNode) IDManager.get().get(tableid);
JSONArray arrNewCols = new JSONArray(newCols);
JSONArray arrNewIdxs = new JSONArray(newIdxs);
JSONArray arrNewPKs = new JSONArray(newPKs);
ISyntaxGenerator syntaxGen = DBSyntaxGeneratorFactory.getSyntaxGenerator(dbNode.getConn());
JSONObject resultObj = new JSONObject();
String qualifiedName = tablename;
StringBuilder strbuilder = new StringBuilder();
strbuilder.append("Create Table ").append(schemaname).append(".").append(tablename);
if (syntaxGen != null) {
for (int i = 0; i < arrNewCols.length(); i++) {
JSONObject newObj = arrNewCols.getJSONObject(i);
String columnName = newObj.getString("cname");
String ctype = newObj.getString("ctype");
String csize = newObj.getString("csize");
String cdecdig = newObj.getString("cdecdig");
boolean acceptNull = newObj.getBoolean("cacceptnull");
String remarks = newObj.getString("ccom");
String def = newObj.getString("cdefault");
syntaxGen.newColumn(strbuilder, qualifiedName, columnName, ctype, csize, cdecdig, remarks, def, acceptNull);
}
for (int i = 0; i < arrNewPKs.length(); i++) {
JSONObject newObj = arrNewPKs.getJSONObject(i);
String pkname = newObj.getString("pkname");
JSONArray cols = newObj.getJSONArray("cols");
List<String> lsCols = new ArrayList<String>();
for (int j = 0; j < cols.length(); j++) {
lsCols.add(cols.getString(j).trim());
}
syntaxGen.newPK(strbuilder, qualifiedName, pkname, lsCols);
}
for (int i = 0; i < arrNewIdxs.length(); i++) {
JSONObject newObj = arrNewIdxs.getJSONObject(i);
String iName = newObj.getString("iname");
boolean unique = newObj.getBoolean("unique");
JSONArray cols = newObj.getJSONArray("cols");
List<String> lsCols = new ArrayList<String>();
for (int j = 0; j < cols.length(); j++) {
lsCols.add(cols.getString(j).trim());
}
syntaxGen.newIndex(strbuilder, qualifiedName, iName, unique, lsCols);
}
} else {
strbuilder.append("DDL not yet implemented for this database");
}
resultObj.put("ddl", strbuilder.toString());
return resultObj;
}
public void setTableid(String tableid) {
this.tableid = tableid;
}
public void setSchemaName(String schemaname) {
this.schemaname = schemaname;
}
public void setTablename(String tablename) {
this.tablename = tablename;
}
public void setNewPKs(String newPKs) {
this.newPKs = newPKs;
}
public void setNewIdxs(String newIdxs) {
this.newIdxs = newIdxs;
}
public void setNewCols(String newCols) {
this.newCols = newCols;
}
}
<file_sep>/src/main/java/com/riversql/actions/PluginAction.java
package com.riversql.actions;
import com.riversql.JSONAction;
import com.riversql.plugin.Plugin;
import com.riversql.plugin.PluginManager;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PluginAction implements JSONAction {
String pluginName;
String pluginAction;
public void setPluginAction(String pluginAction) {
this.pluginAction = pluginAction;
}
public void setPluginName(String pluginName) {
this.pluginName = pluginName;
}
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
Plugin plug = PluginManager.getInstance().getPluginByName(pluginName);
if (plug != null) {
JSONObject str = plug.executeAction(request, response, em, et);
return str;
}
return null;
}
}
<file_sep>/src/main/java/com/riversql/IDManager.java
package com.riversql;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class IDManager {
private static ThreadLocal<IDManager> threadlocalIDManager = new ThreadLocal<IDManager>();
AtomicInteger ai = new AtomicInteger(0);
AtomicInteger ai2 = new AtomicInteger(0);
HashMap<String, Object> map = new HashMap<String, Object>();
protected IDManager() {
}
public static IDManager get() {
IDManager ex = threadlocalIDManager.get();
return ex;
}
public static void set(IDManager ex) {
threadlocalIDManager.set(ex);
}
protected int nextInt() {
return ai.incrementAndGet();
}
public String nextID() {
return "0000" + Integer.toHexString(nextInt());
}
synchronized public void put(String id, Object schemaNode) {
map.put(id, schemaNode);
}
synchronized public Object get(String id) {
return map.get(id);
}
public int nextSessionID() {
return ai2.incrementAndGet();
}
}
<file_sep>/src/main/java/com/riversql/actions/GetTableColumnsForAlterTable.java
package com.riversql.actions;
import com.riversql.IDManager;
import com.riversql.JSONAction;
import com.riversql.dbtree.TableNode;
import com.riversql.sql.TableColumnInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetTableColumnsForAlterTable implements JSONAction {
String id = null;
public void setId(String id) {
this.id = id;
}
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
TableNode tn = (TableNode) IDManager.get().get(id);
TableColumnInfo colsInfo[] = tn.getConn().getSQLMetaData().getColumnInfo(tn.getITableInfo());
JSONObject ret = new JSONObject();
JSONArray arr = new JSONArray();
for (int i = 0; i < colsInfo.length; i++) {
JSONObject obj = new JSONObject();
obj.put("cname", colsInfo[i].getColumnName());
obj.put("cnameold", colsInfo[i].getColumnName());
obj.put("ctype", colsInfo[i].getTypeName().toUpperCase());
obj.put("csize", colsInfo[i].getColumnSize());
obj.put("cdecdig", colsInfo[i].getDecimalDigits());
String remarks = colsInfo[i].getRemarks();
if (remarks == null)
remarks = "";
obj.put("ccom", remarks);
String def = colsInfo[i].getDefaultValue();
if (def == null)
def = "";
obj.put("cdefault", def);
String nullable = colsInfo[i].isNullable();
boolean bnull = true;
if (nullable != null)
bnull = !nullable.toUpperCase().equals("NO");
obj.put("cacceptnull", bnull);
obj.put("cacceptnullold", bnull);
arr.put(obj);
}
ret.put("columns", arr);
return ret;
}
}
<file_sep>/src/main/java/com/riversql/plugins/mysql/actions/Show.java
package com.riversql.plugins.mysql.actions;
import com.riversql.sql.SQLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public abstract class Show {
private SQLConnection conn;
public Show(SQLConnection conn) {
this.conn = conn;
}
public abstract String getShowString();
public final JSONObject execute() throws Exception {
JSONObject results = new JSONObject();
JSONArray meta = new JSONArray();
JSONArray data = new JSONArray();
String sql = getShowString();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData metars = rs.getMetaData();
int icount = metars.getColumnCount();
for (int i = 0; i < icount; i++) {
meta.put(metars.getColumnLabel(i + 1));
}
while (rs.next()) {
JSONArray record = new JSONArray();
for (int i = 0; i < icount; i++) {
record.put(rs.getString(i + 1));
}
data.put(record);
}
} catch (SQLException e) {
//LoggerFactory.getLogger(getClass()).error("error", e);;
} finally {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
}
try {
if (ps != null)
ps.close();
} catch (SQLException e) {
}
}
results.put("meta", meta);
results.put("data", data);
return results;
}
}
<file_sep>/src/main/java/com/riversql/Page.java
package com.riversql;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
@SuppressWarnings("serial")
public class Page extends DoServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(Page.class);
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp, EntityManager em, EntityTransaction et) throws Exception {
try {
String className = req.getParameter("class");
Class iPageActionClass = Class.forName("com.riversql.actions." + className);
IPageAction iPageAction = (IPageAction) iPageActionClass.newInstance();
BeanUtils.populate(iPageAction, req.getParameterMap());
et = em.getTransaction();
et.begin();
iPageAction.execute(req, resp, em, et);
et.commit();
} catch (Exception e) {
//TODO return page with error
if (et != null && et.isActive())
et.rollback();
try {
req.setAttribute("pageid", req.getParameter("pageid"));
req.setAttribute("emsg", e.getMessage());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.close();
sw.close();
req.setAttribute("error", sw.toString());
req.getRequestDispatcher("error.jsp").forward(req, resp);
} catch (Exception e1) {
LOGGER.error("could not display error page", e1);
}
} finally {
IDManager.set(null);
if (em != null)
em.close();
}
}
}
<file_sep>/src/main/java/com/riversql/actions/GetTableIndexesForAlterTable.java
package com.riversql.actions;
import com.riversql.IDManager;
import com.riversql.JSONAction;
import com.riversql.dbtree.TableNode;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
public class GetTableIndexesForAlterTable implements JSONAction {
String id = null;
public void setId(String id) {
this.id = id;
}
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
TableNode tn = (TableNode) IDManager.get().get(id);
String pkName = tn.getPkName();
ResultSet rs = null;
class IndexInfo {
boolean unique;
List<String> ls = new ArrayList<String>();
}
TreeMap<String, IndexInfo> mp = new TreeMap<String, IndexInfo>();
try {
rs = tn.getIndexes();
while (rs.next()) {
boolean nonUnique = rs.getBoolean("NON_UNIQUE");
String column_name = rs.getString("COLUMN_NAME");
String index_name = rs.getString("INDEX_NAME");
if (index_name != null) {
if (index_name.equals(pkName))
continue;
IndexInfo ii = mp.get(index_name);
if (ii == null) {
ii = new IndexInfo();
ii.unique = !nonUnique;
mp.put(index_name, ii);
}
ii.ls.add(column_name);
}
}
} finally {
try {
if (rs != null) {
Statement st = rs.getStatement();
rs.close();
if (st != null)
st.close();
}
} catch (Exception e) {
}
}
JSONArray arr = new JSONArray();
for (Iterator<String> iterator = mp.keySet().iterator(); iterator.hasNext(); ) {
String key = iterator.next();
IndexInfo ii = mp.get(key);
JSONObject obj = new JSONObject();
obj.put("iname", key);
obj.put("unique", ii.unique);
JSONArray colArray = new JSONArray();
for (int i = 0; i < ii.ls.size(); i++) {
colArray.put(ii.ls.get(i));
}
obj.put("cols", colArray);
arr.put(obj);
}
JSONObject ret = new JSONObject();
ret.put("indexes", arr);
return ret;
}
}
<file_sep>/src/main/java/com/riversql/actions/RedoQuery.java
package com.riversql.actions;
import com.riversql.IDManager;
import com.riversql.JSONAction;
import com.riversql.utils.SQLExecutor;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RedoQuery implements JSONAction {
String queryID = null;
public void setQueryID(String queryID) {
this.queryID = queryID;
}
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
SQLExecutor executor = (SQLExecutor) IDManager.get().get(queryID);
JSONObject resultSet = new JSONObject();
JSONArray meta = new JSONArray();
JSONArray data = new JSONArray();
JSONArray info2 = new JSONArray();
try {
executor.redoQuery(data, meta, info2);
info2.put(true);
} catch (Exception e) {
info2.put(false);
info2.put(e.getMessage());
}
resultSet.put("meta", meta);
resultSet.put("data", data);
resultSet.put("info", info2);
return resultSet;
}
}
<file_sep>/src/main/java/com/riversql/plugins/oracle/actions/SeqDetail.java
package com.riversql.plugins.oracle.actions;
import com.riversql.IDManager;
import com.riversql.plugin.BasePluginType;
import com.riversql.plugins.oracle.SequenceNode;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class SeqDetail {
private String id;
public SeqDetail(String id) {
this.id = id;
}
public JSONObject execute() throws Exception {
JSONObject results = new JSONObject();
JSONArray meta = new JSONArray();
JSONArray data = new JSONArray();
String[] detailKeys = {"Min Value", "Max Value", "Increment By", "Cycle Flag", "Order", "Cache Size", "Last Number"};
String[] strs = {"Property", "Value"};
for (int i = 0; i < strs.length; i++) {
meta.put(strs[i]);
}
Object obj = IDManager.get().get(id);
SequenceNode seq = (SequenceNode) obj;
final String sql = "select min_value,max_value,increment_by,cycle_flag,order_flag, cache_size, last_number from sys.all_sequences " +
"where sequence_owner=? and sequence_name=?";
ResultSet rs = null;
PreparedStatement ps = null;
try {
ps = seq.getConn().prepareStatement(sql);
BasePluginType tot = (BasePluginType) seq.getParent();
String owner = tot.getParent().getName();
ps.setString(1, owner);
ps.setString(2, seq.getName());
rs = ps.executeQuery();
if (rs.next()) {
for (int i = 0; i < detailKeys.length; i++) {
JSONArray record = new JSONArray();
record.put(detailKeys[i]);
record.put(rs.getString(i + 1));
data.put(record);
}
}
} catch (Exception e) {
} finally {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
if (ps != null)
ps.close();
} catch (Exception e) {
}
}
results.put("meta", meta);
results.put("data", data);
return results;
}
}
<file_sep>/src/main/java/com/riversql/actions/Preview.java
package com.riversql.actions;
import com.riversql.IDManager;
import com.riversql.JSONAction;
import com.riversql.dbtree.TableNode;
import com.riversql.utils.ResultSetReader;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class Preview implements JSONAction {
String id;
public void setId(String id) {
this.id = id;
}
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
JSONObject results = new JSONObject();
JSONArray meta = new JSONArray();
JSONArray data = new JSONArray();
Object obj = IDManager.get().get(id);
if (obj != null && obj instanceof TableNode) {
TableNode table = ((TableNode) obj);
Connection conn = table.getConn().getConnection();
try {
String sql = "select * from " + table.getITableInfo().getQualifiedName();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setMaxRows(20);
ResultSet rs = ps.executeQuery();
if (rs != null) {
ResultSetMetaData metadata = rs.getMetaData();
int columncount = metadata.getColumnCount();
for (int i = 1; i <= columncount; i++) {
String label = metadata.getColumnLabel(i);
meta.put(label);
}
ResultSetReader reader = new ResultSetReader(rs);
//dataset.setResultSet(rs);
Object[] row;
while ((row = reader.readRow()) != null) {
JSONArray record = new JSONArray();
for (int i = 0; i < columncount; i++) {
Object obj1 = row[i];
record.put(obj1);
}
data.put(record);
}
rs.close();
}
ps.close();
} catch (Exception e) {
}
}
results.put("meta", meta);
results.put("data", data);
return results;
}
}
<file_sep>/src/main/java/com/riversql/plugins/mysql/actions/ShowEngines.java
package com.riversql.plugins.mysql.actions;
import com.riversql.sql.SQLConnection;
public class ShowEngines extends Show {
public ShowEngines(SQLConnection conn) {
super(conn);
}
@Override
public String getShowString() {
return "SHOW ENGINES";
}
}
<file_sep>/src/main/java/com/riversql/plugins/mysql/UsersNode.java
package com.riversql.plugins.mysql;
import com.riversql.dbtree.CatalogNode;
import com.riversql.dbtree.IStructureNode;
import com.riversql.plugin.BasePluginType;
import com.riversql.sql.SQLConnection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class UsersNode extends BasePluginType implements IStructureNode {
public UsersNode(CatalogNode caNode, SQLConnection conn) {
super("User", caNode, conn);
}
@Override
public void load() {
if (loaded)
return;
ResultSet rs = null;
PreparedStatement ps = null;
try {
final String sql = "select concat('''',user,'''','@','''',host,'''') from mysql.user";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
String oname = rs.getString(1);
UserNode functNode = new UserNode(this, oname, conn);
list.add(functNode);
}
} catch (Exception e) {
list.clear();
} finally {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
if (ps != null)
ps.close();
} catch (Exception e) {
}
}
loaded = true;
}
private String getOwner() {
return parentNode.getName();
}
public String getCls() {
return "objs";
}
public String getType() {
return "mysql_users";
}
public boolean isLeaf() {
return false;
}
}
<file_sep>/src/main/java/com/riversql/actions/Connect.java
package com.riversql.actions;
import com.riversql.IDManager;
import com.riversql.JSONAction;
import com.riversql.WebSQLSession;
import com.riversql.dao.DriversDAO;
import com.riversql.dao.SourcesDAO;
import com.riversql.dbtree.SQLSession;
import com.riversql.entities.Driver;
import com.riversql.entities.Source;
import com.riversql.plugin.PluginManager;
import com.riversql.sql.ISQLDriver;
import com.riversql.sql.SQLConnection;
import com.riversql.sql.SQLDriver;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
public class Connect implements JSONAction {
String user, password;
int driverid, sourceid;
String autocommit;
public void setAutocommit(String autocommit) {
this.autocommit = autocommit;
}
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public void setDriverid(int driverid) {
this.driverid = driverid;
}
public void setSourceid(int sourceid) {
this.sourceid = sourceid;
}
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
Driver driver = DriversDAO.getDriver(em, driverid);
Source source = SourcesDAO.getSource(em, sourceid);
ISQLDriver idriver = new SQLDriver();
idriver.setDriverClassName(driver.getDriverClassName());
JSONObject obj = new JSONObject();
java.sql.Driver sqlDriver = (java.sql.Driver) Class.forName(driver.getDriverClassName()).newInstance();
DriverManager.registerDriver(sqlDriver);
Connection _conn = DriverManager.getConnection(source.getJdbcUrl(), user, password);
if (autocommit != null) {
_conn.setAutoCommit(true);
} else {
_conn.setAutoCommit(false);
}
SQLConnection conn = new SQLConnection(_conn, null, idriver);
WebSQLSession sessions = (WebSQLSession) request.getSession(true).getAttribute("sessions");
sessions.getSqlsessions().add(new SQLSession(sourceid, source.getSourceName() + " (" + IDManager.get().nextSessionID() + ")", conn));
obj.put("success", true);
JSONArray arr = new JSONArray();
PluginManager.getInstance().dynamicPluginScripts(arr, conn);
obj.put("pluginScripts", arr);
return obj;
}
}
<file_sep>/src/main/java/com/riversql/actions/TestSourceConnection.java
package com.riversql.actions;
import com.riversql.JSONAction;
import com.riversql.dao.DriversDAO;
import com.riversql.dao.SourcesDAO;
import com.riversql.entities.Driver;
import com.riversql.entities.Source;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
public class TestSourceConnection implements JSONAction {
String password;
int id;
public void setPassword(String password) {
this.password = password;
}
public void setId(int id) {
this.id = id;
}
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
Source s = SourcesDAO.getSource(em, id);
int driverid = s.getDriverid();
Driver driver = DriversDAO.getDriver(em, driverid);
String jdbcUrl = s.getJdbcUrl();
String username = s.getUserName();
//Driver drv=null;
Connection conn = null;
try {
Class.forName(driver.getDriverClassName());
conn = DriverManager.getConnection(jdbcUrl, username, password);
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
return new JSONObject();
}
}
<file_sep>/src/main/java/com/riversql/DoServlet.java
package com.riversql;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@SuppressWarnings("serial")
public abstract class DoServlet extends HttpServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(DoServlet.class);
@SuppressWarnings("unchecked")
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
HttpSession session = req.getSession(true);
synchronized (session) {
WebSQLSession sessions = (WebSQLSession) session.getAttribute("sessions");
if (sessions != null) {
IDManager idmanager = sessions.getIDManager();
IDManager.set(idmanager);
} else {
WebSQLSession newsessions = new WebSQLSession();
IDManager.set(newsessions.getIDManager());
session.setAttribute("sessions", newsessions);
sessions = newsessions;
}
}
EntityManagerFactory emf = (EntityManagerFactory) session.getServletContext().getAttribute("emf");
EntityManager em = emf.createEntityManager();
EntityTransaction et = null;
String usernamesession = (String) session.getAttribute("loggeduser");
String username = null;
// Do we allow that user?
if (usernamesession == null) {
String auth = req.getHeader("Authorization");
username = allowUser(em, auth);
}
if (usernamesession == null && username == null) {
em.close();
resp.setContentType("text/plain");
resp.setHeader("WWW-Authenticate", "BASIC realm=\"dwLoader users\"");
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
} else if (usernamesession == null) {
usernamesession = username;
session.setAttribute("loggeduser", username);
int dot = usernamesession.indexOf(".");
if (dot > -1) {
String shortName = username.substring(0, dot);
shortName = shortName.substring(0, 1).toUpperCase() + shortName.substring(1).toLowerCase();
session.setAttribute("shortName", shortName);
} else {
String capitalized = username.substring(0, 1).toUpperCase() + username.substring(1).toLowerCase();
session.setAttribute("shortName", capitalized);
}
}
String action = req.getParameter("action");
if (action != null && action.equals("main")) {
em.close();
req.getRequestDispatcher("/main.jsp").forward(req, resp);
return;
}
try {
execute(req, resp, em, et);
} catch (Exception ex) {
LOGGER.error(DoServlet.class.getName(), ex);
}
}
public abstract void execute(HttpServletRequest request, HttpServletResponse response, EntityManager em, EntityTransaction et) throws Exception;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
protected String allowUser(EntityManager em, String auth) {
return "User";
}
}
<file_sep>/src/main/java/com/riversql/entities/Driver.java
package com.riversql.entities;
import javax.persistence.*;
@NamedQueries(value = {
@NamedQuery(name = "Driver.selectAll", query = "SELECT p FROM Driver p order by p.driverName")
})
@Entity
@Table(name = "DRIVER")
public class Driver {
@Column(length = 255, nullable = false)
String driverName;
@Column(length = 600)
String exampleUrl;
@Column(length = 600, nullable = false)
String driverClassName;
@Column(length = 600)
String iconUrl = "ext/resources/images/default/s.gif";
@Id
@GeneratedValue
@Column(name = "DRIVER_ID")
int id;
private boolean valid;
public String getDriverName() {
return driverName;
}
public void setDriverName(String driverName) {
this.driverName = driverName;
}
public String getExampleUrl() {
return exampleUrl;
}
public void setExampleUrl(String exampleUrl) {
this.exampleUrl = exampleUrl;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
this.valid = validate();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private boolean validate() {
try {
Class<?> clazz = Class.forName(driverClassName);
if (java.sql.Driver.class.isAssignableFrom(clazz))
return true;
} catch (Exception e) {
return false;
}
return false;
}
public boolean isValid() {
return valid;
}
public String getIconurl() {
return iconUrl;
}
public void setIconUrl(String iconurl) {
this.iconUrl = iconurl;
}
public void updateValidation(EntityManager em) {
this.valid = validate();
em.merge(this);
}
}
<file_sep>/src/main/java/com/riversql/actions/ChangeCatalog.java
package com.riversql.actions;
import com.riversql.IDManager;
import com.riversql.JSONAction;
import com.riversql.dbtree.SQLSession;
import com.riversql.sql.SQLConnection;
import org.json.JSONObject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ChangeCatalog implements JSONAction {
String catalog, sessionid;
public void setCatalog(String catalog) {
this.catalog = catalog;
}
public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}
public JSONObject execute(HttpServletRequest request,
HttpServletResponse response, EntityManager em, EntityTransaction et)
throws Exception {
SQLConnection conn = null;
if (sessionid != null) {
SQLSession sqlsession = (SQLSession) IDManager.get().get(sessionid);
if (sqlsession != null) {
conn = sqlsession.getConn();
conn.setCatalog(catalog);
}
}
JSONObject ret = new JSONObject();
return ret;
}
}
<file_sep>/src/main/java/com/riversql/Do.java
package com.riversql;
import com.riversql.actions.*;
import org.apache.commons.beanutils.BeanUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("serial")
public class Do extends DoServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(DoServlet.class);
Map<String, Class<? extends JSONAction>> jsonActionMap;
Map<String, Class<? extends IPageAction>> pageActionMap;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
HashMap<String, Class<? extends JSONAction>> tmp = new HashMap<String, Class<? extends JSONAction>>();
tmp.put("generateDDLAlterTable", GenerateDDLAlterTable.class);
tmp.put("generateDDLCreateTable", GenerateDDLCreateTable.class);
tmp.put("generateDDLCreateIndex", GenerateDDLCreateIndex.class);
tmp.put("getTableColumns", GetTableColumns.class);
tmp.put("getTableIndexesAlterTable", GetTableIndexesForAlterTable.class);
tmp.put("getTableColumnsAlterTable", GetTableColumnsForAlterTable.class);
tmp.put("getPKAlterTable", GetPKForAlterTable.class);
tmp.put("getTypesAlterTable", GetTypesAlterTable.class);
tmp.put("getMenu", GetMenu.class);
tmp.put("pluginAction", PluginAction.class);
tmp.put("getPK", GetPK.class);
tmp.put("getFK", GetFK.class);
tmp.put("getMeta", GetMeta.class);
tmp.put("getExportedKeys", GetExportedKeys.class);
tmp.put("getAdditionalData", GetAdditionalData.class);
tmp.put("redoQuery", RedoQuery.class);
tmp.put("changeCatalog", ChangeCatalog.class);
tmp.put("getColumnsForViewer", GetColumnsForViewer.class);
tmp.put("getSources", GetSources.class);
tmp.put("getIndexes", GetIndexes.class);
tmp.put("getDatabaseMetadata", GetDatabaseMetadata.class);
tmp.put("getConnectionStatus", GetConnectionStatus.class);
tmp.put("getGrants", GetGrants.class);
tmp.put("closeResultSet", CloseResultSet.class);
tmp.put("commitConnection", CommitConnection.class);
tmp.put("closeConnection", CloseConnection.class);
tmp.put("rollbackConnection", RollbackConnection.class);
tmp.put("getDrivers", GetDrivers.class);
tmp.put("getDetails", GetDetails.class);
tmp.put("createDriver", CreateDriver.class);
tmp.put("deleteDriver", DeleteDriver.class);
tmp.put("updateDriver", UpdateDriver.class);
tmp.put("preview", Preview.class);
tmp.put("ping", Ping.class);
tmp.put("updateSource", UpdateSource.class);
tmp.put("createSource", CreateSource.class);
tmp.put("deleteSource", DeleteSource.class);
tmp.put("getTree", GetTree.class);
tmp.put("getDatabases", GetDatabases.class);
tmp.put("testSourceConnection", TestSourceConnection.class);
tmp.put("connect", Connect.class);
tmp.put("execute", ExecuteSQL.class);
tmp.put("export", Export.class);
tmp.put("import", Import.class);
jsonActionMap = Collections.unmodifiableMap(tmp);
HashMap<String, Class<? extends IPageAction>> tmp2 = new HashMap<String, Class<? extends IPageAction>>();
//tmp2.put("selectTable",SelectTable.class);
tmp2.put("about", AboutPage.class);
tmp2.put("config", ConfigPage.class);
tmp2.put("sourcesPage", SourcesPage.class);
tmp2.put("exportTablePage", ExportTablePage.class);
tmp2.put("doExport", DoExport.class);
tmp2.put("excelExport", ExcelExport.class);
tmp2.put("pdfExport", PdfExport.class);
tmp2.put("csvExport", CsvExport.class);
pageActionMap = Collections.unmodifiableMap(tmp2);
}
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp, EntityManager em, EntityTransaction et) throws Exception {
String action = req.getParameter("action");
Class<? extends JSONAction> iactionclass = jsonActionMap.get(action);
if (iactionclass != null) {
JSONObject obj = new JSONObject();
PrintWriter writer = resp.getWriter();
try {
JSONAction iaction = iactionclass.newInstance();
BeanUtils.populate(iaction, req.getParameterMap());
et = em.getTransaction();
et.begin();
JSONObject objsr = iaction.execute(req, resp, em, et);
if (et.isActive())
et.commit();
resp.setHeader("Content-Type", "text/html;charset=ISO-8859-1");
obj.put("success", true);
if (objsr != null)
obj.put("result", objsr);
} catch (Exception e) {
LOGGER.error("While handling action '" + action + "'", e);
if (et != null && et.isActive())
et.rollback();
try {
obj.put("success", false);
obj.put("error", e.toString());
} catch (JSONException e1) {
LOGGER.error("JSON Error", e1);
}
} finally {
IDManager.set(null);
if (em != null)
em.close();
}
writer.write(obj.toString());
} else {
Class<? extends IPageAction> iPageActionclass = pageActionMap.get(action);
if (iPageActionclass != null) {
try {
IPageAction iPageAction = iPageActionclass.newInstance();
BeanUtils.populate(iPageAction, req.getParameterMap());
et = em.getTransaction();
et.begin();
iPageAction.execute(req, resp, em, et);
et.commit();
} catch (Exception e) {
LOGGER.error("While handling page action", e);
//TODO return page with error
if (et != null && et.isActive())
et.rollback();
try {
req.setAttribute("pageid", req.getParameter("pageid"));
req.setAttribute("emsg", e.getMessage());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.close();
sw.close();
req.setAttribute("error", sw.toString());
req.getRequestDispatcher("error.jsp").forward(req, resp);
} catch (Exception e1) {
LOGGER.error("", e1);
}
} finally {
IDManager.set(null);
if (em != null)
em.close();
}
} else {
if (em != null)
em.close();
throw new IllegalArgumentException("No such action : " + action);
}
}
}
}
<file_sep>/deploy/Dockerfile
FROM frolvlad/alpine-oraclejdk8
ENV CATALINA_HOME /usr/local/tomcat
ENV PATH $CATALINA_HOME/bin:$PATH
RUN mkdir -p "$CATALINA_HOME"
WORKDIR $CATALINA_HOME
ENV TOMCAT_MAJOR 8
ENV TOMCAT_VERSION 8.5.34
ENV TOMCAT_TGZ_URL http://apache.mirrors.ovh.net/ftp.apache.org/dist/tomcat/tomcat-$TOMCAT_MAJOR/v$TOMCAT_VERSION/bin/apache-tomcat-$TOMCAT_VERSION.tar.gz
RUN apk add curl
RUN set -x && curl -fSL "$TOMCAT_TGZ_URL" -o tomcat.tar.gz \
&& tar -xvf tomcat.tar.gz --strip-components=1 \
&& rm bin/*.bat \
&& rm tomcat.tar.gz*
RUN apk del curl
RUN rm $CATALINA_HOME/webapps/* -rf
ADD ./ROOT $CATALINA_HOME/webapps/ROOT
EXPOSE 8080
CMD ["catalina.sh", "run"]
<file_sep>/src/main/java/com/riversql/ContextListener.java
package com.riversql;
import com.riversql.dao.DriversDAO;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
public class ContextListener implements ServletContextListener {
private static final String PU_NAME = "riversql";
private static EntityManagerFactory emf;
public static EntityManagerFactory getEntityManagerFactory() {
return emf;
}
public static void setEntityManagerFactory(EntityManagerFactory emf) {
ContextListener.emf = emf;
}
public void contextDestroyed(ServletContextEvent sce) {
EntityManagerFactory emf = (EntityManagerFactory) sce.getServletContext().getAttribute("emf");
if (emf != null)
emf.close();
}
protected EntityManagerFactory createEntityManagerFactoryFromProperties(Path propFile) throws IOException {
if (!Files.isRegularFile(propFile)) {
throw new IllegalStateException("Not a regular file : " + propFile);
}
try (final InputStream in = Files.newInputStream(propFile)) {
final Properties props = new Properties();
props.load(in);
return Persistence.createEntityManagerFactory(PU_NAME, props);
}
}
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
Path props = Paths.get(sc.getRealPath("WEB-INF/database.properties"));
try {
EntityManagerFactory emf = createEntityManagerFactoryFromProperties(props);
setEntityManagerFactory(emf);
sc.setAttribute("emf", emf);
EntityManager em = emf.createEntityManager();
DriversDAO.initialize(em);
em.close();
} catch (Exception e) {
throw new IllegalStateException(e);
}
sc.setAttribute("riversql_version", sc.getInitParameter("riversql_version"));
}
}<file_sep>/src/main/java/com/riversql/entities/Source.java
package com.riversql.entities;
import javax.persistence.*;
import java.util.Date;
@NamedQueries(value = {
@NamedQuery(name = "Source.selectAll", query = "SELECT p FROM Source p"),
@NamedQuery(name = "Source.deleteAll", query = "delete FROM Source p")
}
)
@Entity
@Table(name = "SOURCE")
public class Source {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "SOURCE_ID")
int id;
@Column(name = "SOURCE_NAME", nullable = false, length = 255, unique = true)
String sourceName;
@Column(name = "JDBC_URL", nullable = false, length = 255)
String jdbcUrl;
@Column(name = "USER_NAME", nullable = false, length = 255)
String userName;
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
Date creationDate;
@Column(name = "DRIVER_ID", nullable = false)
int driverid;
@Version
int version;
public String getJdbcUrl() {
return jdbcUrl;
}
public void setJdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSourceName() {
return sourceName;
}
public void setSourceName(String sourceName) {
this.sourceName = sourceName;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getDriverid() {
return driverid;
}
public void setDriverid(int driverid) {
this.driverid = driverid;
}
}
| 18e54913a6f1ce6696ade3d1fc4e840f89c093fe | [
"Markdown",
"Maven POM",
"Java",
"Dockerfile",
"Shell"
] | 40 | Java | jrialland/riversql | 9eda1050d6af0ba7ae5bd2a418310e565cf740fd | 1c9e585131f3f0c3297f76a592f0f59602baa558 |
refs/heads/master | <file_sep>package ilog
import (
"encoding/json"
"io/ioutil"
"github.com/BurntSushi/toml"
)
// LogConfig 日志配置
type LogConfig struct {
AdapterConsole bool `toml:"adapter_console"` // 是否输出到控制台
ConsoleLevel int `toml:"console_level"` // 输出到命令行的日志级别
File string `toml:"file"` // 文件日志输出路径
FileLevel int `toml:"file_level"` // 文件日志级别
EnableFuncCallDepth bool `toml:"enable_func_call_depth"` // 是否输出行号和文件名
Async bool `toml:"async"` // 是否异步输出,提升性能
ChanLength int `toml:"chan_length"` // 异步channel大小
Rotate bool `toml:"rotate"` // 是否开启日志rotate
Maxlines int `toml:"maxlines"` // 单个文件行数限制
Maxsize int `toml:"maxsize"` // 单个文件大小限制
Daily bool `toml:"daily"` // 是否按照每天rotat
Maxdays int `toml:"maxdays"` // 文件最多保留天数
Multifile bool `toml:"multifile"` // 是否分文件存储日志
Separate []string `toml:"separate"` //分文件存储的日志类型
}
// CreateLogger 创建一个logger对象
func CreateLogger(cfgFile string) *BeeLogger {
content, err := ioutil.ReadFile(cfgFile)
if err != nil {
panic(err)
}
var cfg LogConfig
if _, err := toml.Decode(string(content), &cfg); err != nil {
panic(err)
}
log := NewLogger()
// 设置异步输出
if cfg.Async {
log.Async(int64(cfg.ChanLength))
}
// 设置输出文件名、文件行数
if cfg.EnableFuncCallDepth {
log.EnableFuncCallDepth(true)
}
// 设置控制台输出
if cfg.AdapterConsole {
consoleConfig := make(map[string]int)
consoleConfig["level"] = cfg.ConsoleLevel
byt, _ := json.Marshal(consoleConfig)
log.SetLogger(AdapterConsole, string(byt))
}
fileConfig := make(map[string]interface{})
fileConfig["filename"] = cfg.File
fileConfig["maxlines"] = cfg.Maxlines
fileConfig["maxsize"] = cfg.Maxsize
fileConfig["daily"] = cfg.Daily
fileConfig["maxdays"] = cfg.Maxdays
fileConfig["rotate"] = cfg.Rotate
if cfg.Multifile {
fileConfig["separate"] = cfg.Separate
byt, _ := json.Marshal(fileConfig)
log.SetLogger(AdapterMultiFile, string(byt))
} else {
byt, _ := json.Marshal(fileConfig)
log.SetLogger(AdapterFile, string(byt))
}
// 据说不这样做,会有一些性能问题
log.SetLevel(cfg.FileLevel)
return log
}
<file_sep># 是否输出到控制台 true|false
adapter_console=true
# 输出到命令行的日志级别 2:critical;3:error;4:warning;5:notice;6:info;7:debug;8:trace
console_level = 8
# 日志保留路径
file="/data/ilog/main.log"
# 文件日志级别 2:critical;3:error;4:warning;5:notice;6:info;7:debug;8:trace
file_level=8
# 是否输出行号和文件名 true|false
enable_func_call_depth=true
# 是否异步输出,提升性能 true|false
async=true
# 异步channel大小
chan_length=10000
# 是否开启日志rotate true|false
rotate=true
# 是否按照每天rotate true|false
daily=false
# 单个文件行数限制
maxlines=0
# 单个文件大小限制
maxsize=102400000
# 文件最多保留天数
maxdays = 1
# 是否分文件存储日志 true|false
multifile=true
# 分文件存储的日志类型
separate=["info", "warning", "error", "critical"]
| 206c24fc2bd80bb736deee810dbea1eb9293a4d9 | [
"TOML",
"Go"
] | 2 | Go | fwhappy/ilog | 84ab4d71461ab9564c786dcab65c4716beaa989e | 565c221ceb346ca42f26c76ff95fa57a0153ca68 |
refs/heads/master | <file_sep>
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from pyconf import __version__
metadata = {
'name': 'pyconf',
'py_modules': ['pyconf'],
'version': __version__,
'author': '<NAME>',
'author_email': '<EMAIL>',
'license': 'MIT',
'url': 'https://github.com/hrtshu/pyconf',
}
setup(**metadata)
<file_sep>
from sys import version_info
__version__ = '0.1.2'
__all__ = ['read_config']
def _initialize_globals(globals):
exec('', globals)
return globals
def _exclude_init_globals(globals, init_globals):
new_globals = {}
for k in globals:
if not (k in init_globals and globals[k] is init_globals[k]):
new_globals[k] = globals[k]
return new_globals
def _dict_intersect(a, b): # a(dict) & b(iterable)
res = {}
for k, v in a.items():
if k in b:
res[k] = v
return res
default_globals = _initialize_globals({})
def read_config(src, required=[], default={}, exclude_unknown=True,
ignore_unknown=True, exclude_init_globals=True, globals=None,
__name__='__main__', __file__=None, exec_=None):
globals = globals or default_globals.copy()
if __name__ is not None:
globals['__name__'] = __name__
if __file__ is not None:
globals['__file__'] = __file__
init_globals = globals.copy()
# TODO configファイルが例外を送出した場合の処理
if exec_ is None:
exec(src, globals)
else:
exec_(src, globals)
if exclude_init_globals:
globals = _exclude_init_globals(globals, init_globals)
required = set(required)
missing_required = required - set(globals.keys())
if missing_required:
raise AttributeError(
'missing required name(s): {}'.format(', '.join(missing_required))
)
conf = default.copy()
conf.update(globals)
known = required | set(default)
if not ignore_unknown:
extra = set(conf.keys()) - known
if extra:
raise AttributeError('given unrecognized name(s): {}'.format())
else:
if exclude_unknown:
conf = _dict_intersect(conf, known)
return conf
| e05804157de056b51edefe0c60eed2183fe7b8d3 | [
"Python"
] | 2 | Python | hrtshu/pyconf-dev | 1c9953ccb129695d89e0453bdc7e8523fdfd28c2 | cda1fa431b81293006671cfebf7de73d41189cc4 |
refs/heads/main | <file_sep>objects=[];
video='';
status='';
function preload(){
video=createVideo("video.mp4");;
video.hide()
}
function setup() {
canvas = createCanvas(1240,336);
//canvas = createCanvas(650,400);
video = createCapture(VIDEO);
video.size(600,300);
canvas.parent('canvas');
instializeInSetup(mario);
poseNet=ml5.poseNet(video,modelloaded);
poseNet.on('pose',gotposes);
}
function draw(){
image(video,0,0,380,380);
} | 4219d8caf7c508396bfc3888e2f78407ffeeb824 | [
"JavaScript"
] | 1 | JavaScript | vivaan-rocks/github | 3217a83fd63da1b234d6b2caaadb6fdd4c44d8be | 15190173507b9316fc8043d0f97455a5a988d2c5 |
refs/heads/master | <repo_name>wxx961023/z-wheel<file_sep>/test/tabs-item.test.js
const expect = chai.expect
import Tabs from '../src/tabs/tabs'
import TabsHead from '../src/tabs/tabs-head'
import TabsBody from '../src/tabs/tabs-body'
import TabsItem from '../src/tabs/tabs-item'
import TabsPane from '../src/tabs/tabs-pane'
import Vue from 'vue'
Vue.component('z-tabs', Tabs)
Vue.component('z-tabs-head', TabsHead)
Vue.component('z-tabs-body', TabsBody)
Vue.component('z-tabs-item', TabsItem)
Vue.component('z-tabs-pane', TabsPane)
Vue.config.productionTip = false
Vue.config.devtools = false
describe('TabsItem', () => {
it('存在.', () => {
expect(TabsItem).to.be.exist
})
it('接受 name 属性', () => {
let Constructor = Vue.extend(TabsItem)
const vm = new Constructor({
propsData: {
name: 'xxx'
}
}).$mount()
expect(vm.$el.getAttribute('data-name')).to.eq('xxx')
})
})<file_sep>/docs/components/popover.md
---
title: Popover
---
# 弹出层组件
***
1.组件介绍
冒泡组件功能及用法如下,支持设置冒泡方向、触发形式等功能
2.使用方法
<ClientOnly>
<popover-demo></popover-demo>
</ClientOnly>
3.组件代码
```HTML
<div>
<z-popover position="bottom">
<template slot="content">
<div>popover内容</div>
</template>
<z-button>向下</z-button>
</z-popover>
<z-popover>
<template slot="content">
<div>popover内容</div>
</template>
<z-button>向上</z-button>
</z-popover>
<z-popover position="left">
<template slot="content">
<div>popover内容</div>
</template>
<z-button>向左</z-button>
</z-popover>
<z-popover position="right">
<template slot="content">
<div>popover内容</div>
</template>
<z-button>向右</z-button>
</z-popover>
<z-popover position="bottom" trigger="hover">
<template slot="content">
<div>popover内容</div>
</template>
<z-button>下浮</z-button>
</z-popover>
<z-popover trigger="hover">
<template slot="content">
<div>popover内容</div>
</template>
<z-button>上浮</z-button>
</z-popover>
<z-popover position="left" trigger="hover">
<template slot="content">
<div>popover内容</div>
</template>
<z-button>左浮</z-button>
</z-popover>
<z-popover position="right" trigger="hover">
<template slot="content">
<div>popover内容</div>
</template>
<z-button>右浮</z-button>
</z-popover>
</div>
```<file_sep>/src/toast/plugin.js
import Toast from '../toast/toast.vue'
let currentToast
export default {
install(Vue,options){
Vue.prototype.$toast = function(message,toastOptions,location){
if(currentToast){ currentToast.close() }
currentToast = createToast({
Vue,
message,
propsData:toastOptions,
location,
onClose:()=>{
currentToast = null
}
})
}
}
}
function createToast( {Vue,message,propsData,location,onClose,} ){
let Constructor = Vue.extend(Toast)
let toast = new Constructor({ propsData })
toast.$slots.default = [message]
toast.$mount()
toast.$on('close',onClose)
location.appendChild(toast.$el)
return toast
}<file_sep>/docs/components/layout.md
---
title: Layout
---
# 布局组件
***
1.组件介绍
布局组件功能及用法如下,支持常见基础布局
2.使用方法
<ClientOnly>
<layout-demo></layout-demo>
</ClientOnly>
3.组件代码
```HTML
<div>
<z-layout>
<z-header></z-header>
<z-content></z-content>
<z-footer></z-footer>
</z-layout>
<br/>
<z-layout>
<z-sider></z-sider>
<z-layout>
<z-header></z-header>
<z-content></z-content>
<z-footer></z-footer>
</z-layout>
</z-layout>
</div>
```<file_sep>/docs/components/input.md
---
title: Input
---
# 输入框
***
1.组件介绍
输入框组件功能及用法如下,支持disabled、readonly、error及双向绑定等功能
2.使用方法
<ClientOnly>
<input-demos></input-demos>
</ClientOnly>
3.组件代码
```HTML
<div>
<z-input value="张三" disabled></z-input>
<z-input value="李四" readonly></z-input>
<z-input value="王五"></z-input>
<z-input v-model="message"></z-input>
<span>message:{{message}}</span>
<z-input value="" error="姓名不能少于两个字"></z-input>
</div>
```<file_sep>/docs/install/README.md
---
title: 安装
---
# 安装
#
```
npm install z-wheel
```
或者:
```
yarn add z-wheel
```
::: danger
目前该 UI 仍然是半成品,切勿在生产环境中使用
:::<file_sep>/docs/components/collapse.md
---
title: Collapse
---
# 折叠组件
***
1.组件介绍
折页组件功能及用法如下,单页显示或多页显示等功能
2.使用方法
<ClientOnly>
<collapse-demo></collapse-demo>
</ClientOnly>
3.组件代码
```HTML
<div class="collapse-wrapper">
<z-collapse :selected.sync="currentSelected">
<z-collapse-item title="标题1" name="1">第一个内容 </z-collapse-item>
<z-collapse-item title="标题2" name="2">第二个内容 </z-collapse-item>
<z-collapse-item title="标题3" name="3">第三个内容 </z-collapse-item>
</z-collapse>
<z-collapse :selected.sync="currentSelected" single>
<z-collapse-item title="标题1" name="1">第一个内容 </z-collapse-item>
<z-collapse-item title="标题2" name="2">第二个内容 </z-collapse-item>
<z-collapse-item title="标题3" name="3">第三个内容 </z-collapse-item>
</z-collapse>
</div>
```<file_sep>/docs/components/tabs.md
---
title: Tabs
---
# 标签组件
***
1.组件介绍
标签组件功能及用法如下,支持添加icon,点击标签切换显示相应的内容
2.使用方法
<ClientOnly>
<tabs-demo></tabs-demo>
</ClientOnly>
3.组件代码
```HTML
<div>
<z-tabs selected="sports">
<z-tabs-head>
<template slot="actions">
<button>设置</button>
</template>
<z-tabs-item name="woman"> 美女 </z-tabs-item>
<z-tabs-item name="finance">财经</z-tabs-item>
<z-tabs-item name="sports">足球</z-tabs-item>
</z-tabs-head>
<z-tabs-body>
<z-tabs-pane name="woman">美女相关</z-tabs-pane>
<z-tabs-pane name="finance">财经相关</z-tabs-pane>
<z-tabs-pane name="sports">足球相关</z-tabs-pane>
</z-tabs-body>
</z-tabs>
</div>
```<file_sep>/docs/introduce/README.md
# Z-Wheel
[](https://travis-ci.org/wxx961023/z-wheel)
Wheels-ada UI 是一个好用的 UI 框架,提供了一些常用组件,适合 PC 端和移动端使用。
组件:按钮、输入框、网格、布局、Toast、Tabs、Popover、手风琴
## why Wheel
Wheel 就是轮子,这是我在学习 Vue 的过程中尝试写的一个 UI 框架(造的轮子),希望对你有用。
## 文档
[官方文档](https://wxx961023.github.io/z-wheel/)
## 联系方式
邮箱:<EMAIL>
电话:15361584160
<file_sep>/src/app.js
import Vue from 'vue';
import Button from './button/button.vue';
import Icon from './button/icon.vue';
import ButtonGroup from './button/button-group.vue';
import Input from './input/input.vue';
import Row from './grid/row.vue';
import Col from './grid/col.vue';
import Layout from './layout/layout.vue';
import Header from './layout/header.vue';
import Content from './layout/content.vue';
import Footer from './layout/footer.vue';
import Sider from './layout/sider.vue';
import Toast from './toast/toast.vue';
import Plugin from './toast/plugin.js';
import Tabs from './tabs/tabs.vue'
import TabsHead from './tabs/tabs-head'
import TabsBody from './tabs/tabs-body'
import TabsItem from './tabs/tabs-item'
import TabsPane from './tabs/tabs-pane'
import Popover from './popover/popover'
import Collapse from './collapse/collapse'
import CollapseItem from './collapse/collapse-item'
Vue.component('z-button',Button);
Vue.component('z-icon',Icon);
Vue.component('z-button-group',ButtonGroup);
Vue.component('z-input',Input);
Vue.component('z-row',Row);
Vue.component('z-col',Col);
Vue.component('z-layout',Layout);
Vue.component('z-header',Header);
Vue.component('z-content',Content);
Vue.component('z-footer',Footer);
Vue.component('z-sider',Sider);
Vue.component('z-toast',Toast);
Vue.component('z-tabs',Tabs);
Vue.component('z-tabs-head',TabsHead);
Vue.component('z-tabs-body',TabsBody);
Vue.component('z-tabs-item',TabsItem);
Vue.component('z-tabs-pane',TabsPane);
Vue.component('z-popover',Popover);
Vue.component('z-collapse',Collapse);
Vue.component('z-collapse-item',CollapseItem);
Vue.use(Plugin)
new Vue({
el:'#app',
data:{
selectedTab:['2']
},
created(){
},
methods:{
showToast(){
this.$toast('你的智商需要充值!',{
position:'top',
enableHtml:false,
closeButton:{
text:'已充值',
callback(){
console.log('1')
}
},
autoClose:3,
})
}
}
})<file_sep>/docs/components/button.md
---
title: Button
---
# 按钮
***
1.组件介绍
按钮组件功能及用法如下,支持添加icon,设置icon位置,加载状态,按钮形状等功能
2.使用方法
<ClientOnly>
<button-demos></button-demos>
</ClientOnly>
3.组件代码
```HTML
<div>
<z-button>默认按钮</z-button>
<z-button icon="settings" :loading="true">按钮</z-button>
<z-button icon="settings" icon-position="right">按钮</z-button>
<z-button icon="settings" circle :loading="toggle" @click="toggle=!toggle"></z-button>
<z-button-group>
<z-button icon="left">上一页</z-button>
<z-button>更多</z-button>
<z-button icon="right" icon-position="right">下一页</z-button>
</z-button-group>
</div>
```<file_sep>/docs/components/grid.md
---
title: Grid
---
# 网格系统
***
1.组件介绍
网格组件功能及用法如下,支持自动均分,设置单元宽度、间隔、排列方向等功能
2.使用方法
<ClientOnly>
<grid-demo></grid-demo>
</ClientOnly>
3.组件代码
```HTML
<div>
<z-row>
<z-col span="8">8</z-col>
<z-col span="16">16</z-col>
</z-row>
<br />
<z-row>
<z-col span="8">8</z-col>
<z-col span="6" offset="2">6</z-col>
<z-col span="4" offset="4">4</z-col>
</z-row>
<br />
<z-row>
<z-col span="8">8</z-col>
<z-col span="6">6</z-col>
<z-col span="4">4</z-col>
</z-row>
<br />
<z-row align="right">
<z-col span="8">8</z-col>
<z-col span="6">6</z-col>
<z-col span="4">4</z-col>
</z-row>
<br />
</div>
```<file_sep>/index.js
import Button from './src/button/button'
import ButtonGroup from './src/button/button-group';
import Icon from './src/button/icon'
export {Button,ButtonGroup,Icon}
<file_sep>/test/tabs.test.js
const expect = chai.expect;
import Tabs from '../src/tabs/tabs'
import TabsHead from '../src/tabs/tabs-head'
import TabsBody from '../src/tabs/tabs-body'
import TabsItem from '../src/tabs/tabs-item'
import TabsPane from '../src/tabs/tabs-pane'
import Vue from 'vue'
Vue.component('z-tabs', Tabs)
Vue.component('z-tabs-head', TabsHead)
Vue.component('z-tabs-body', TabsBody)
Vue.component('z-tabs-item', TabsItem)
Vue.component('z-tabs-pane', TabsPane)
Vue.config.productionTip = false
Vue.config.devtools = false
describe('Tabs', () => {
it('存在.', () => {
expect(Tabs).to.be.exist
})
it('接受selected属性', (done) => {
let div = document.createElement('div')
document.body.appendChild(div)
div.innerHTML = `
<z-tabs selected="finance">
<z-tabs-head>
<z-tabs-item name="woman" >美女</z-tabs-item>
<z-tabs-item name="finance"> 财经 </z-tabs-item>
<z-tabs-item name="sports"> 体育 </z-tabs-item>
</z-tabs-head>
<z-tabs-body>
<z-tabs-pane name="woman"> 美女相关资讯 </z-tabs-pane>
<z-tabs-pane name="finance"> 财经相关资讯 </z-tabs-pane>
<z-tabs-pane name="sports"> 体育相关资讯 </z-tabs-pane>
</z-tabs-body>
</z-tabs>
`
let vm = new Vue({
el: div
})
vm.$nextTick(() => {
let x = vm.$el.querySelector('.tabs-item[data-name="finance"]')
expect(x.classList.contains('active')).to.be.true
done()
})
})
it('可以接受 direction prop', () => {
})
})<file_sep>/README.md
# Z-Wheel - 一个 Vue UI 组件
[](https://travis-ci.org/wxx961023/z-wheel)
## 介绍
这是我在学习 Vue 过程中,做的一个 UI 框架,希望对你有用。
## 开始使用
1. CSS 样式
使用本框架,请在CSS中开启 border-box
```
*,*::before,*::after{box-sizing:border-box}
```
IE 8 及以上浏览器都支持此样式。
你还需设置默认颜色变量(后续会改为SCSS变量)
```
html{
--button-height:32px;
--font-size:14px;
--button-bg:white;
--button-active-bg:#eee;
--border-radius:4px;
--color:#333;
--border-color:#999;
--border-color-hover:#666;
}
```
IE 15 及以上浏览器都支持此样式。
2. 安装 gulu
```
npm i --save gulu
```
3. 引入
```
import {Button,ButtonGroup,Icon} from 'brazen-sec'
import 'brazen-sec/dist/index.css'
export default {
name: 'app',
components: {
'g-button':Button,
'g-icon':Icon
}
}
```
## 文档
## 提问
## 变更记录
## 联系方式
## 贡献代码
<file_sep>/docs/components/toast.md
---
title: Toast
---
# 标签组件
***
1.组件介绍
弹窗组件功能及用法如下,支持设置弹窗内容、弹窗位置、自动关闭、手动关闭、关闭回调等功能
2.使用方法
<ClientOnly>
<toast-demo></toast-demo>
</ClientOnly>
3.组件代码
```HTML
<div class="toast-wrapper" ref="wrapper">
<z-button @click="showToast1">默认顶部弹窗</z-button>
<z-button @click="showToast2">默认中间弹窗</z-button>
<z-button @click="showToast3">默认底层弹窗</z-button>
<z-button @click="showToast4">设置手动关闭</z-button>
<z-button @click="showToast5">设置关闭回调</z-button>
</div>
```
```JS
methods: {
showToast1() {
this.$toast(
'出现顶部位置自动关闭',
{ position:'top', autoClose:2},
this.$refs.wrapper
)
},
showToast2() {
this.$toast(
'出现中间位置自动关闭',
{ position:'middle',autoClose:2 },
this.$refs.wrapper
)
},
showToast3() {
this.$toast(
'出现底部位置自动关闭',
{ position:'bottom',autoClose:2},
this.$refs.wrapper
)
},
showToast4() {
this.$toast('设置手动关闭按钮',
{
autoClose:false,
},
this.$refs.wrapper
)
},
showToast5() {
this.$toast(
'设置手动关闭回调函数',
{
autoClose:false,
closeButton: { text: '关闭', callback(){ alert('弹窗被关闭了') }
}
},
this.$refs.wrapper
)
}
}
``` | fabd776b31bc21683c6dc78928cf610edee1b609 | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | wxx961023/z-wheel | 2dd9fbadb2b55b0f9f8850dac4b5560650ae2535 | 4ac34d21f3390ba2740c12768e05ea0a30496bb4 |
refs/heads/master | <repo_name>cs2r/leap_hand<file_sep>/src/Sample.py
#!/usr/bin/env python
import sys, time, os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from src.lib import Leap
import rospy, time
from geometry_msgs.msg import Vector3
class SampleListener(Leap.Listener):
finger_names = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky']
bone_names = ['Metacarpal', 'Proximal', 'Intermediate', 'Distal']
state_names = ['STATE_INVALID', 'STATE_START', 'STATE_UPDATE', 'STATE_END']
def on_init(self, controller):
print "Initialized"
rospy.init_node("leap_motion_publisher")
self.palm_dir_pub = rospy.Publisher('palm_direction', Vector3 , queue_size=10)
self.thumb_dir_pub = rospy.Publisher('thumb_direction', Vector3, queue_size=10)
self.index_dir_pub = rospy.Publisher('index_direction', Vector3, queue_size=10)
self.middle_dir_pub = rospy.Publisher('middle_direction', Vector3, queue_size=10)
self.ring_dir_pub = rospy.Publisher('ring_direction', Vector3, queue_size=10)
self.pinky_dir_pub = rospy.Publisher('pinky_direction', Vector3, queue_size=10)
def on_connect(self, controller):
print "Connected"
def on_disconnect(self, controller):
# Note: not dispatched when running in a debugger.
print "Disconnected"
def on_exit(self, controller):
print "Exited"
def on_frame(self, controller):
# Get the most recent frame and report some basic information
frame = controller.frame()
for hand in frame.hands:
if ~hand.is_left:
normal = hand.palm_normal
direction = hand.direction
arm = hand.arm
palm_dir = Vector3()
palm_dir.x = direction.pitch - arm.direction[1]
palm_dir.y = normal.roll
palm_dir.z = direction.yaw - arm.direction[0]
self.palm_dir_pub.publish(palm_dir)
# Get fingers
finger_dir = Vector3()
for finger in hand.fingers:
if finger.type == 0: #thumb
finger_dir.x = finger.bone(3).direction[0] - finger.bone(2).direction[0]
finger_dir.y = finger.bone(1).direction[1] - normal.roll
print finger_dir.y
self.thumb_dir_pub.publish(finger_dir)
elif finger.type == 1: #index
dire = finger.bone(1).direction - finger.bone(0).direction
finger_dir.x = dire[0]
finger_dir.y = dire[1]
finger_dir.z = dire[2]
self.index_dir_pub.publish(finger_dir)
elif finger.type == 2: #middle
dire = finger.bone(1).direction - finger.bone(0).direction
finger_dir.x = dire[0]
finger_dir.y = dire[1]
finger_dir.z = dire[2]
self.middle_dir_pub.publish(finger_dir)
elif finger.type == 3: # ring
dire = finger.bone(1).direction - finger.bone(0).direction
finger_dir.x = dire[0]
finger_dir.y = dire[1]
finger_dir.z = dire[2]
self.ring_dir_pub.publish(finger_dir)
elif finger.type == 4: # pinky
dire = finger.bone(1).direction - finger.bone(0).direction
finger_dir.x = dire[0]
finger_dir.y = dire[1]
finger_dir.z = dire[2]
self.pinky_dir_pub.publish(finger_dir)
time.sleep(0.1)
if not (frame.hands.is_empty and frame.gestures().is_empty):
print "NO Hand on field of view"
def state_string(self, state):
if state == Leap.Gesture.STATE_START:
return "STATE_START"
if state == Leap.Gesture.STATE_UPDATE:
return "STATE_UPDATE"
if state == Leap.Gesture.STATE_STOP:
return "STATE_STOP"
if state == Leap.Gesture.STATE_INVALID:
return "STATE_INVALID"
def main():
# Create a sample listener and controller
listener = SampleListener()
controller = Leap.Controller()
# Have the sample listener receive events from the controller
controller.add_listener(listener)
# Keep this process running until Enter is pressed
print "Press Enter to quit..."
try:
sys.stdin.readline()
except KeyboardInterrupt:
pass
finally:
# Remove the sample listener when done
controller.remove_listener(listener)
if __name__ == "__main__":
main()
<file_sep>/src/hand_ctrl.py
#!/usr/bin/env python
import rospy, math, time
from geometry_msgs.msg import Vector3
from std_msgs.msg import Int16
class Leap_ctrl():
def map(self, x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def get_palm (self, data):
#print data
w_v = self.map(data.z, 0.8, -0.4, 100, 200)
self.w_v.publish(w_v)
w_h = self.map(data.x, 0.9, -0.9, 100, 250)
self.w_h.publish(w_h)
def get_thumb (self, data):
#print data
thumb = self.map(data.x, -0.7, 0.2, 100, 300)
self.thumb.publish(thumb)
thumb_j = self.map(data.y, -0.2, 0.5, 100, 300)
self.thumb_j.publish(thumb_j)
def get_index (self, data):
#print data
index = self.map(data.y, -0.3, 1.1, 100, 300)
self.index.publish(index)
def get_middle (self, data):
#print data
middle = self.map(data.y, -0.3, 0.9, 100, 300)
self.middle.publish(middle)
def get_ring (self, data):
#print data
ring = self.map(data.y, -0.3, 0.9, 100, 300)
self.ring.publish(ring)
def get_pinky (self, data):
#print data
pinky = self.map(data.y, -0.3, 0.9, 100, 300)
self.pinky.publish(pinky)
def __init__(self):
rospy.init_node("hand_ctrl")
rospy.Subscriber("palm_direction", Vector3, self.get_palm)
rospy.Subscriber("thumb_direction", Vector3, self.get_thumb)
rospy.Subscriber("index_direction", Vector3, self.get_index)
rospy.Subscriber("middle_direction", Vector3, self.get_middle)
rospy.Subscriber("ring_direction", Vector3, self.get_ring)
rospy.Subscriber("pinky_direction", Vector3, self.get_pinky)
self.w_v = rospy.Publisher("servo/L5", Int16, queue_size=10)
self.w_h = rospy.Publisher("servo/L6", Int16, queue_size=10)
self.thumb = rospy.Publisher("servo/L3", Int16, queue_size=10)
self.thumb_j = rospy.Publisher("servo/L7", Int16, queue_size=10)
self.index = rospy.Publisher("servo/L2", Int16, queue_size=10)
self.middle = rospy.Publisher("servo/L1", Int16, queue_size=10)
self.ring = rospy.Publisher("servo/L9", Int16, queue_size=10)
self.pinky = rospy.Publisher("servo/L8", Int16, queue_size=10)
print "leap hand is Ready"
rospy.spin()
if __name__ == "__main__":
leap_ctrl = Leap_ctrl()
| 2c0c4f8346172ebe643a6330bccac82f91939083 | [
"Python"
] | 2 | Python | cs2r/leap_hand | 9a8a805edcc2afdecea8f98bd58295379b33cd76 | 8bff2ef387125869a17bfa5e120636f39de2a69c |
refs/heads/master | <file_sep>#!/bin/sh
# make data directory (you can replace with symbolic link to elsewhere)
test -e data || mkdir data
# install matplotlib & numpy
sudo apt-get install python-matplotlib
sudo apt-get install python-numpy
# install install Python Twitter Tools
sudo easy_install twitter
<file_sep>#!/usr/bin/python
import time
import twitter # Python Twitter Tools (not the homonymous Python-Twitter)
import sqlite3
from matplotlib import pyplot
import main
def TODO (message = None): raise NotImplementedError(message)
def zero_if_none (x):
if x is None: return 0
else: return x
def null_if_none (x):
if x is None: return ''
else: return x
search = twitter.Twitter(domain='search.twitter.com').search
class CachedSearcher:
def __init__ (self, database = '/data/sna/bands.db'):
self.twitter_search = twitter.Twitter(domain='search.twitter.com').search
self.db = sqlite3.connect(database)
self.db_cursor = self.db.cursor()
self.init_db()
def init_db (self):
tables = [ row[0] for row in self.db_cursor.execute(
'''
select name
from sqlite_master
where type = 'table'
order by name
''',
)]
if 'searches' not in tables:
self.db_cursor.execute(
'''
create table searches (query text, latest_id long)
''')
if 'search_results' not in tables:
self.db_cursor.execute(
'''
create table search_results (query text, tweet_id long)
''')
if 'tweets' not in tables:
self.db_cursor.execute(
'''
create table tweets (
tweet_id long,
from_user_id long,
to_user_id long,
geo text,
created_at text,
text text)
''')
def get_latest_id (self, query):
rows = list(self.db_cursor.execute(
'''
select latest_id from searches where query=(?)
''',
(query,)))
if rows:
return rows[0][0]
else:
self.db_cursor.execute(
'''
insert into searches (query, latest_id) values (?, 0)
''',
(query,))
return 0
def add_new_results (self, query):
since_id = self.get_latest_id(query)
old_since_id = since_id
tweets = []
for page_num in range(1,150):
page = self.twitter_search(
q = query,
tweet_type = 'recent',
with_twitter_user_id = True,
page = page_num,
since_id = old_since_id,
)
new_tweets = page['results']
if new_tweets:
tweets += new_tweets
since_id = max(since_id, page['max_id'])
else:
break
if tweets:
self.db_cursor.execute(
'''
update searches set latest_id = (?) where query = (?)
''',
(since_id, query))
tweets_data = [
( tweet['id'],
zero_if_none(tweet['from_user_id']),
zero_if_none(tweet['to_user_id']),
'', # TODO remove geo column
tweet['created_at'],
tweet['text'])
for tweet in tweets ]
self.db_cursor.executemany(
'''
insert into tweets
(tweet_id, from_user_id, to_user_id, geo, created_at, text)
values (?,?,?,?,?,?)
''',
tweets_data)
self.db_cursor.executemany(
'''
insert into search_results (query, tweet_id) values (?,?)
''',
[ (query, tweet['id']) for tweet in tweets ])
self.db.commit()
return len(tweets)
def search (self, query):
self.add_new_results(query)
# return new + old results
results = list(self.db_cursor.execute(
'''
select
tweets.tweet_id,
tweets.from_user_id,
tweets.to_user_id,
tweets.geo,
tweets.created_at,
tweets.text
from search_results join tweets
on search_results.tweet_id = tweets.tweet_id
where query = (?)
order by tweets.tweet_id
''',
(query,)))
if main.at_top():
for result in results:
text = results[-1]
print '\n%s' % text
else:
return results
def update_db (self):
queries = list(self.db_cursor.execute('select query from searches'))
print time.asctime()
for row in queries:
query = row[0]
num_tweets = self.add_new_results(query)
print 'added %i new tweets about %r' % (num_tweets, query)
def get_queries (self):
queries = list(self.db_cursor.execute(
'select count(*),query from search_results group by query'))
queries.sort()
queries.reverse()
return queries
#----( commands )-------------------------------------------------------------
searcher = CachedSearcher()
@main.command
def search (query):
'searches twitter & caches result in local database'
print query
results = searcher.search(query)
if main.at_top():
for t in results:
print '-' * 80
print t
print '\nsearch returned %i results' % len(results)
else:
return results
@main.command
def update ():
'updates all search terms'
searcher.update_db()
@main.command
def queries ():
'lists cached queries'
print 'cached queries:'
for row in searcher.get_queries():
print ' %d\t%s' % row
if __name__ == '__main__': main.main()
| 955a2a09c5a89821a4729e7707e87222cdfd220b | [
"Python",
"Shell"
] | 2 | Shell | fritzo/sna | 3ffc1783bfea409c9d3fc5bdad6901b83f376b5e | fa77e1acbe82ba80f394cfb4fbf9ce3e6e19a443 |
refs/heads/master | <file_sep>
import logging
logger = logging.getLogger('quiz_webhook')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
file_handler = logging.FileHandler('quiz_webhook.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)
#logger.addHandler(mail_handler)
logger.addHandler(file_handler)
logger.setLevel(logging.WARNING)
logger.info('Starting...')
<file_sep>""""
Send emails using SES. SES Credentials must be stored in ~/.aws/credentials.
"""
import boto3
from botocore.exceptions import ClientError
def send_simple_email(recipient, subject, contents, sender="506 Investor Group <<EMAIL>>"):
""" Send a very simple email. Not currently used. """
SENDER = sender
RECIPIENT = recipient
AWS_REGION = "us-west-2"
SUBJECT = subject
BODY_TEXT = ("")
BODY_HTML = contents
CHARSET = "UTF-8"
client = boto3.client('ses', region_name=AWS_REGION)
try:
response = client.send_email(
Destination={
'ToAddresses': [
RECIPIENT,
],
},
Message={
'Body': {
'Html': {
'Charset': CHARSET,
'Data': BODY_HTML,
},
'Text': {
'Charset': CHARSET,
'Data': BODY_TEXT,
},
},
'Subject': {
'Charset': CHARSET,
'Data': SUBJECT,
},
},
Source=SENDER,
)
# Display an error if something goes wrong.
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message ID:"),
print(response['MessageId'])
if __name__ == '__main__':
send_simple_email('<EMAIL>', 'test from ses.py', 'this is a test')
<file_sep>"""
Demote all TL1 users to TL0. They will no longer be able to post until they
take the quiz. Send them a notification of explanation.
Can't run this until pydiscourse is fixed (although this is hanging in the
request rather than returning Payload Too Big, but it must be the same issue.)
v1.1.1 has delete_group_member and add_group_member. How is this related to
trust levels?
Never finished this as we decided not to demote users, but I found the way to
do it, by reverse-engineering and pushing the button to do it manually. In
Chrome, at least, be sure to check the box *not to clear the network traffic
on reload.
"""
from time import time, sleep
from client506 import MyDiscourseClient, create_client
from log import logger
def demote():
client = create_client()
tl1_users = client.members_of_group('trust_level_1')
for user in tl1_users:
try:
print 'adding user details for ', user['username']
client.add_user_details(user)
print user
sleep(5)
except Exception, exc:
print 'failed to get details or update user: ', exc
logger.exception('Users failed')
sleep(3600)
if __name__ == '__main__':
demote()
<file_sep>"""
A flask server to handle webhooks from Typeform. This is similar to the general
forms webhook which adds users to a group if they self-certify. I've made a copy
for this application because it's a little different- for example it might be
different to determine whether they've passed the test, and it will take a
different action- unlock their trust level and add them to the passed_quiz group.
"""
from flask import Flask, render_template, flash, request
import logging
import json
from pprint import pprint, pformat
from client506 import create_client
from ses import send_simple_email
from pydiscourse.exceptions import (
DiscourseClientError
)
recipients = ['<EMAIL>',]
logger = logging.getLogger('quiz_webhook')
file_handler = logging.FileHandler('quiz_webhook.log')
file_handler.setLevel(logging.INFO)
logger.addHandler(file_handler)
logger.info('running quiz web hook server.py')
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '<KEY>'
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
class RequestHandler:
def __init__(self, data):
self.client = create_client(1)
self.data = data
self.answers = self.data['form_response']['answers']
self.score = self.data['form_response']['calculated']['score']
self.username = self.data['form_response']['hidden']['username']
self.user = self.client.user(self.username)
pprint(self.data)
def user_is_in_group(self, group_name, username):
members = self.client.members_of_group(group_name)
membernames = [x['username'] for x in members]
return username in membernames
def add_to_group(self, group_name, username):
group = self.client.my_group(group_name)
self.client.add_group_members(group['id'], [username, ])
def process(self):
# just the fact that we're here is enough if we keep circle-back logic
passed = True
if passed:
# Unlock them from TL0. Discourse will recognize this soon and will promote them to TL1.
# See https://meta.discourse.org/t/understanding-discourse-trust-levels/90752/61
# Actually it seems to recognize immediately?
self.client.trust_level_lock(self.user['id'], False)
group_name = 'passed_quiz'
try:
self.add_to_group(group_name, self.username)
subject = 'User was added to %s' % group_name
s = '%s was added to the group %s because they passed the quiz.' % (self.username, group_name)
except DiscourseClientError, exc:
subject = 'User could not be added to %s' % group_name
s = '%s could not be added to the group %s. Maybe they are already a member?' % (self.username, group_name)
s += '<br>'
url = 'https://forum.506investorgroup.com/g/%s' % group_name
s += 'To change this, visit the %s group settings at ' % group_name
s += url
s += '.'
for recipient in recipients:
send_simple_email(recipient, subject, s)
print 'sent email'
"""
Thurs pm this almost worked. Unlocked JohnDoe and it seemed to immediately promote him
to TL1, so that's a bonus if they don't have to wait a day. However it couldn't add him
to eh paassed_quiz group. I did get an email. ok the group name was wrong. fixed.
need to fix the quiz (dunderhead pic is wrong). And send a
notification from here? No- there's not a way in client and not worth it.
So the dunderhead pic is the only thing.
"""
@app.route('/quiz_complete', methods=['POST'])
def quiz_complete_handler():
if request.method == 'POST':
print 'quiz is complete: '
data = request.json
q = RequestHandler(data)
q.process()
return '', 200
else:
return '', 400
@app.route('/user_event', methods=['POST'])
def user_event_handler():
# Currently we're only interested in user_created. Other webhooks are available,
# for users, topics, and posts. (However not for user_added_to_group). See
# https://meta.discourse.org/t/setting-up-webhooks/49045.
headers = request.headers
pprint(headers)
event = request.headers['X-Discourse-Event']
print 'event: ', event
if event == 'user_created':
print 'user was created'
data = request.json
pprint(data)
send_simple_email('<EMAIL>', 'User Created', 'no text yet...')
user = request.json['user']
user_id = user['id']
email = user['email']
username = user['username']
msg = '%d %s %s' % (user_id, username, email)
send_simple_email('<EMAIL>', 'User Created, interpreted', msg)
client = create_client(1)
client.trust_level_lock(user_id, True)
send_simple_email('<EMAIL>', 'User Locked', msg)
return '', 200
else:
return '', 400
if __name__ == "__main__":
# Digests use 8081, forms use 8082, tracking_pixel and resourse server use 8083,
# not sure if either of those two on 8083 are running; run this on 8084 (it's open).
app.run(host="0.0.0.0", port=8084, debug=True, threaded=True)
| 5b8d3dae142c4c2d4942b1f13997afa74d8878bf | [
"Python"
] | 4 | Python | markschmucker/quiz | c7e1c3413458538e09cb57b17f72c0e83137e53d | 651a0a1f1f8e91748fea8c80971e530898c865a4 |
refs/heads/master | <file_sep># Java-Motorcycle_system
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Mar 16, 2020 at 08:12 AM
-- Server version: 5.7.15-log
-- PHP Version: 5.6.26
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `sadb`
--
-- --------------------------------------------------------
--
-- Table structure for table `customer`
--
CREATE TABLE `customer` (
`Cus_id` int(50) NOT NULL,
`Cus_name` varchar(50) NOT NULL,
`Address` varchar(100) NOT NULL,
`Phone` int(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `customer`
--
INSERT INTO `customer` (`Cus_id`, `Cus_name`, `Address`, `Phone`) VALUES
(1, 'ฟร้อง', '42/1 ม. 2 ต.โรงเข้ จ. สมุทรสาคร', 630855581),
(2, 'ออม', 'fsfsdfsd', 897450903),
(3, 'เจเจ', 'ม.เกษตร', 950391249),
(4, 'กัส', 'KU', 123456789),
(5, 'luffy', 'geta311', 852286366),
(6, 'แดง', 'TEST', 123),
(7, 'TEST', 'TEST', 1150),
(8, 'เก่ง', 'สะพานลอย', 987654321),
(9, 'เฟริน', 'GETA 311', 39);
-- --------------------------------------------------------
--
-- Table structure for table `login`
--
CREATE TABLE `login` (
`Log_id` int(50) NOT NULL,
`Log_name` varchar(50) NOT NULL,
`Username` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`Status` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `login`
--
INSERT INTO `login` (`Log_id`, `Log_name`, `Username`, `Password`, `Status`) VALUES
(1, 'Employee1', 'em', '1234', 'Admin'),
(2, 'frongz', 'fz', '1234', 'CEO'),
(3, 'Employee2', 'em2', '1234', 'Admin'),
(4, 'Employee3', 'em3', '1234', 'Admin'),
(5, 'Employee3', 'em3', '1234', 'CEO'),
(6, '', '', '', 'Admin');
-- --------------------------------------------------------
--
-- Table structure for table `orders`
--
CREATE TABLE `orders` (
`Order_id` int(50) NOT NULL,
`CategoryID` int(50) NOT NULL,
`ProductName` varchar(50) NOT NULL,
`Price` int(50) NOT NULL,
`Quantity` int(50) NOT NULL,
`Total` int(50) NOT NULL,
`Date` date NOT NULL,
`Cus_id` int(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `orders`
--
INSERT INTO `orders` (`Order_id`, `CategoryID`, `ProductName`, `Price`, `Quantity`, `Total`, `Date`, `Cus_id`) VALUES
(11, 1, 'ไส้กรองอากาศ', 300, 1, 300, '2563-02-09', 1),
(14, 2, 'ชุดเปลือกรถ', 1500, 2, 3000, '2563-02-01', 1),
(16, 2, 'ชุดเปลือกรถ', 1500, 2, 3000, '2563-03-01', 1),
(18, 2, 'ท่อ', 1000, 1, 1000, '2563-01-01', 1),
(20, 3, 'สายไฟ', 20, 3, 60, '2563-07-01', 4),
(22, 3, 'ไฟหน้า', 80, 1, 80, '2563-05-01', 4),
(23, 1, 'หัวเทียน', 100, 3, 300, '2563-04-01', 4),
(24, 1, 'คาร์บูเรเตอร์', 1550, 33, 51150, '2563-04-01', 4),
(25, 1, 'เฟืองทด', 20, 2, 40, '2563-05-01', 1),
(38, 2, 'มือเบรก', 550, 1, 550, '2563-06-09', 1),
(40, 2, 'ปั้มเบรกบน', 500, 2, 1000, '2563-02-15', 4),
(42, 4, 'หมวกกันน็อค', 500, 2, 1000, '2563-07-08', 1),
(43, 1, 'เฟืองทด', 20, 1, 20, '2563-02-22', 4),
(48, 4, 'หมวกกันน็อค', 500, 2, 1000, '2563-02-08', 2),
(50, 4, 'หมวกกันน็อค', 500, 2, 1000, '2563-08-04', 2),
(54, 3, 'สายไฟ', 20, 1, 20, '2562-02-06', 4),
(55, 4, 'หมวกกันน็อค', 500, 2, 1000, '2562-02-06', 4),
(56, 4, 'หมวกกันน็อค', 500, 2, 1000, '2562-02-06', 2),
(57, 4, 'แฮนแต่ง', 500, 1, 500, '2562-02-06', 2),
(58, 1, 'ก้านลูกสูบ', 50, 1, 50, '2563-02-25', 4),
(59, 3, 'สายไฟ', 20, 1, 20, '2563-02-25', 4),
(61, 2, 'มือเบรก', 550, 1, 550, '2563-08-04', 1),
(64, 4, 'แฮนแต่ง', 500, 2, 1000, '2563-09-10', 1),
(68, 2, 'โช็คหลัง', 2000, 3, 6000, '2563-02-09', 4),
(71, 1, 'หัวเทียน', 100, 3, 300, '2563-12-08', 4),
(73, 4, 'หมวกกันน็อค', 500, 2, 1000, '2563-12-08', 4),
(74, 1, 'คาร์บูเรเตอร์', 1550, 33, 51150, '2563-02-26', 4),
(77, 3, 'สายไฟ', 20, 1, 20, '2563-02-26', 2),
(78, 1, 'หัวเทียน', 100, 3, 300, '2563-02-03', 4),
(79, 3, 'สายไฟ', 20, 3, 60, '2563-02-03', 4),
(81, 4, 'หมวกกันน็อค', 500, 2, 1000, '2563-02-22', 4),
(82, 1, 'หัวเทียน', 100, 3, 300, '2563-07-10', 2),
(84, 1, 'คาร์บูเรเตอร์', 1550, 33, 51150, '2563-09-14', 2),
(85, 3, 'ไฟซีนอล', 500, 2, 1000, '2563-09-14', 2),
(86, 1, 'ไส้กรองอากาศ', 300, 1, 300, '2563-05-16', 2),
(87, 2, 'โช็คหลัง', 2000, 3, 6000, '2563-05-16', 2),
(88, 1, 'หัวเทียน', 100, 3, 300, '2563-05-17', 2),
(89, 2, 'ชุดเปลือกรถ', 1500, 2, 3000, '2563-05-17', 2),
(92, 3, 'สายไฟ', 20, 1, 20, '2563-08-12', 4),
(93, 1, 'หัวเทียน', 100, 3, 300, '2563-12-01', 2),
(94, 1, 'ชุดข้างรถ 4 จังหวะ', 800, 3, 2400, '2563-12-01', 2),
(97, 3, 'สายไฟ', 20, 2, 40, '2563-12-01', 1),
(99, 3, 'สายถัก', 100, 5, 500, '2563-05-14', 1),
(100, 3, 'สวิตไฟ', 100, 4, 400, '2563-05-14', 1),
(101, 3, 'ไฟหน้า', 80, 1, 80, '2563-02-28', 3),
(102, 3, 'ไฟหลัง', 20, 1, 20, '2563-02-28', 3),
(103, 4, 'ตะกร้า', 500, 1, 500, '2563-02-28', 3),
(104, 1, 'หัวเทียน', 100, 3, 300, '2563-06-04', 4),
(105, 2, 'กันร้อนข้างท่อ', 350, 3, 1050, '2563-06-04', 4),
(106, 1, 'หัวเทียน', 100, 3, 300, '2563-01-02', 4),
(107, 1, 'ชุดข้างรถ 4 จังหวะ', 800, 1, 800, '2563-01-01', 4),
(108, 3, 'สายถัก', 100, 5, 500, '2563-01-01', 4),
(110, 1, 'ชุดข้างรถ 4 จังหวะ', 800, 2, 1600, '2563-01-03', 4),
(111, 1, 'หัวเทียน', 100, 3, 300, '2562-01-01', 1),
(112, 2, 'โช็คหลัง', 2000, 1, 2000, '2563-02-28', 5),
(115, 2, 'กันร้อนข้างท่อ', 350, 3, 1050, '2563-02-20', 5),
(116, 1, 'หัวเทียน', 100, 3, 300, '2563-02-10', 1),
(117, 2, 'ท่อ', 1000, 3, 3000, '2563-02-10', 1),
(118, 1, 'คาร์บูเรเตอร์', 1550, 33, 51150, '2563-02-02', 1),
(119, 1, 'หัวเทียน', 100, 3, 300, '2563-02-07', 2),
(121, 3, 'ไฟหน้า', 80, 4, 320, '2563-02-28', 5),
(122, 2, 'กันร้อนข้างท่อ', 350, 3, 1050, '2563-05-10', 1),
(123, 1, 'ไส้กรองอากาศ', 300, 1, 300, '2563-07-09', 1),
(124, 2, 'กันร้อนข้างท่อ', 350, 3, 1050, '2563-07-09', 1),
(125, 1, 'ไส้กรองอากาศ', 300, 1, 300, '2563-12-09', 4),
(127, 4, 'เบาะแต่ง', 1000, 1, 1000, '2563-12-09', 4),
(128, 4, 'ผ้าคลุมรถ', 300, 2, 600, '2563-12-08', 4),
(129, 4, 'แฮนแต่ง', 500, 1, 500, '2563-12-08', 4),
(130, 4, 'ตะกร้า', 500, 2, 1000, '2563-11-01', 2),
(131, 2, 'ท่อ', 1000, 1, 1000, '2563-11-01', 2),
(132, 1, 'ไส้กรองอากาศ', 300, 1, 300, '2563-06-08', 4),
(133, 1, 'หัวเทียน', 100, 3, 300, '2563-03-01', 6),
(134, 2, 'กันร้อนข้างท่อ', 350, 3, 1050, '2563-03-01', 6),
(135, 1, 'หัวเทียน', 100, 1, 100, '2563-03-02', 6),
(136, 1, 'ชุดข้างรถ 4 จังหวะ', 800, 2, 1600, '2563-03-02', 6),
(137, 4, 'ตะกร้า', 500, 1, 500, '2563-03-03', 6),
(138, 2, 'คอท่อสแตนเลส', 800, 2, 1600, '2563-03-03', 6),
(139, 1, 'ชุดข้างรถ 4 จังหวะ', 800, 1, 800, '2563-03-03', 6),
(140, 2, 'กันร้อนข้างท่อ', 350, 2, 700, '2563-03-03', 6),
(141, 2, 'คอท่อสแตนเลส', 800, 2, 1600, '2563-03-04', 6),
(142, 2, 'กันร้อนข้างท่อ', 350, 1, 350, '2563-03-04', 6),
(143, 1, 'ไส้กรองอากาศ', 300, 1, 300, '2563-03-06', 6),
(145, 2, 'แฮนด์', 150, 10, 1500, '2563-03-06', 6),
(146, 3, 'ไฟเลี่ยวแต่ง', 600, 2, 1200, '2563-03-06', 6),
(147, 3, 'สวิตไฟ', 100, 3, 300, '2563-03-06', 6),
(148, 4, 'น็อตสแตนเลส', 20, 3, 60, '2563-03-06', 6),
(149, 1, 'หัวเทียน', 100, 1, 100, '2563-03-12', 6),
(150, 1, 'ก้านลูกสูบ', 50, 2, 100, '2563-03-12', 6),
(151, 3, 'ไฟกระพริบ LED', 295, 1, 295, '2563-03-12', 6),
(153, 1, 'หัวเทียน', 100, 2, 200, '2563-03-19', 6),
(154, 1, 'น็อตเครื่อง', 20, 11, 220, '2563-03-19', 6),
(155, 3, 'ไฟกระพริบ LED', 295, 1, 295, '2563-03-19', 6),
(156, 2, 'คอท่อสแตนเลส', 800, 1, 800, '2563-03-19', 6),
(157, 2, 'กระจกส่องหลัง', 420, 2, 840, '2563-03-21', 6),
(158, 2, 'ท่อ', 1000, 1, 1000, '2563-03-21', 6),
(159, 4, 'หมวกกันน็อค', 500, 1, 500, '2563-03-21', 6),
(160, 1, 'ไส้กรองอากาศ', 300, 1, 300, '2563-03-22', 6),
(161, 1, 'ลูกสูบ', 300, 2, 600, '2563-03-22', 6),
(162, 1, 'ชุดข้างรถ 4 จังหวะ', 800, 2, 1600, '2563-03-16', 6),
(163, 1, 'ลูกสูบ', 300, 1, 300, '2563-03-16', 6),
(164, 1, 'ไส้กรองอากาศ', 300, 2, 600, '2563-03-16', 6),
(165, 1, 'ไส้กรองอากาศ', 300, 1, 300, '2563-03-26', 6),
(166, 1, 'คาร์บูเรเตอร์', 1550, 33, 51150, '2563-03-26', 6),
(167, 1, 'เฟืองทด', 20, 1, 20, '2563-03-26', 6),
(168, 2, 'กันร้อนข้างท่อ', 350, 1, 350, '2563-03-31', 6),
(169, 2, 'คอท่อสแตนเลส', 800, 1, 800, '2563-03-31', 6),
(170, 2, 'กระจกส่องหลัง', 420, 1, 420, '2563-03-31', 6),
(171, 2, 'เข็มน้ำมันแยก', 600, 1, 600, '2563-03-31', 6),
(172, 2, 'เรือนไมล์', 775, 1, 775, '2563-03-31', 6),
(173, 3, 'ไฟหน้า ', 80, 2, 160, '2563-03-30', 6),
(174, 3, 'ไฟหลัง ', 20, 1, 20, '2563-03-30', 6),
(175, 1, 'คาร์บูเรเตอร์', 1550, 33, 51150, '2563-03-30', 6),
(176, 1, 'ลูกสูบ 53 cm ', 300, 1, 300, '2563-03-30', 6),
(178, 1, 'ปั้มหัวฉีด ', 500, 1, 500, '2563-03-01', 1),
(179, 1, 'ไส้กรองอากาศ', 300, 2, 600, '2563-03-01', 1),
(180, 1, 'เฟืองทด ', 20, 1, 20, '2563-03-01', 1),
(181, 2, 'ท่อพร้อมคอท่อ', 1000, 2, 2000, '2563-03-01', 1),
(182, 3, 'สวิตไฟ ', 100, 1, 100, '2563-03-01', 1),
(183, 3, 'สายไฟ ', 20, 2, 40, '2563-03-01', 1),
(184, 3, 'สายถัก ', 100, 5, 500, '2563-03-01', 1),
(186, 1, 'ปั้มหัวฉีด ', 500, 1, 500, '2563-08-02', 6),
(187, 1, 'ไส้กรองอากาศ', 300, 2, 600, '2563-08-02', 6),
(188, 1, 'หัวเทียนขนาดเล็ก', 100, 3, 300, '2563-08-02', 6),
(189, 1, 'หัวเทียนขนาดเล็ก', 100, 2, 200, '2563-08-02', 6),
(190, 1, 'คาร์บูเรเตอร์ ', 1550, 33, 51150, '2563-08-02', 6),
(191, 1, 'ชุดข้างรถ 4 จังหวะ', 800, 2, 1600, '2563-08-02', 6),
(192, 1, 'ลูกสูบ 53 cm ', 300, 1, 300, '2563-08-02', 6),
(193, 1, 'เฟืองทด ', 20, 2, 40, '2563-08-02', 6),
(194, 1, 'โซ่ราวลิ้น ', 800, 1, 800, '2563-08-02', 6),
(196, 1, 'ก้านลูกสูบ ', 50, 1, 50, '2563-08-02', 6),
(197, 1, 'น็อตเครื่อง ', 20, 2, 40, '2563-08-02', 6),
(198, 2, 'กันร้อนข้างท่อ', 350, 1, 350, '2563-08-02', 6),
(199, 2, 'ชุดเปลือกรถ ', 1500, 2, 3000, '2563-08-03', 6),
(200, 2, 'มือเบรก ', 550, 2, 1100, '2563-08-03', 6),
(201, 2, 'โช็คหลัง ', 2000, 1, 2000, '2563-08-03', 6),
(202, 2, 'เบรกหน้า ', 800, 2, 1600, '2563-08-03', 6),
(203, 2, 'ปั้มเบรกบน ', 500, 1, 500, '2563-08-03', 6),
(204, 2, 'แฮนด์ ', 150, 2, 300, '2563-08-03', 6),
(205, 2, 'คอท่อสแตนเลส', 800, 1, 800, '2563-08-03', 6),
(206, 2, 'กระจกส่องหลัง', 420, 2, 840, '2563-08-03', 6),
(207, 2, 'เรือนไมล์ ', 775, 1, 775, '2563-08-03', 6),
(208, 2, 'เข็มน้ำมันแยก', 600, 2, 1200, '2563-08-03', 6),
(209, 3, 'ไฟหน้า ', 80, 1, 80, '2563-06-03', 6),
(210, 3, 'ไฟหลัง ', 20, 2, 40, '2563-06-03', 6),
(211, 3, 'สายไฟ ', 20, 1, 20, '2563-06-03', 6),
(212, 3, 'สายถัก ', 100, 5, 500, '2563-06-03', 6),
(213, 3, 'ไฟซีนอล ', 500, 1, 500, '2563-06-03', 6),
(214, 3, 'ไฟเลี่ยวแต่ง ', 600, 2, 1200, '2563-06-03', 6),
(215, 3, 'สวิตไฟ ', 100, 1, 100, '2563-06-03', 6),
(216, 3, 'ไฟแต่ง LED ', 750, 2, 1500, '2563-06-03', 6),
(217, 3, 'ไฟกระพริบ LED', 295, 1, 295, '2563-06-03', 6),
(218, 3, 'ไฟติดข้างรถ', 50, 2, 100, '2563-06-03', 6),
(219, 3, 'ไฟดีเลย์ ', 200, 1, 200, '2563-06-03', 6),
(220, 4, 'ตะกร้า ', 500, 2, 1000, '2563-06-03', 6),
(222, 4, 'ผ้าคลุมรถ ', 300, 2, 600, '2563-06-03', 6),
(223, 4, 'หมวกกันน็อค ', 500, 1, 500, '2563-06-03', 6),
(224, 4, 'แฮนแต่ง ', 500, 2, 1000, '2563-06-03', 6),
(225, 4, 'เบาะแต่ง ', 1000, 1, 1000, '2563-06-03', 6),
(227, 4, 'ดุมกลึง ', 1500, 1, 1500, '2563-06-03', 6),
(228, 4, 'ล้ออลูมิเนียม ', 500, 2, 1000, '2563-06-03', 6),
(229, 4, 'ล้อแมกซ์ ', 2000, 1, 2000, '2563-06-03', 6),
(230, 4, 'พักเท้าแต่ง ', 60, 2, 120, '2563-06-03', 6),
(231, 4, 'น็อตสแตนเลส', 20, 1, 20, '2563-06-03', 6),
(232, 4, 'กระจกแต่ง ', 500, 2, 1000, '2563-06-03', 6),
(233, 4, 'ตัวเกี่ยวของ ', 50, 1, 50, '2563-06-03', 6),
(234, 3, 'สายไฟ ', 20, 0, 0, '2563-06-04', 6),
(235, 3, 'สายถัก ', 100, 5, 500, '2563-06-04', 6),
(236, 3, 'ไฟติดข้างรถ ', 50, 2, 100, '2563-06-04', 6),
(237, 1, 'เฟืองทด ', 20, 1, 20, '2563-03-02', 7),
(238, 1, 'หัวเทียนขนาดเล็ก', 100, 2, 200, '2563-03-02', 7),
(239, 3, 'สายถัก ', 100, 5, 500, '2563-03-02', 7),
(240, 2, 'ชุดเปลือกรถ ', 1500, 4, 6000, '2563-03-02', 7),
(242, 1, 'คาร์บูเรเตอร์ ', 1550, 33, 51150, '2563-03-02', 8),
(243, 2, 'ท่อพร้อมคอท่อ', 1000, 1, 1000, '2563-03-02', 8),
(244, 3, 'ไฟหลัง ', 20, 2, 40, '2563-03-02', 8),
(247, 2, 'ท่อพร้อมคอท่อ', 1000, 1, 1000, '2563-03-06', 9),
(248, 3, 'ไฟแต่ง LED ', 750, 3, 2250, '2563-03-06', 9),
(249, 2, 'ชุดเปลือกรถ ', 1500, 1, 1500, '2563-03-08', 7),
(250, 2, 'เบรกหน้า ', 800, 2, 1600, '2563-03-08', 7),
(251, 2, 'คอท่อสแตนเลส', 800, 1, 800, '2563-03-08', 7),
(252, 1, 'หัวเทียนขนาดเล็ก', 100, 2, 200, '2563-03-11', 1),
(253, 1, 'ลูกสูบ 53 cm ', 300, 1, 300, '2563-03-11', 1),
(254, 2, 'ท่อพร้อมคอท่อ', 1000, 2, 2000, '2563-03-11', 1),
(255, 2, 'แฮนด์ ', 150, 1, 150, '2563-03-11', 1),
(256, 1, 'ปั้มหัวฉีด ', 500, 1, 500, '2563-03-08', 1),
(257, 2, 'กันร้อนข้างท่อ', 350, 2, 700, '2563-03-08', 1),
(258, 3, 'ไฟหน้า ', 80, 1, 80, '2563-03-08', 1),
(259, 1, 'ปั้มหัวฉีด ', 500, 1, 500, '2563-03-18', 1),
(260, 2, 'กันร้อนข้างท่อ', 350, 2, 700, '2563-03-18', 1),
(261, 3, 'ไฟหน้า ', 80, 1, 80, '2563-03-18', 1);
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`Product_no` int(50) NOT NULL,
`CategoryID` int(50) NOT NULL,
`CategoryName` varchar(50) NOT NULL,
`ProductName` varchar(50) NOT NULL,
`Price` int(50) NOT NULL,
`Stock` int(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`Product_no`, `CategoryID`, `CategoryName`, `ProductName`, `Price`, `Stock`) VALUES
(1, 1, 'อะไหล่เครื่อง', 'ปั้มหัวฉีด ', 500, 98),
(2, 1, 'อะไหล่เครื่อง', 'ไส้กรองอากาศ', 300, 98),
(3, 1, 'อะไหล่เครื่อง', 'หัวเทียนขนาดเล็ก', 100, 178),
(4, 2, 'ชุดแต่งภายนอก', 'กันร้อนข้างท่อ', 350, 257),
(5, 2, 'ชุดแต่งภายนอก', 'ชุดเปลือกรถ ', 1500, 593),
(6, 2, 'ชุดแต่งภายนอก', 'ท่อพร้อมคอท่อ', 1000, 795),
(7, 3, 'ชุดไฟ', 'ไฟหน้า ', 80, 998),
(8, 3, 'ชุดไฟ', 'ไฟหลัง ', 20, 294),
(9, 3, 'ชุดไฟ', 'สายไฟ ', 20, 599),
(10, 1, 'อะไหล่เครื่อง', 'คาร์บูเรเตอร์ ', 1550, 464),
(11, 1, 'อะไหล่เครื่อง', 'ชุดข้างรถ 4 จังหวะ', 800, 98),
(12, 1, 'อะไหล่เครื่อง', 'ลูกสูบ 53 cm ', 300, 598),
(13, 1, 'อะไหล่เครื่อง', 'เฟืองทด ', 20, 497),
(14, 1, 'อะไหล่เครื่อง', 'โซ่ราวลิ้น ', 800, 299),
(15, 1, 'อะไหล่เครื่อง', 'แบตเตอรี่ ', 755, 800),
(16, 1, 'อะไหล่เครื่อง', 'ก้านลูกสูบ ', 50, 490),
(17, 4, 'อุปกรณ์เสริม', 'ตะกร้า ', 500, 470),
(18, 4, 'อุปกรณ์เสริม', 'ตัวยกโช็ค ', 80, 299),
(19, 4, 'อุปกรณ์เสริม', 'ผ้าคลุมรถ ', 300, 98),
(20, 4, 'อุปกรณ์เสริม', 'หมวกกันน็อค ', 500, 49),
(21, 4, 'อุปกรณ์เสริม', 'แฮนแต่ง ', 500, 38),
(22, 4, 'อุปกรณ์เสริม', 'เบาะแต่ง ', 1000, 39),
(23, 4, 'อุปกรณ์เสริม', 'กรองอากาศเปลือย', 80, 96),
(24, 4, 'อุปกรณ์เสริม', 'ดุมกลึง ', 1500, 299),
(25, 4, 'อุปกรณ์เสริม', 'ล้ออลูมิเนียม ', 500, 48),
(26, 4, 'อุปกรณ์เสริม', 'ล้อแมกซ์ ', 2000, 99),
(27, 4, 'อุปกรณ์เสริม', 'พักเท้าแต่ง ', 60, 58),
(28, 4, 'อุปกรณ์เสริม', 'น็อตสแตนเลส', 20, 46),
(29, 4, 'อุปกรณ์เสริม', 'กระจกแต่ง ', 500, 48),
(30, 3, 'ชุดไฟ', 'สายถัก ', 100, 209),
(31, 3, 'ชุดไฟ', 'ไฟซีนอล ', 500, 79),
(32, 3, 'ชุดไฟ', 'ไฟเลี่ยวแต่ง ', 600, 298),
(33, 3, 'ชุดไฟ', 'สวิตไฟ ', 100, 269),
(34, 3, 'ชุดไฟ', 'ไฟแต่ง LED ', 750, 45),
(35, 3, 'ชุดไฟ', 'ไฟกระพริบ LED', 295, 39),
(36, 2, 'ชุดแต่งภายนอก', 'มือเบรก ', 550, 58),
(37, 2, 'ชุดแต่งภายนอก', 'โช็คหลัง ', 2000, 59),
(38, 2, 'ชุดแต่งภายนอก', 'เบรกหน้า ', 800, 196),
(39, 2, 'ชุดแต่งภายนอก', 'ปั้มเบรกบน ', 500, 49),
(40, 2, 'ชุดแต่งภายนอก', 'แฮนด์ ', 150, 497),
(41, 2, 'ชุดแต่งภายนอก', 'คอท่อสแตนเลส', 800, 192),
(42, 2, 'ชุดแต่งภายนอก', 'กระจกส่องหลัง', 420, 698),
(43, 2, 'ชุดแต่งภายนอก', 'เรือนไมล์ ', 775, 199),
(45, 3, 'ชุดไฟ', 'ไฟติดข้างรถ ', 50, 78),
(46, 1, 'อะไหล่เครื่อง', 'น็อตเครื่อง ', 20, 87),
(47, 2, 'ชุดแต่งภายนอก', 'เข็มน้ำมันแยก', 600, 898),
(48, 3, 'ชุดไฟ', 'ไฟดีเลย์ ', 200, 49),
(49, 4, 'อุปกรณ์เสริม', 'ตัวเกี่ยวของ ', 50, 99),
(51, 3, 'ชุดไฟ', 'ไฟรุ่นไหม่', 30, 20);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `customer`
--
ALTER TABLE `customer`
ADD PRIMARY KEY (`Cus_id`);
--
-- Indexes for table `login`
--
ALTER TABLE `login`
ADD PRIMARY KEY (`Log_id`);
--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
ADD PRIMARY KEY (`Order_id`);
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`Product_no`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `customer`
--
ALTER TABLE `customer`
MODIFY `Cus_id` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `login`
--
ALTER TABLE `login`
MODIFY `Log_id` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
MODIFY `Order_id` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=262;
--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
MODIFY `Product_no` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=52;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sa;
import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.table.*;
import java.sql.Connection;
import javax.swing.JInternalFrame;
import net.proteanit.sql.DbUtils;
import javax.swing.JTextField;
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
/**
*
* @author ADMIN
*/
public class Main extends javax.swing.JFrame {
Connection c = Conection.getConnection();
String cus_id ;
String date;
/*String[] Value_quantity = {"","",""} ;
String[] Value_stock = {"","",""} ;*/
int countinsert = 0;
double totalresource =0;
String Product_no;
public Main() {
initComponents();
bartap();
}
public Main(String user){
initComponents();
name_Em.setText(user);
showemployee();
}
public void bartap(){
Bar.setVisible(false);
Bar.setEnabled(false);
Closetap.setVisible(false);
Closetap.setEnabled(false);
Bar_Tap.setVisible(true);
Bar_Tap.setEnabled(true);
}
public void active(){
Bar.setVisible(true);
Bar.setEnabled(true);
Closetap.setVisible(true);
Closetap.setEnabled(true);
Bar_Tap.setVisible(false);
Bar_Tap.setEnabled(false);
}
public void activer(JInternalFrame fr){
Order.setVisible(false);
Choice_manage.setVisible(false);
Payment.setVisible(false);
Manage.setVisible(false);
Register.setVisible(false);
Export_excel.setVisible(false);
dataanalyze.setVisible(false);
fr.setVisible(true);
}
public void showemployee(){
try{
String sql = "SELECT Log_name,Status FROM login where username = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, name_Em.getText());
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
name_em3.setText(rs.getString("Log_name"));
name_em2.setText(rs.getString("Status"));
}
String status = name_em2.getText();
if("CEO".equals(status)){
jButton14.setEnabled(true);
}
}catch(Exception e){e.printStackTrace();}
}
public void showproduct(){
try{
String sql = "SELECT * FROM products";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
jTableupdate.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}
public void showTable(){
try{
String sql = "select orders.CategoryID,orders.ProductName,orders.Price,Quantity,Total,Stock "
+ " from orders INNER JOIN products "
+ " ON orders.ProductName = products.ProductName "
+ " where Cus_id = ? and Date = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, cus_id);
stmt.setString(2, date);
ResultSet rs = stmt.executeQuery();
jTableconfirme.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}
public void showTablepayment(){
try{
String sql = "select orders.CategoryID,orders.ProductName,orders.Price,Quantity,Total "
+ " from orders INNER JOIN products "
+ " ON orders.ProductName = products.ProductName "
+ " where Cus_id = ? and Date = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, cus_id);
stmt.setString(2, date);
ResultSet rs = stmt.executeQuery();
jTablepayment.setModel(DbUtils.resultSetToTableModel(rs));
int row = 0;
for(int n=0;n<countinsert;n++){ //วนตามตาราง/////////////////////////////////////////////////////////
String total = jTableconfirme.getModel().getValueAt(row,4).toString();
totalresource += Double.parseDouble(total);
row++;
}
paymenttxt.setText(""+totalresource);
//countinsert=0;
}catch(Exception e){e.printStackTrace();}
}
public void Bill(){
String Employee_n = name_em3.getText();
String payment = paymenttxt.getText();
String money_in = payment_input.getText();
String money_out = payment_output.getText();
String cus_name = nameproduct.getText();
String phone = findphone.getText();
DefaultTableModel model = new DefaultTableModel();
model = (DefaultTableModel)jTablepayment.getModel();
showbill.setText(showbill.getText() + "-------------------------------------------------------------------------------\n");
showbill.setText(showbill.getText() + "ร้านขายอะไหล่ปลีกส่งรถจักรยานยนตร์(Motorcycle parts store) \n");
showbill.setText(showbill.getText() + "\n");
showbill.setText(showbill.getText() + " ใบเสร็จรับเงินแบบย่อ วันที่ขาย :"+date +" \n");
showbill.setText(showbill.getText() + "-------------------------------------------------------------------------------\n");
showbill.setText(showbill.getText() + " รายการสินค้า \n");
showbill.setText(showbill.getText() + "-------------------------------------------------------------------------------\n");
showbill.setText(showbill.getText() +"Quantity" + "\t" + "ProductName" + "\t" + "Price" + "\t" + "Total" +"\n");
int row =0;
for(int i =0; i < countinsert; i++)
{
String name1 = jTablepayment.getModel().getValueAt(row,1).toString();
String price1 = jTablepayment.getModel().getValueAt(row,2).toString();
String quantity1 = jTablepayment.getModel().getValueAt(row,3).toString();
String total1 = jTablepayment.getModel().getValueAt(row,4).toString();
showbill.setText(showbill.getText() + quantity1 + "\t" + name1+ "\t" + price1 + "\t"+ total1 +"\n");
row++;
}
showbill.setText(showbill.getText() + "\n");
showbill.setText(showbill.getText() + "\n");
showbill.setText(showbill.getText() + "\t" + "\t" + "\t" + "ยอดชำระ :" + totalresource + "\n");
showbill.setText(showbill.getText() + "\t" + "\t" + "\t" + "รับเงิน :" + money_in + "\n");
showbill.setText(showbill.getText() + "\t" + "\t" + "\t" + "เงินทอน :" + money_out + "\n");
showbill.setText(showbill.getText() + "\n");
showbill.setText(showbill.getText() + "ชื่อลูกค้า : "+cus_name+"\n");
showbill.setText(showbill.getText() + "เบอร์โทร : "+phone+"\n");
showbill.setText(showbill.getText() + "ชื่อพนักงานคิดเงิน : "+Employee_n+"\n");
showbill.setText(showbill.getText() + "\n");
showbill.setText(showbill.getText() + "-------------------------THANK YOU-----------------------------------\n");
countinsert=0;
totalresource=0;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
Bar_Tap = new javax.swing.JLabel();
Bar = new javax.swing.JPanel();
Profile = new javax.swing.JLabel();
Band = new javax.swing.JLabel();
Name_Em = new javax.swing.JLabel();
name_Em = new javax.swing.JLabel();
Closetap = new javax.swing.JLabel();
Status = new javax.swing.JLabel();
name_em2 = new javax.swing.JLabel();
name_em3 = new javax.swing.JLabel();
Status1 = new javax.swing.JLabel();
jLabel47 = new javax.swing.JLabel();
Band1 = new javax.swing.JLabel();
jLabel43 = new javax.swing.JLabel();
Mainmenu = new javax.swing.JPanel();
tap = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
Black = new javax.swing.JPanel();
gg = new javax.swing.JPanel();
jDesktopPane1 = new javax.swing.JDesktopPane();
Order = new javax.swing.JInternalFrame();
SetOrder = new javax.swing.JPanel();
jLabel27 = new javax.swing.JLabel();
jLabel63 = new javax.swing.JLabel();
jRadioButton17 = new javax.swing.JRadioButton();
jRadioButton18 = new javax.swing.JRadioButton();
jRadioButton19 = new javax.swing.JRadioButton();
jRadioButton20 = new javax.swing.JRadioButton();
jScrollPane5 = new javax.swing.JScrollPane();
jTable5 = new javax.swing.JTable();
jPanel2 = new javax.swing.JPanel();
jLabel70 = new javax.swing.JLabel();
jLabel54 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jButton7 = new javax.swing.JButton();
findphone = new javax.swing.JTextField();
jLabel71 = new javax.swing.JLabel();
id = new javax.swing.JLabel();
jLabel68 = new javax.swing.JLabel();
nameproduct = new javax.swing.JTextField();
jLabel20 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jLabel21 = new javax.swing.JLabel();
Order_type = new javax.swing.JTextField();
jLabel64 = new javax.swing.JLabel();
Order_name = new javax.swing.JTextField();
jLabel65 = new javax.swing.JLabel();
Order_price = new javax.swing.JTextField();
jLabel66 = new javax.swing.JLabel();
Order_quantity = new javax.swing.JSpinner();
jLabel67 = new javax.swing.JLabel();
total = new javax.swing.JTextField();
jLabel72 = new javax.swing.JLabel();
date_chooser = new com.toedter.calendar.JDateChooser();
jButton13 = new javax.swing.JButton();
jPanel5 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jButton9 = new javax.swing.JButton();
Payment = new javax.swing.JInternalFrame();
Setpayment = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
jTablepayment = new javax.swing.JTable();
jLabel26 = new javax.swing.JLabel();
jLabel28 = new javax.swing.JLabel();
jLabel29 = new javax.swing.JLabel();
paymenttxt = new javax.swing.JTextField();
payment_input = new javax.swing.JTextField();
payment_output = new javax.swing.JTextField();
jButton5 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jScrollPane4 = new javax.swing.JScrollPane();
showbill = new javax.swing.JTextArea();
jPanel8 = new javax.swing.JPanel();
jLabel74 = new javax.swing.JLabel();
jLabel56 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
Manage = new javax.swing.JInternalFrame();
Setmanagement = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jScrollPane6 = new javax.swing.JScrollPane();
jTableupdate = new javax.swing.JTable();
name1 = new javax.swing.JTextField();
price1 = new javax.swing.JTextField();
stock1 = new javax.swing.JTextField();
jLabel37 = new javax.swing.JLabel();
jLabel38 = new javax.swing.JLabel();
jLabel39 = new javax.swing.JLabel();
type1 = new javax.swing.JTextField();
jLabel40 = new javax.swing.JLabel();
jLabel30 = new javax.swing.JLabel();
searchtxt = new javax.swing.JTextField();
jLabel41 = new javax.swing.JLabel();
typename = new javax.swing.JTextField();
jPanel11 = new javax.swing.JPanel();
jLabel76 = new javax.swing.JLabel();
jLabel55 = new javax.swing.JLabel();
Register = new javax.swing.JInternalFrame();
Setregister = new javax.swing.JPanel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
phone = new javax.swing.JTextField();
name = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
address = new javax.swing.JTextArea();
jButton3 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel13 = new javax.swing.JLabel();
jLabel57 = new javax.swing.JLabel();
jLabel48 = new javax.swing.JLabel();
Export_excel = new javax.swing.JInternalFrame();
Setexcel = new javax.swing.JPanel();
jScrollPane7 = new javax.swing.JScrollPane();
jTableexcel = new javax.swing.JTable();
jButton10 = new javax.swing.JButton();
jRadioButton5 = new javax.swing.JRadioButton();
jRadioButton6 = new javax.swing.JRadioButton();
jRadioButton7 = new javax.swing.JRadioButton();
jRadioButton8 = new javax.swing.JRadioButton();
jPanel13 = new javax.swing.JPanel();
jLabel78 = new javax.swing.JLabel();
jLabel58 = new javax.swing.JLabel();
jLabel42 = new javax.swing.JLabel();
jLabel50 = new javax.swing.JLabel();
jLabel51 = new javax.swing.JLabel();
jLabel52 = new javax.swing.JLabel();
famelogo = new javax.swing.JLabel();
fameblack = new javax.swing.JLabel();
Confirm = new javax.swing.JInternalFrame();
Confirmed = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTableconfirme = new javax.swing.JTable();
jLabel17 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
Confirm_name = new javax.swing.JTextField();
Confirm_quantity = new javax.swing.JTextField();
Confirm_total = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jButton12 = new javax.swing.JButton();
jLabel22 = new javax.swing.JLabel();
Confirm_price = new javax.swing.JTextField();
jButton17 = new javax.swing.JButton();
jPanel6 = new javax.swing.JPanel();
jLabel73 = new javax.swing.JLabel();
jLabel59 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
Choice_manage = new javax.swing.JInternalFrame();
Setchoicemanage = new javax.swing.JPanel();
jButton4 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jButton14 = new javax.swing.JButton();
jButton15 = new javax.swing.JButton();
jLabel31 = new javax.swing.JLabel();
jLabel60 = new javax.swing.JLabel();
Input_product = new javax.swing.JInternalFrame();
inputdata = new javax.swing.JPanel();
jLabel32 = new javax.swing.JLabel();
jLabel33 = new javax.swing.JLabel();
jLabel34 = new javax.swing.JLabel();
jLabel35 = new javax.swing.JLabel();
input = new javax.swing.JTextField();
quantity = new javax.swing.JTextField();
price = new javax.swing.JTextField();
jButton16 = new javax.swing.JButton();
jPanel9 = new javax.swing.JPanel();
jLabel75 = new javax.swing.JLabel();
jLabel61 = new javax.swing.JLabel();
jPanel10 = new javax.swing.JPanel();
jLabel36 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jRadioButton4 = new javax.swing.JRadioButton();
jLabel49 = new javax.swing.JLabel();
dataanalyze = new javax.swing.JInternalFrame();
Setanalyze = new javax.swing.JPanel();
jScrollPane8 = new javax.swing.JScrollPane();
jTableanalyze = new javax.swing.JTable();
jLabel44 = new javax.swing.JLabel();
sumquantity = new javax.swing.JTextField();
jLabel45 = new javax.swing.JLabel();
sumtotal = new javax.swing.JTextField();
jComboBox1 = new javax.swing.JComboBox();
jLabel46 = new javax.swing.JLabel();
jPanel12 = new javax.swing.JPanel();
jLabel77 = new javax.swing.JLabel();
jLabel62 = new javax.swing.JLabel();
jLabel19 = new javax.swing.JLabel();
jLabel53 = new javax.swing.JLabel();
year1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Bar_Tap.setBackground(new java.awt.Color(255, 255, 255));
Bar_Tap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/menu (1).png"))); // NOI18N
Bar_Tap.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
Bar_TapMouseClicked(evt);
}
});
getContentPane().add(Bar_Tap, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 10, 70, 60));
Bar.setBackground(new java.awt.Color(0, 0, 0));
Bar.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Profile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/man (2).png"))); // NOI18N
Bar.add(Profile, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 180, 269, 226));
Band.setBackground(new java.awt.Color(255, 255, 255));
Band.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
Band.setForeground(new java.awt.Color(255, 153, 0));
Band.setText("parts store");
Band.setToolTipText("");
Bar.add(Band, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 100, 170, 80));
Name_Em.setBackground(new java.awt.Color(255, 255, 255));
Name_Em.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 18)); // NOI18N
Name_Em.setForeground(new java.awt.Color(255, 255, 255));
Name_Em.setText("<NAME>");
Bar.add(Name_Em, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 520, -1, 27));
name_Em.setBackground(new java.awt.Color(255, 255, 255));
name_Em.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 18)); // NOI18N
name_Em.setForeground(new java.awt.Color(0, 255, 0));
name_Em.setText(".");
Bar.add(name_Em, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 480, 110, 27));
Closetap.setBackground(new java.awt.Color(255, 255, 255));
Closetap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/back.png"))); // NOI18N
Closetap.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ClosetapMouseClicked(evt);
}
});
Bar.add(Closetap, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 0, 40, 70));
Status.setBackground(new java.awt.Color(255, 255, 255));
Status.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 18)); // NOI18N
Status.setForeground(new java.awt.Color(255, 255, 255));
Status.setText("Username");
Bar.add(Status, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 480, 120, 27));
name_em2.setBackground(new java.awt.Color(255, 255, 255));
name_em2.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 18)); // NOI18N
name_em2.setForeground(new java.awt.Color(51, 255, 0));
name_em2.setText(".");
Bar.add(name_em2, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 560, 110, 27));
name_em3.setBackground(new java.awt.Color(255, 255, 255));
name_em3.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 18)); // NOI18N
name_em3.setForeground(new java.awt.Color(51, 255, 0));
name_em3.setText(".");
Bar.add(name_em3, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 520, 110, 27));
Status1.setBackground(new java.awt.Color(255, 255, 255));
Status1.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 18)); // NOI18N
Status1.setForeground(new java.awt.Color(255, 255, 255));
Status1.setText("Status");
Bar.add(Status1, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 560, 70, 27));
Bar.add(jLabel47, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 140, -1, -1));
Band1.setBackground(new java.awt.Color(0, 0, 0));
Band1.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
Band1.setForeground(new java.awt.Color(255, 255, 255));
Band1.setText("Motorcycle ");
Band1.setToolTipText("");
Bar.add(Band1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, 260, 80));
jLabel43.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 18)); // NOI18N
jLabel43.setForeground(new java.awt.Color(102, 255, 255));
jLabel43.setText("LOGOUT");
jLabel43.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel43MouseClicked(evt);
}
});
Bar.add(jLabel43, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 650, -1, -1));
getContentPane().add(Bar, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 360, 690));
Mainmenu.setBackground(new java.awt.Color(255, 255, 255));
Mainmenu.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
tap.setBackground(new java.awt.Color(0, 153, 153));
tap.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/setup (1).png"))); // NOI18N
jLabel3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel3MouseClicked(evt);
}
});
tap.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 420, -1, 90));
jLabel7.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Management");
jLabel7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel7MouseClicked(evt);
}
});
tap.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 460, -1, -1));
jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/note (1).png"))); // NOI18N
jLabel11.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel11MouseClicked(evt);
}
});
tap.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 90, 120, 140));
jLabel12.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel12.setForeground(new java.awt.Color(255, 255, 255));
jLabel12.setText("Register");
jLabel12.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel12MouseClicked(evt);
}
});
tap.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 150, 140, 40));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/order (2).png"))); // NOI18N
jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel1MouseClicked(evt);
}
});
tap.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 200, 90, 110));
jLabel5.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Order");
jLabel5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel5MouseClicked(evt);
}
});
tap.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 250, 110, 40));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/money.png"))); // NOI18N
jLabel2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel2MouseClicked(evt);
}
});
tap.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 320, 70, 90));
jLabel6.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("Payment");
jLabel6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel6MouseClicked(evt);
}
});
tap.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 360, -1, -1));
jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/excel (1).png"))); // NOI18N
jLabel8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel8MouseClicked(evt);
}
});
tap.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 540, -1, 70));
jLabel10.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("Export to excel");
jLabel10.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel10MouseClicked(evt);
}
});
tap.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 570, 220, -1));
Mainmenu.add(tap, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 360, 740));
Black.setBackground(new java.awt.Color(0, 102, 153));
javax.swing.GroupLayout BlackLayout = new javax.swing.GroupLayout(Black);
Black.setLayout(BlackLayout);
BlackLayout.setHorizontalGroup(
BlackLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1310, Short.MAX_VALUE)
);
BlackLayout.setVerticalGroup(
BlackLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 130, Short.MAX_VALUE)
);
Mainmenu.add(Black, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 610, -1, 130));
gg.setBackground(new java.awt.Color(255, 255, 255));
jDesktopPane1.setBackground(new java.awt.Color(255, 255, 255));
jDesktopPane1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jDesktopPane1mouseclicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jDesktopPane1mouseentred(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jDesktopPane1mouseexited(evt);
}
});
jDesktopPane1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Order.setBackground(new java.awt.Color(255, 255, 255));
Order.setVisible(false);
Order.getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
SetOrder.setBackground(new java.awt.Color(51, 51, 51));
SetOrder.setPreferredSize(new java.awt.Dimension(860, 590));
SetOrder.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel27.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel27.setForeground(new java.awt.Color(255, 255, 255));
jLabel27.setText("หมวดสินค้า");
SetOrder.add(jLabel27, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 330, -1, -1));
SetOrder.add(jLabel63, new org.netbeans.lib.awtextra.AbsoluteConstraints(29, 218, -1, -1));
jRadioButton17.setBackground(new java.awt.Color(0, 153, 153));
buttonGroup1.add(jRadioButton17);
jRadioButton17.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jRadioButton17.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton17.setText("ชุดอะไหล่เครื่อง");
jRadioButton17.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton17ActionPerformed(evt);
}
});
SetOrder.add(jRadioButton17, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 330, -1, -1));
jRadioButton18.setBackground(new java.awt.Color(0, 153, 153));
buttonGroup1.add(jRadioButton18);
jRadioButton18.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jRadioButton18.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton18.setText("ชุดแต่งภายนอก");
jRadioButton18.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton18ActionPerformed(evt);
}
});
SetOrder.add(jRadioButton18, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 330, -1, -1));
jRadioButton19.setBackground(new java.awt.Color(0, 153, 153));
buttonGroup1.add(jRadioButton19);
jRadioButton19.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jRadioButton19.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton19.setText("ชุดไฟ");
jRadioButton19.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton19ActionPerformed(evt);
}
});
SetOrder.add(jRadioButton19, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 330, -1, -1));
jRadioButton20.setBackground(new java.awt.Color(0, 153, 153));
buttonGroup1.add(jRadioButton20);
jRadioButton20.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jRadioButton20.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton20.setText("อุปกรณ์เสริม");
jRadioButton20.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton20ActionPerformed(evt);
}
});
SetOrder.add(jRadioButton20, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 330, -1, -1));
jTable5.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jTable5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable5MouseClicked(evt);
}
});
jScrollPane5.setViewportView(jTable5);
SetOrder.add(jScrollPane5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 380, 540, 220));
jPanel2.setBackground(new java.awt.Color(255, 204, 51));
jLabel70.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel70.setForeground(new java.awt.Color(255, 255, 255));
jLabel70.setText("Order");
jLabel54.setBackground(new java.awt.Color(255, 255, 255));
jLabel54.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel54.setForeground(new java.awt.Color(255, 255, 255));
jLabel54.setText("X");
jLabel54.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel54MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel70, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 694, Short.MAX_VALUE)
.addComponent(jLabel54)
.addGap(87, 87, 87))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel70, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel54)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
SetOrder.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 70));
jPanel3.setBackground(new java.awt.Color(0, 204, 204));
jButton7.setBackground(new java.awt.Color(255, 255, 255));
jButton7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton7.setText("ค้นหา");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
findphone.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel71.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel71.setText("เบอร์โทรลูกค้า");
id.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel68.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel68.setText("รหัสลูกค้า :");
nameproduct.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
nameproduct.setRequestFocusEnabled(false);
jLabel20.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel20.setText("ชื่อลูกค้า :");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap(109, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel71, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel68, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel20, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(nameproduct, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(id)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(findphone, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(jButton7)))
.addContainerGap(42, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton7)
.addComponent(findphone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel71))
.addGap(29, 29, 29)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(id)
.addComponent(jLabel68))
.addGap(28, 28, 28)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(nameproduct, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20))
.addContainerGap(52, Short.MAX_VALUE))
);
SetOrder.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 80, 540, 220));
jPanel4.setBackground(new java.awt.Color(0, 102, 153));
jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel21.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel21.setForeground(new java.awt.Color(255, 255, 255));
jLabel21.setText("หมวดสินค้า :");
jPanel4.add(jLabel21, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 30, -1, -1));
Order_type.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jPanel4.add(Order_type, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 30, 150, -1));
jLabel64.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel64.setForeground(new java.awt.Color(255, 255, 255));
jLabel64.setText("ชื่อสินค้า :");
jPanel4.add(jLabel64, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 80, -1, -1));
Order_name.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jPanel4.add(Order_name, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 80, 150, -1));
jLabel65.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel65.setForeground(new java.awt.Color(255, 255, 255));
jLabel65.setText("ราคา :");
jPanel4.add(jLabel65, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 130, -1, -1));
Order_price.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jPanel4.add(Order_price, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 130, 150, -1));
jLabel66.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel66.setForeground(new java.awt.Color(255, 255, 255));
jLabel66.setText("จำนวนที่ต้องาร :");
jPanel4.add(jLabel66, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 190, -1, -1));
Order_quantity.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
Order_quantityStateChanged(evt);
}
});
jPanel4.add(Order_quantity, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 190, 150, 30));
jLabel67.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel67.setForeground(new java.awt.Color(255, 255, 255));
jLabel67.setText("ราคารวม :");
jPanel4.add(jLabel67, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 250, -1, -1));
total.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
total.setRequestFocusEnabled(false);
jPanel4.add(total, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 250, 150, -1));
jLabel72.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel72.setForeground(new java.awt.Color(255, 255, 255));
jLabel72.setText("วันที่ขาย :");
jPanel4.add(jLabel72, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 310, -1, -1));
date_chooser.setDateFormatString("yyyy-MM-dd");
date_chooser.setMaxSelectableDate(new java.util.Date(253370743302000L));
date_chooser.setMinSelectableDate(new java.util.Date(-62135791098000L));
jPanel4.add(date_chooser, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 310, 150, 30));
jButton13.setBackground(new java.awt.Color(255, 255, 255));
jButton13.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton13.setText("เพิ่มรายการ");
jButton13.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton13ActionPerformed(evt);
}
});
jPanel4.add(jButton13, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 380, 150, -1));
SetOrder.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 80, 340, 430));
jPanel5.setBackground(new java.awt.Color(0, 153, 153));
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 540, Short.MAX_VALUE)
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 40, Short.MAX_VALUE)
);
SetOrder.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 320, 540, 40));
jPanel7.setBackground(new java.awt.Color(0, 153, 153));
jButton9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton9.setText("ยืนยันออเดอร์");
jButton9.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton9MouseClicked(evt);
}
});
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
.addContainerGap(105, Short.MAX_VALUE)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(95, 95, 95))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(19, Short.MAX_VALUE))
);
SetOrder.add(jPanel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 520, 340, 80));
Order.getContentPane().add(SetOrder, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 970, 640));
jDesktopPane1.add(Order, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, -30, 1150, 800));
Payment.setBackground(new java.awt.Color(255, 255, 255));
Payment.setPreferredSize(new java.awt.Dimension(906, 604));
Payment.setVisible(false);
Payment.getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Setpayment.setBackground(new java.awt.Color(0, 0, 51));
Setpayment.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTablepayment.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane3.setViewportView(jTablepayment);
Setpayment.add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 120, 590, 180));
jLabel26.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel26.setForeground(new java.awt.Color(255, 255, 255));
jLabel26.setText("จำนวนเงินที่ต้องชำระ");
Setpayment.add(jLabel26, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 350, -1, -1));
jLabel28.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel28.setForeground(new java.awt.Color(255, 255, 255));
jLabel28.setText("รับเงินมา");
Setpayment.add(jLabel28, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 390, -1, -1));
jLabel29.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel29.setForeground(new java.awt.Color(255, 255, 255));
jLabel29.setText("เงินทอน");
Setpayment.add(jLabel29, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 440, -1, -1));
paymenttxt.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Setpayment.add(paymenttxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 350, 140, -1));
payment_input.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Setpayment.add(payment_input, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 390, 140, -1));
payment_output.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Setpayment.add(payment_output, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 430, 140, -1));
jButton5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton5.setText("จ่ายเงิน");
jButton5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton5MouseClicked(evt);
}
});
Setpayment.add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 500, 140, 70));
jButton8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton8.setText("พิมใบเสร็จ");
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
Setpayment.add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 500, 140, 70));
showbill.setColumns(20);
showbill.setRows(5);
jScrollPane4.setViewportView(showbill);
Setpayment.add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 330, 365, 252));
jPanel8.setBackground(new java.awt.Color(102, 102, 255));
jLabel74.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel74.setForeground(new java.awt.Color(255, 255, 255));
jLabel74.setText("PAYMENT");
jLabel56.setBackground(new java.awt.Color(255, 255, 255));
jLabel56.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel56.setForeground(new java.awt.Color(255, 255, 255));
jLabel56.setText("X");
jLabel56.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel56MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel74, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 605, Short.MAX_VALUE)
.addComponent(jLabel56)
.addGap(81, 81, 81))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel74, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel56)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
Setpayment.add(jPanel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 70));
jLabel25.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/mastercard.png"))); // NOI18N
Setpayment.add(jLabel25, new org.netbeans.lib.awtextra.AbsoluteConstraints(720, 150, -1, -1));
Payment.getContentPane().add(Setpayment, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 950, 620));
jDesktopPane1.add(Payment, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, -30, 1150, 800));
Manage.setBackground(new java.awt.Color(255, 255, 255));
Manage.setVisible(false);
Manage.getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Setmanagement.setBackground(new java.awt.Color(51, 0, 51));
Setmanagement.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setBackground(new java.awt.Color(255, 255, 255));
jButton1.setText("ลบ");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
Setmanagement.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(780, 450, 130, 70));
jButton6.setBackground(new java.awt.Color(255, 255, 255));
jButton6.setText("แก้ไข");
jButton6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton6MouseClicked(evt);
}
});
Setmanagement.add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 450, 130, 70));
jTableupdate.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTableupdate.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTableupdateMouseClicked(evt);
}
});
jScrollPane6.setViewportView(jTableupdate);
Setmanagement.add(jScrollPane6, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 200, 520, 370));
name1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Setmanagement.add(name1, new org.netbeans.lib.awtextra.AbsoluteConstraints(720, 270, 139, 29));
price1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Setmanagement.add(price1, new org.netbeans.lib.awtextra.AbsoluteConstraints(720, 320, 139, 29));
stock1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Setmanagement.add(stock1, new org.netbeans.lib.awtextra.AbsoluteConstraints(720, 370, 139, 29));
jLabel37.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel37.setForeground(new java.awt.Color(255, 255, 255));
jLabel37.setText("คงเหลือในคลัง");
Setmanagement.add(jLabel37, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 370, -1, -1));
jLabel38.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel38.setForeground(new java.awt.Color(255, 255, 255));
jLabel38.setText("ราคา");
Setmanagement.add(jLabel38, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 320, -1, -1));
jLabel39.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel39.setForeground(new java.awt.Color(255, 255, 255));
jLabel39.setText("ชื่อสินค้า");
Setmanagement.add(jLabel39, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 270, -1, -1));
type1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Setmanagement.add(type1, new org.netbeans.lib.awtextra.AbsoluteConstraints(720, 150, 139, 29));
jLabel40.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel40.setForeground(new java.awt.Color(255, 255, 255));
jLabel40.setText("รหัสหมวดสินค้า");
Setmanagement.add(jLabel40, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 150, -1, -1));
jLabel30.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel30.setForeground(new java.awt.Color(255, 255, 255));
jLabel30.setText("ชื่อสินค้า");
Setmanagement.add(jLabel30, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 130, -1, -1));
searchtxt.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
searchtxt.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
searchtxtKeyReleased(evt);
}
});
Setmanagement.add(searchtxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 130, 180, -1));
jLabel41.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel41.setForeground(new java.awt.Color(255, 255, 255));
jLabel41.setText("ชนิดสินค้า");
Setmanagement.add(jLabel41, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 210, -1, -1));
typename.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Setmanagement.add(typename, new org.netbeans.lib.awtextra.AbsoluteConstraints(720, 210, 139, 29));
jPanel11.setBackground(new java.awt.Color(153, 153, 255));
jLabel76.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel76.setForeground(new java.awt.Color(255, 255, 255));
jLabel76.setText("Management");
jLabel55.setBackground(new java.awt.Color(255, 255, 255));
jLabel55.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel55.setForeground(new java.awt.Color(255, 255, 255));
jLabel55.setText("X");
jLabel55.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel55MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel76, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 564, Short.MAX_VALUE)
.addComponent(jLabel55)
.addGap(95, 95, 95))
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addComponent(jLabel76, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel55)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
Setmanagement.add(jPanel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 70));
Manage.getContentPane().add(Setmanagement, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 950, 630));
jDesktopPane1.add(Manage, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, -30, 1150, 800));
Register.setBackground(new java.awt.Color(255, 255, 255));
Register.setPreferredSize(new java.awt.Dimension(906, 604));
Register.setVisible(false);
Register.getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Setregister.setBackground(new java.awt.Color(51, 51, 51));
Setregister.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel14.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel14.setForeground(new java.awt.Color(255, 255, 255));
jLabel14.setText("Address");
Setregister.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 260, -1, -1));
jLabel15.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel15.setForeground(new java.awt.Color(255, 255, 255));
jLabel15.setText("Name");
Setregister.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 160, -1, -1));
jLabel18.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel18.setForeground(new java.awt.Color(255, 255, 255));
jLabel18.setText("Phnoe");
Setregister.add(jLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 210, -1, -1));
Setregister.add(phone, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 210, 176, 37));
Setregister.add(name, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 160, 176, 30));
address.setColumns(20);
address.setRows(5);
jScrollPane1.setViewportView(address);
Setregister.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 270, 353, 209));
jButton3.setBackground(new java.awt.Color(255, 255, 255));
jButton3.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jButton3.setText("confirm");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
Setregister.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 510, 160, 34));
jPanel1.setBackground(new java.awt.Color(0, 204, 102));
jLabel13.setBackground(new java.awt.Color(255, 255, 255));
jLabel13.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel13.setForeground(new java.awt.Color(255, 255, 255));
jLabel13.setText("Register");
jLabel57.setBackground(new java.awt.Color(255, 255, 255));
jLabel57.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel57.setForeground(new java.awt.Color(255, 255, 255));
jLabel57.setText("X");
jLabel57.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel57MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 644, Short.MAX_VALUE)
.addComponent(jLabel57)
.addGap(39, 39, 39))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 29, Short.MAX_VALUE)
.addComponent(jLabel13))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel57)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
Setregister.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 950, 70));
jLabel48.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/sign-up.png"))); // NOI18N
Setregister.add(jLabel48, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 160, 480, 470));
Register.getContentPane().add(Setregister, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 950, 620));
jDesktopPane1.add(Register, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, -30, 1150, 800));
Export_excel.setBackground(new java.awt.Color(255, 255, 255));
Export_excel.setPreferredSize(new java.awt.Dimension(906, 604));
Export_excel.setVisible(false);
Export_excel.getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Setexcel.setBackground(new java.awt.Color(0, 51, 51));
Setexcel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTableexcel.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane7.setViewportView(jTableexcel);
Setexcel.add(jScrollPane7, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 140, 680, 360));
jButton10.setBackground(new java.awt.Color(255, 255, 255));
jButton10.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton10.setText("Export");
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
Setexcel.add(jButton10, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 520, 140, 49));
jRadioButton5.setBackground(new java.awt.Color(0, 51, 51));
buttonGroup3.add(jRadioButton5);
jRadioButton5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jRadioButton5.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton5.setText("Customer");
jRadioButton5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jRadioButton5MouseClicked(evt);
}
});
Setexcel.add(jRadioButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 180, -1, -1));
jRadioButton6.setBackground(new java.awt.Color(0, 51, 51));
buttonGroup3.add(jRadioButton6);
jRadioButton6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jRadioButton6.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton6.setText("Login");
jRadioButton6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jRadioButton6MouseClicked(evt);
}
});
Setexcel.add(jRadioButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 240, -1, -1));
jRadioButton7.setBackground(new java.awt.Color(0, 51, 51));
buttonGroup3.add(jRadioButton7);
jRadioButton7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jRadioButton7.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton7.setText("Orders");
jRadioButton7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jRadioButton7MouseClicked(evt);
}
});
Setexcel.add(jRadioButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 300, -1, -1));
jRadioButton8.setBackground(new java.awt.Color(0, 51, 51));
buttonGroup3.add(jRadioButton8);
jRadioButton8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jRadioButton8.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton8.setText("Products");
jRadioButton8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jRadioButton8MouseClicked(evt);
}
});
Setexcel.add(jRadioButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 360, -1, -1));
jPanel13.setBackground(new java.awt.Color(255, 102, 102));
jLabel78.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel78.setForeground(new java.awt.Color(255, 255, 255));
jLabel78.setText("Export Excel");
jLabel58.setBackground(new java.awt.Color(255, 255, 255));
jLabel58.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel58.setForeground(new java.awt.Color(255, 255, 255));
jLabel58.setText("X");
jLabel58.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel58MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel78, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 553, Short.MAX_VALUE)
.addComponent(jLabel58)
.addGap(104, 104, 104))
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel78, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel58)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
Setexcel.add(jPanel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1020, 70));
Export_excel.getContentPane().add(Setexcel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1030, 630));
jDesktopPane1.add(Export_excel, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, -30, 1150, 800));
jLabel42.setBackground(new java.awt.Color(255, 255, 255));
jLabel42.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel42.setForeground(new java.awt.Color(255, 255, 255));
jLabel42.setText("X");
jLabel42.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel42MouseClicked(evt);
}
});
jDesktopPane1.add(jLabel42, new org.netbeans.lib.awtextra.AbsoluteConstraints(890, 10, 30, 30));
jLabel50.setFont(new java.awt.Font("Copperplate Gothic Bold", 1, 36)); // NOI18N
jLabel50.setForeground(new java.awt.Color(255, 255, 255));
jLabel50.setText("About");
jDesktopPane1.add(jLabel50, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 110, -1, -1));
jLabel51.setFont(new java.awt.Font("Copperplate Gothic Bold", 1, 24)); // NOI18N
jLabel51.setForeground(new java.awt.Color(255, 255, 255));
jLabel51.setText("Motorcycle parts store - 1.0.1\n");
jDesktopPane1.add(jLabel51, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 200, -1, -1));
jLabel52.setFont(new java.awt.Font("Copperplate Gothic Bold", 1, 24)); // NOI18N
jLabel52.setForeground(new java.awt.Color(255, 255, 255));
jLabel52.setText("version : 1.0.1 SE");
jDesktopPane1.add(jLabel52, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 260, -1, -1));
famelogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/scooter.png"))); // NOI18N
jDesktopPane1.add(famelogo, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 330, 270, 240));
fameblack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/black2.png"))); // NOI18N
jDesktopPane1.add(fameblack, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 790));
Confirm.setBackground(new java.awt.Color(255, 255, 255));
Confirm.setPreferredSize(new java.awt.Dimension(906, 604));
Confirm.setVisible(false);
Confirm.getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Confirmed.setBackground(new java.awt.Color(0, 51, 51));
Confirmed.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTableconfirme.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTableconfirme.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTableconfirmeMouseClicked(evt);
}
});
jScrollPane2.setViewportView(jTableconfirme);
Confirmed.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 100, 570, 263));
jLabel17.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel17.setForeground(new java.awt.Color(255, 255, 255));
jLabel17.setText("ชื่อ");
Confirmed.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 400, -1, -1));
jLabel23.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel23.setForeground(new java.awt.Color(255, 255, 255));
jLabel23.setText("จำนวน");
Confirmed.add(jLabel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 510, -1, -1));
jLabel24.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel24.setForeground(new java.awt.Color(255, 255, 255));
jLabel24.setText("ราคารวม");
Confirmed.add(jLabel24, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 560, -1, -1));
Confirm_name.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Confirm_name.setRequestFocusEnabled(false);
Confirmed.add(Confirm_name, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 400, 160, -1));
Confirm_quantity.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Confirmed.add(Confirm_quantity, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 500, 160, -1));
Confirm_total.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Confirm_total.setRequestFocusEnabled(false);
Confirmed.add(Confirm_total, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 560, 160, -1));
jButton2.setBackground(new java.awt.Color(255, 255, 255));
jButton2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton2.setText("ยืนยันรายการ");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton2MouseClicked(evt);
}
});
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
Confirmed.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 420, 140, 150));
jButton12.setBackground(new java.awt.Color(255, 255, 255));
jButton12.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton12.setText("แก้ไข");
jButton12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton12ActionPerformed(evt);
}
});
Confirmed.add(jButton12, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 420, 120, 60));
jLabel22.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel22.setForeground(new java.awt.Color(255, 255, 255));
jLabel22.setText("ราคา");
Confirmed.add(jLabel22, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 450, -1, -1));
Confirm_price.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Confirm_price.setRequestFocusEnabled(false);
Confirmed.add(Confirm_price, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 450, 160, -1));
jButton17.setBackground(new java.awt.Color(255, 255, 255));
jButton17.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton17.setText("ลบ");
jButton17.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton17ActionPerformed(evt);
}
});
Confirmed.add(jButton17, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 510, 120, 60));
jPanel6.setBackground(new java.awt.Color(255, 102, 102));
jLabel73.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel73.setForeground(new java.awt.Color(255, 255, 255));
jLabel73.setText("Confirmed");
jLabel59.setBackground(new java.awt.Color(255, 255, 255));
jLabel59.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel59.setForeground(new java.awt.Color(255, 255, 255));
jLabel59.setText("X");
jLabel59.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel59MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(48, 48, 48)
.addComponent(jLabel73, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 583, Short.MAX_VALUE)
.addComponent(jLabel59)
.addGap(63, 63, 63))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addComponent(jLabel73, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel59)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
Confirmed.add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 970, 70));
jLabel16.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/contact-form.png"))); // NOI18N
Confirmed.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 160, -1, -1));
Confirm.getContentPane().add(Confirmed, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 950, 620));
jDesktopPane1.add(Confirm, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, -30, 1150, 800));
Choice_manage.setBackground(new java.awt.Color(255, 255, 255));
Choice_manage.setPreferredSize(new java.awt.Dimension(906, 604));
Choice_manage.setVisible(false);
Choice_manage.getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Setchoicemanage.setBackground(new java.awt.Color(0, 51, 51));
jButton4.setBackground(new java.awt.Color(0, 51, 51));
jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/box (1).png"))); // NOI18N
jButton4.setBorder(null);
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("ลบ/แก้ไขข้อมูล");
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("เพิ่มสินค้าเข้าคลังสินค้า");
jButton14.setBackground(new java.awt.Color(0, 51, 51));
jButton14.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/3d.png"))); // NOI18N
jButton14.setBorder(null);
jButton14.setEnabled(false);
jButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton14ActionPerformed(evt);
}
});
jButton15.setBackground(new java.awt.Color(0, 51, 51));
jButton15.setForeground(new java.awt.Color(0, 51, 51));
jButton15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/data-storage.png"))); // NOI18N
jButton15.setBorder(null);
jButton15.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton15MouseClicked(evt);
}
});
jLabel31.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel31.setForeground(new java.awt.Color(255, 255, 255));
jLabel31.setText("วิเคราะห์ยอดขาย");
jLabel60.setBackground(new java.awt.Color(255, 255, 255));
jLabel60.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel60.setForeground(new java.awt.Color(255, 255, 255));
jLabel60.setText("X");
jLabel60.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel60MouseClicked(evt);
}
});
javax.swing.GroupLayout SetchoicemanageLayout = new javax.swing.GroupLayout(Setchoicemanage);
Setchoicemanage.setLayout(SetchoicemanageLayout);
SetchoicemanageLayout.setHorizontalGroup(
SetchoicemanageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SetchoicemanageLayout.createSequentialGroup()
.addGroup(SetchoicemanageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SetchoicemanageLayout.createSequentialGroup()
.addGap(43, 43, 43)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SetchoicemanageLayout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 61, Short.MAX_VALUE)
.addGroup(SetchoicemanageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SetchoicemanageLayout.createSequentialGroup()
.addComponent(jButton15)
.addGap(59, 59, 59)
.addComponent(jButton14)
.addGap(30, 30, 30))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SetchoicemanageLayout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(132, 132, 132)
.addComponent(jLabel31, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(73, 73, 73))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SetchoicemanageLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel60)
.addGap(41, 41, 41))
);
SetchoicemanageLayout.setVerticalGroup(
SetchoicemanageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SetchoicemanageLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel60)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 160, Short.MAX_VALUE)
.addGroup(SetchoicemanageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton14, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGap(27, 27, 27)
.addGroup(SetchoicemanageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel31))
.addGap(118, 118, 118))
);
Choice_manage.getContentPane().add(Setchoicemanage, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 950, 620));
jDesktopPane1.add(Choice_manage, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, -30, 1150, 800));
Input_product.setBackground(new java.awt.Color(255, 255, 255));
Input_product.setVisible(false);
Input_product.getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
inputdata.setBackground(new java.awt.Color(51, 51, 51));
inputdata.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel32.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
inputdata.add(jLabel32, new org.netbeans.lib.awtextra.AbsoluteConstraints(48, 29, -1, -1));
jLabel33.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel33.setForeground(new java.awt.Color(255, 255, 255));
jLabel33.setText("ชื่อสินค้า");
inputdata.add(jLabel33, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 170, 80, -1));
jLabel34.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel34.setForeground(new java.awt.Color(255, 255, 255));
jLabel34.setText("จำนวน");
inputdata.add(jLabel34, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 330, 60, -1));
jLabel35.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel35.setForeground(new java.awt.Color(255, 255, 255));
jLabel35.setText("ราคา");
inputdata.add(jLabel35, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 240, 50, -1));
input.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
inputdata.add(input, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 160, 180, 29));
quantity.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
inputdata.add(quantity, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 330, 180, 30));
price.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
inputdata.add(price, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 240, 180, 29));
jButton16.setBackground(new java.awt.Color(255, 255, 255));
jButton16.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton16.setText("เพิ่มรายการ");
jButton16.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton16ActionPerformed(evt);
}
});
inputdata.add(jButton16, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 430, 150, 50));
jPanel9.setBackground(new java.awt.Color(204, 0, 255));
jLabel75.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel75.setForeground(new java.awt.Color(255, 255, 255));
jLabel75.setText("Management");
jLabel61.setBackground(new java.awt.Color(255, 255, 255));
jLabel61.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel61.setForeground(new java.awt.Color(255, 255, 255));
jLabel61.setText("X");
jLabel61.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel61MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel75, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 567, Short.MAX_VALUE)
.addComponent(jLabel61)
.addGap(92, 92, 92))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addComponent(jLabel75, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel61)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
inputdata.add(jPanel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 70));
jPanel10.setBackground(new java.awt.Color(0, 204, 204));
jPanel10.setForeground(new java.awt.Color(204, 204, 255));
jLabel36.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel36.setForeground(new java.awt.Color(255, 255, 255));
jLabel36.setText("หมวด");
jRadioButton1.setBackground(new java.awt.Color(0, 204, 204));
buttonGroup2.add(jRadioButton1);
jRadioButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jRadioButton1.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton1.setText("อะไหล่ภายใน");
jRadioButton2.setBackground(new java.awt.Color(0, 204, 204));
buttonGroup2.add(jRadioButton2);
jRadioButton2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jRadioButton2.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton2.setText("อะไหล่ภายนอก");
jRadioButton2.setActionCommand("อะไหล่ภายใน");
jRadioButton3.setBackground(new java.awt.Color(0, 204, 204));
buttonGroup2.add(jRadioButton3);
jRadioButton3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jRadioButton3.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton3.setText("ชุดไฟ");
jRadioButton3.setActionCommand("อะไหล่ภายใน");
jRadioButton4.setBackground(new java.awt.Color(0, 204, 204));
buttonGroup2.add(jRadioButton4);
jRadioButton4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jRadioButton4.setForeground(new java.awt.Color(255, 255, 255));
jRadioButton4.setText("อะไหล่แต่งเสริม");
jRadioButton4.setActionCommand("อะไหล่ภายใน");
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButton1)
.addComponent(jRadioButton2)
.addComponent(jRadioButton3)
.addComponent(jRadioButton4)
.addComponent(jLabel36, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel36)
.addGap(31, 31, 31)
.addComponent(jRadioButton1)
.addGap(19, 19, 19)
.addComponent(jRadioButton2)
.addGap(19, 19, 19)
.addComponent(jRadioButton3)
.addGap(19, 19, 19)
.addComponent(jRadioButton4)
.addContainerGap(38, Short.MAX_VALUE))
);
inputdata.add(jPanel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 120, 220, 290));
jLabel49.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/management.png"))); // NOI18N
inputdata.add(jLabel49, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 130, -1, -1));
Input_product.getContentPane().add(inputdata, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 950, 630));
jDesktopPane1.add(Input_product, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, -30, 1150, 800));
dataanalyze.setBackground(new java.awt.Color(255, 255, 255));
dataanalyze.setPreferredSize(new java.awt.Dimension(906, 604));
dataanalyze.setVisible(false);
dataanalyze.getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Setanalyze.setBackground(new java.awt.Color(0, 51, 51));
Setanalyze.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTableanalyze.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane8.setViewportView(jTableanalyze);
Setanalyze.add(jScrollPane8, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 160, 620, 240));
jLabel44.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel44.setForeground(new java.awt.Color(255, 255, 255));
jLabel44.setText("จำนวนสินค้าที่ขายได้");
Setanalyze.add(jLabel44, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 440, 240, -1));
sumquantity.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
Setanalyze.add(sumquantity, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 440, 170, -1));
jLabel45.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel45.setForeground(new java.awt.Color(255, 255, 255));
jLabel45.setText("รายได้รวม");
Setanalyze.add(jLabel45, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 500, -1, -1));
sumtotal.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
Setanalyze.add(sumtotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 500, 170, -1));
jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " SELECT MONTH", "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม" }));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
Setanalyze.add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 110, 300, -1));
jLabel46.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel46.setForeground(new java.awt.Color(255, 255, 255));
jLabel46.setText("YEAR");
Setanalyze.add(jLabel46, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 110, -1, -1));
jPanel12.setBackground(new java.awt.Color(0, 204, 204));
jLabel77.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel77.setForeground(new java.awt.Color(255, 255, 255));
jLabel77.setText(" Analyze");
jLabel62.setBackground(new java.awt.Color(255, 255, 255));
jLabel62.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel62.setForeground(new java.awt.Color(255, 255, 255));
jLabel62.setText("X");
jLabel62.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel62MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel77, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 572, Short.MAX_VALUE)
.addComponent(jLabel62)
.addGap(87, 87, 87))
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addComponent(jLabel77, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel62)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
Setanalyze.add(jPanel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 70));
jLabel19.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/home (1).png"))); // NOI18N
Setanalyze.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 280, 320, 330));
jLabel53.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel53.setForeground(new java.awt.Color(255, 255, 255));
jLabel53.setText("MONTH");
Setanalyze.add(jLabel53, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 110, -1, -1));
year1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
Setanalyze.add(year1, new org.netbeans.lib.awtextra.AbsoluteConstraints(690, 110, 110, 30));
dataanalyze.getContentPane().add(Setanalyze, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 950, 620));
jDesktopPane1.add(dataanalyze, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, -30, 1150, 800));
javax.swing.GroupLayout ggLayout = new javax.swing.GroupLayout(gg);
gg.setLayout(ggLayout);
ggLayout.setHorizontalGroup(
ggLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ggLayout.createSequentialGroup()
.addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 940, Short.MAX_VALUE)
.addContainerGap())
);
ggLayout.setVerticalGroup(
ggLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 610, Short.MAX_VALUE)
);
Mainmenu.add(gg, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 0, 950, 610));
getContentPane().add(Mainmenu, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1290, 690));
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void Bar_TapMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Bar_TapMouseClicked
active();
}//GEN-LAST:event_Bar_TapMouseClicked
private void ClosetapMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ClosetapMouseClicked
bartap();
}//GEN-LAST:event_ClosetapMouseClicked
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked
activer(Order);
showbill.setText("");
}//GEN-LAST:event_jLabel1MouseClicked
private void jDesktopPane1mouseclicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDesktopPane1mouseclicked
}//GEN-LAST:event_jDesktopPane1mouseclicked
private void jDesktopPane1mouseentred(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDesktopPane1mouseentred
}//GEN-LAST:event_jDesktopPane1mouseentred
private void jDesktopPane1mouseexited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDesktopPane1mouseexited
}//GEN-LAST:event_jDesktopPane1mouseexited
private void jLabel5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel5MouseClicked
activer(Order);
showbill.setText("");
payment_input.setText("");
payment_output.setText("");
}//GEN-LAST:event_jLabel5MouseClicked
private void jLabel12MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel12MouseClicked
activer(Register);
}//GEN-LAST:event_jLabel12MouseClicked
private void jLabel11MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel11MouseClicked
activer(Register);
}//GEN-LAST:event_jLabel11MouseClicked
private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel2MouseClicked
activer(Payment);
showTablepayment();
}//GEN-LAST:event_jLabel2MouseClicked
private void jLabel6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel6MouseClicked
activer(Payment);
showTablepayment();
}//GEN-LAST:event_jLabel6MouseClicked
private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked
activer(Choice_manage);
}//GEN-LAST:event_jLabel3MouseClicked
private void jLabel7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel7MouseClicked
activer(Choice_manage);
}//GEN-LAST:event_jLabel7MouseClicked
private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked
activer(Export_excel);
}//GEN-LAST:event_jLabel8MouseClicked
private void jLabel10MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel10MouseClicked
activer(Export_excel);
}//GEN-LAST:event_jLabel10MouseClicked
private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton16ActionPerformed
////////////////////////////// เพิ่มข้อมูลสินค้า ////////////////////////////////////////
try{
if (jRadioButton1.isSelected()){
int type1 = 1;
String name1 = "อะไหล่เครื่อง";
String sql = "INSERT INTO products (CategoryID,CategoryName,ProductName,Price,Stock) VALUES (?,?,?,?,?)";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, ""+type1);
stmt.setString(2, name1);
stmt.setString(3, input.getText());
stmt.setString(4, price.getText());
stmt.setString(5, quantity.getText());
stmt.executeUpdate();
}
if (jRadioButton2.isSelected()){
int type2 = 2;
String name2 = "ชุดแต่งภายนอก";
String sql = "INSERT INTO products (CategoryID,CategoryName,ProductName,Price,Stock) VALUES (?,?,?,?,?)";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, ""+type2);
stmt.setString(2, name2);
stmt.setString(3, input.getText());
stmt.setString(4, price.getText());
stmt.setString(5, quantity.getText());
stmt.executeUpdate();
}
if (jRadioButton3.isSelected()){
int type3 = 3;
String name3 = "ชุดไฟ";
String sql = "INSERT INTO products (CategoryID,CategoryName,ProductName,Price,Stock) VALUES (?,?,?,?,?)";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, ""+type3);
stmt.setString(2, name3);
stmt.setString(3, input.getText());
stmt.setString(4, price.getText());
stmt.setString(5, quantity.getText());
stmt.executeUpdate();
}
if (jRadioButton4.isSelected()){
int type4 = 4;
String name4 = "อุปกรณ์เสริม";
String sql = "INSERT INTO products (CategoryID,CategoryName,ProductName,Price,Stock) VALUES (?,?,?,?,?)";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, ""+type4);
stmt.setString(2, name4);
stmt.setString(3, input.getText());
stmt.setString(4, price.getText());
stmt.setString(5, quantity.getText());
stmt.executeUpdate();
}
JOptionPane.showMessageDialog(null, "การเพิ่มข้อมูลสำเร็จ","เพิ่มข้อมูลสินค้า",JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {e.printStackTrace();}
input.setText("");
price.setText("");
quantity.setText("");
}//GEN-LAST:event_jButton16ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
activer(Input_product);
}//GEN-LAST:event_jButton4ActionPerformed
private void jRadioButton17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton17ActionPerformed
//////////////////////////////// สินค้าประเภท ภายใน ////////////////////////
try{
String sql = "SELECT CategoryID,ProductName,Price,Stock FROM products where CategoryID = 1 HAVING Stock >= 1";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
jTable5.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jRadioButton17ActionPerformed
private void jRadioButton18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton18ActionPerformed
//////////////////////////////// สินค้าประเภท ภายนอก ////////////////////////
try{
String sql = "SELECT CategoryID,ProductName,Price,Stock FROM products where CategoryID = 2 HAVING Stock >= 1";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
jTable5.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jRadioButton18ActionPerformed
private void jRadioButton19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton19ActionPerformed
//////////////////////////////// สินค้าประเภท ชุดไฟ ////////////////////////
try{
String sql = "SELECT CategoryID,ProductName,Price,Stock FROM products where CategoryID = 3 HAVING Stock >= 1";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
jTable5.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jRadioButton19ActionPerformed
private void jRadioButton20ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton20ActionPerformed
//////////////////////////////// สินค้าประเภท อุปกรณ์เสริม ////////////////////////
try{
String sql = "SELECT CategoryID,ProductName,Price,Stock FROM products where CategoryID = 4 HAVING Stock >= 1";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
jTable5.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jRadioButton20ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
//////////////////////////////// สินค้าประเภท เก็บประวัติลูกค้า ////////////////////////
try{
String sql = "INSERT INTO customer (Cus_name,Phone,Address) VALUES (?,?,?)";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, name.getText());
stmt.setString(2, phone.getText());
stmt.setString(3, address.getText());
stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "การเพิ่มข้อมูลสำเร็จ","กรอกข้อมูลลูกค้า",JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {e.printStackTrace();}
name.setText("");
phone.setText("");
address.setText("");
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
//////////////////////////////// สินค้าประเภท ค้นหาข้อมูลลูกค้า ////////////////////////
try
{
String sql = "select Cus_id,Cus_name from customer where Phone = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, findphone.getText());
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
id.setText(rs.getString("Cus_id"));
nameproduct.setText(rs.getString("Cus_name"));
}
else{
JOptionPane.showMessageDialog(this,"เบอร์โทรศัพท์ไม่ถูกต้อง");
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);}
}//GEN-LAST:event_jButton7ActionPerformed
private void jTable5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable5MouseClicked
//////////////////////////////// สินค้าประเภท เลือกสินค้าในตาราง Product ////////////////////////
DefaultTableModel model = (DefaultTableModel)jTable5.getModel();
int row = jTable5.getSelectedRow();
Order_type.setText(model.getValueAt(row, 0).toString());
Order_name.setText(model.getValueAt(row, 1).toString());
Order_price.setText(model.getValueAt(row, 2).toString());
}//GEN-LAST:event_jTable5MouseClicked
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
//////////////////////////////// เพิ่มสินค้าไปยัง table : Order ////////////////////////
date = ((JTextField)date_chooser.getDateEditor().getUiComponent()).getText();
cus_id = id.getText();
int qty = Integer.parseInt(Order_quantity.getValue().toString());
try{
String sql = "INSERT INTO orders (CategoryID,ProductName,Price,Quantity,Total,Date,Cus_id) VALUES (?,?,?,?,?,?,?)";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, Order_type.getText());
stmt.setString(2, Order_name.getText());
stmt.setString(3, Order_price.getText());
stmt.setString(4, ""+qty);
stmt.setString(5, total.getText());
stmt.setString(6, date);
stmt.setString(7, cus_id);
stmt.executeUpdate();
countinsert++;
JOptionPane.showMessageDialog(null, "ทำรายการสำเร็จ","รายการสั่งซื้อ",JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {e.printStackTrace();
JOptionPane.showMessageDialog(null, "การทำรายการผิดพลาด","เกิดข้อผิดพลาด",JOptionPane.INFORMATION_MESSAGE);
}
Order_type.setText("");
Order_name.setText("");
total.setText("");
}//GEN-LAST:event_jButton13ActionPerformed
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
//////////////////////////////// Confirm สินค้า ////////////////////////
activer(Confirm);
try
{
showTable();
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jButton9ActionPerformed
private void jTableconfirmeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableconfirmeMouseClicked
//////////////////////////////// เลือกรายการใน jTableconfirm ////////////////////////
DefaultTableModel model = (DefaultTableModel)jTableconfirme.getModel();
int row = jTableconfirme.getSelectedRow();
Confirm_name.setText(model.getValueAt(row, 1).toString());
Confirm_price.setText(model.getValueAt(row, 2).toString());
Confirm_quantity.setText(model.getValueAt(row, 3).toString());
Confirm_total.setText(model.getValueAt(row, 4).toString());
}//GEN-LAST:event_jTableconfirmeMouseClicked
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
//////////////////////////////// ยืนยันออเดอร์ ////////////////////////
try{
int row = 0;
String sql = "UPDATE `products` SET `Stock`= ? where ProductName = ?";
PreparedStatement stmt = c.prepareStatement(sql);
for(int n=0;n<countinsert;n++){
String Name = jTableconfirme.getModel().getValueAt(row,1).toString();
String quantity = jTableconfirme.getModel().getValueAt(row,3).toString();
String stock = jTableconfirme.getModel().getValueAt(row,5).toString();
Double numstock = Double.parseDouble(stock);
Double numquantity = Double.parseDouble(quantity);
double sum = numstock-numquantity;
stmt.setString(1, ""+sum);
stmt.setString(2, Name);
stmt.execute();
row++;
}
JOptionPane.showMessageDialog(null, "ส่งรายการออเดอร์แล้ว");
}catch (Exception e) {e.printStackTrace();}
}//GEN-LAST:event_jButton2MouseClicked
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
//////////////////////////////// แก้ไขรายการสินค้าใน หน้า Confirm ////////////////////////
try{
int quantity = Integer.parseInt(Confirm_quantity.getText());
int price = Integer.parseInt(Confirm_price.getText());
double total = quantity*price;
String sql = "UPDATE `orders` SET `Quantity`= ?,`Total`= ? where ProductName = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, Confirm_quantity.getText());
stmt.setString(2, ""+total);
stmt.setString(3, Confirm_name.getText());
stmt.execute();
JOptionPane.showMessageDialog(null, "แก้ไขรายการแล้ว");
}catch (Exception e) {e.printStackTrace();}
showTable();
Confirm_name.setText("");
Confirm_price.setText("");
Confirm_total.setText("");
Confirm_quantity.setText("");
}//GEN-LAST:event_jButton12ActionPerformed
private void jButton9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton9MouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_jButton9MouseClicked
private void jButton5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton5MouseClicked
//////////////////////////////// ชำระเงินพร้อม ////////////////////////
double money_in = Double.parseDouble(payment_input.getText());
double money_out = money_in-totalresource;
payment_output.setText(""+money_out);
Bill();
}//GEN-LAST:event_jButton5MouseClicked
private void Order_quantityStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_Order_quantityStateChanged
//////////////// คิดราคาสินค้าอัตโนมัต ////////////////
int qty = Integer.parseInt(Order_quantity.getValue().toString());
int price = Integer.parseInt(Order_price.getText());
double total1 = qty*price;
total.setText(String.valueOf(total1));
}//GEN-LAST:event_Order_quantityStateChanged
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
try
{
showbill.print();
JOptionPane.showMessageDialog(null, "ออกใบเสร็จแล้ว");
}catch(Exception e){}
payment_input.setText("");
payment_output.setText("");
}//GEN-LAST:event_jButton8ActionPerformed
private void jButton15MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton15MouseClicked
activer(Manage);
showproduct();
}//GEN-LAST:event_jButton15MouseClicked
private void jTableupdateMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableupdateMouseClicked
////////////////// แก้ไข คลังสินค้า ///////////////////////
DefaultTableModel model = (DefaultTableModel)jTableupdate.getModel();
int row = jTableupdate.getSelectedRow();
Product_no = jTableupdate.getModel().getValueAt(row,0).toString();
type1.setText(model.getValueAt(row, 1).toString());
typename.setText(model.getValueAt(row, 2).toString());
name1.setText(model.getValueAt(row, 3).toString());
price1.setText(model.getValueAt(row,4).toString());
stock1.setText(model.getValueAt(row, 5).toString());
}//GEN-LAST:event_jTableupdateMouseClicked
private void jButton6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton6MouseClicked
/////// อัพเดต table jtableupdate ////////////
try{
String sql = "UPDATE `products` SET `CategoryID`= ?,`CategoryName`= ?,`ProductName`= ? ,`Price`= ?,`Stock`= ? WHERE Product_no = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, type1.getText());
stmt.setString(2, typename.getText());
stmt.setString(3, name1.getText());
stmt.setString(4, price1.getText());
stmt.setString(5, stock1.getText());
stmt.setString(6, Product_no);
stmt.execute();
JOptionPane.showMessageDialog(null, "แก้ไขข้อมูลสินค้าแล้ว");
}catch (Exception e) {e.printStackTrace();}
showproduct();
type1.setText("");
name1.setText("");
price1.setText("");
stock1.setText("");
typename.setText("");
}//GEN-LAST:event_jButton6MouseClicked
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
/////// ลบสินค้า ในตาราง jTableupdate ///////////
try{
int row = jTableupdate.getSelectedRow();
String pname = jTableupdate.getModel().getValueAt(row,2).toString();
String sql = "DELETE FROM `products` WHERE ProductName = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, pname);
stmt.execute();
JOptionPane.showMessageDialog(null, "ลบข้อมูลสินค้าแล้ว");
}catch (Exception e) {e.printStackTrace();}
showproduct();
}//GEN-LAST:event_jButton1MouseClicked
private void searchtxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchtxtKeyReleased
///////////////// ค้นหา /////////////////////
String txt = searchtxt.getText();
try{
if(txt.isEmpty()){
showproduct();
}else{
String sql = "SELECT * FROM products where ProductName = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, txt);
ResultSet rs = stmt.executeQuery();
jTableupdate.setModel(DbUtils.resultSetToTableModel(rs));
}
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_searchtxtKeyReleased
private void jButton17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton17ActionPerformed
////////////////////////// ลบสินค้า หน้า confrime //////////////////////////
try{
int row = jTableconfirme.getSelectedRow();
String pname = jTableconfirme.getModel().getValueAt(row,1).toString();
String sql = "DELETE FROM `orders` WHERE ProductName = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, pname);
stmt.execute();
JOptionPane.showMessageDialog(null, "ลบข้อมูลสินค้าแล้ว");
}catch (Exception e) {e.printStackTrace();}
showTable();
countinsert--;
}//GEN-LAST:event_jButton17ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed
private void jRadioButton5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jRadioButton5MouseClicked
try{
String sql = "SELECT * FROM customer";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
jTableexcel.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jRadioButton5MouseClicked
private void jRadioButton6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jRadioButton6MouseClicked
try{
String sql = "SELECT * FROM login";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
jTableexcel.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jRadioButton6MouseClicked
private void jRadioButton7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jRadioButton7MouseClicked
try{
String sql = "SELECT * FROM orders";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
jTableexcel.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jRadioButton7MouseClicked
private void jRadioButton8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jRadioButton8MouseClicked
try{
String sql = "SELECT * FROM products";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
jTableexcel.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jRadioButton8MouseClicked
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
//////////////////// export /////////////////
try{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet1");
DefaultTableModel dtm = (DefaultTableModel) jTableexcel.getModel();
if(jRadioButton5.isSelected()){
String[] colName = {"Cus_id", "Cus_name", "Address", "Phone"};
for (int col = 0; col < 1; col++) {
Row row = sheet.createRow(col);
for (int col2 = 0; col2 < colName.length; col2++) {
String v = (String) colName[col2];
Cell c = row.createCell(col2);
c.setCellValue(v);
}
}
}
if(jRadioButton6.isSelected()){
String[] colName = {"Log_id", "Log_name", "Username", "Password", "Status"};
for (int col = 0; col < 1; col++) {
Row row = sheet.createRow(col);
for (int col2 = 0; col2 < colName.length; col2++) {
String v = (String) colName[col2];
Cell c = row.createCell(col2);
c.setCellValue(v);
}
}
}
if(jRadioButton7.isSelected()){
String[] colName = {"Order_id", "CategoryID", "ProductName", "Price", "Quantity", "Total", "Date", "Cus_id"};
for (int col = 0; col < 1; col++) {
Row row = sheet.createRow(col);
for (int col2 = 0; col2 < colName.length; col2++) {
String v = (String) colName[col2];
Cell c = row.createCell(col2);
c.setCellValue(v);
}
}
}
if(jRadioButton8.isSelected()){
String[] colName = {"Product_no", "CategoryID", "CategoryName", "ProductName", "Price", "Stock"};
for (int col = 0; col < 1; col++) {
Row row = sheet.createRow(col);
for (int col2 = 0; col2 < colName.length; col2++) {
String v = (String) colName[col2];
Cell c = row.createCell(col2);
c.setCellValue(v);
}
}
}
for (int i = 1; i < dtm.getRowCount()+1; i++) {
Row row = sheet.createRow(i);
for (int j = 0; j < dtm.getColumnCount(); j++) {
String v = String.valueOf(dtm.getValueAt(i - 1, j));
Cell c = row.createCell(j);
c.setCellValue(v);
}
}
String FILE_NAME = "D:/export file excel.xlsx";
FileOutputStream fos = new FileOutputStream(FILE_NAME);
workbook.write(fos);
workbook.close();
JOptionPane.showMessageDialog(rootPane, "เก็บข้อมูลไปยัง D:/export file excel.xlsx");
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jButton10ActionPerformed
private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed
activer(dataanalyze);
try{
String sql = "SELECT * FROM orders";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}//GEN-LAST:event_jButton14ActionPerformed
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
int Jan = 1;
int Feb = 2;
int March = 3;
int April =4;
int May =5;
int June =6;
int July = 7;
int Au = 8;
int Sep =9;
int Oc =10;
int Nov =11;
int De =12;
if(jComboBox1.getSelectedIndex()==0){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==1){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Jan);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Jan);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==2){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Feb);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Feb);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==3){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+March);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+March);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==4){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+April);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+April);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==5){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+May);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+May);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==6){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+June);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+June);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==7){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+July);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+July);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==8){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Au);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Au);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==9){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Sep);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Sep);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==10){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Oc);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Oc);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==11){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Nov);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+Nov);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}else if(jComboBox1.getSelectedIndex()==12){
try
{
String sql = " SELECT SUM(Total),SUM(Quantity) FROM orders WHERE MONTH(Date) = ? and YEAR(Date) = ? ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+De);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
sumquantity.setText(rs.getString("SUM(Quantity)"));
sumtotal.setText(rs.getString("SUM(Total)"));
}
}catch(Exception e){e.printStackTrace();}
try{
String sql = "SELECT * FROM orders where MONTH(Date) = ? and YEAR(Date) = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1,""+De);
stmt.setString(2,year1.getText());
ResultSet rs = stmt.executeQuery();
jTableanalyze.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){e.printStackTrace();}
}
}//GEN-LAST:event_jComboBox1ActionPerformed
private void jLabel43MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel43MouseClicked
Login_sa login = new Login_sa();
login.setVisible(true);
this.setVisible(false);
this.dispose();
}//GEN-LAST:event_jLabel43MouseClicked
private void jLabel42MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel42MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel42MouseClicked
private void jLabel55MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel55MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel55MouseClicked
private void jLabel54MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel54MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel54MouseClicked
private void jLabel56MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel56MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel56MouseClicked
private void jLabel57MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel57MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel57MouseClicked
private void jLabel58MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel58MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel58MouseClicked
private void jLabel59MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel59MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel59MouseClicked
private void jLabel60MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel60MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel60MouseClicked
private void jLabel61MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel61MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel61MouseClicked
private void jLabel62MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel62MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel62MouseClicked
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel Band;
private javax.swing.JLabel Band1;
private javax.swing.JPanel Bar;
private javax.swing.JLabel Bar_Tap;
private javax.swing.JPanel Black;
private javax.swing.JInternalFrame Choice_manage;
private javax.swing.JLabel Closetap;
private javax.swing.JInternalFrame Confirm;
private javax.swing.JTextField Confirm_name;
private javax.swing.JTextField Confirm_price;
private javax.swing.JTextField Confirm_quantity;
private javax.swing.JTextField Confirm_total;
private javax.swing.JPanel Confirmed;
private javax.swing.JInternalFrame Export_excel;
private javax.swing.JInternalFrame Input_product;
private javax.swing.JPanel Mainmenu;
private javax.swing.JInternalFrame Manage;
private javax.swing.JLabel Name_Em;
private javax.swing.JInternalFrame Order;
private javax.swing.JTextField Order_name;
private javax.swing.JTextField Order_price;
private javax.swing.JSpinner Order_quantity;
private javax.swing.JTextField Order_type;
private javax.swing.JInternalFrame Payment;
private javax.swing.JLabel Profile;
private javax.swing.JInternalFrame Register;
private javax.swing.JPanel SetOrder;
private javax.swing.JPanel Setanalyze;
private javax.swing.JPanel Setchoicemanage;
private javax.swing.JPanel Setexcel;
private javax.swing.JPanel Setmanagement;
private javax.swing.JPanel Setpayment;
private javax.swing.JPanel Setregister;
private javax.swing.JLabel Status;
private javax.swing.JLabel Status1;
private javax.swing.JTextArea address;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.JInternalFrame dataanalyze;
private com.toedter.calendar.JDateChooser date_chooser;
private javax.swing.JLabel fameblack;
private javax.swing.JLabel famelogo;
private javax.swing.JTextField findphone;
private javax.swing.JPanel gg;
private javax.swing.JLabel id;
private javax.swing.JTextField input;
private javax.swing.JPanel inputdata;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton17;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel35;
private javax.swing.JLabel jLabel36;
private javax.swing.JLabel jLabel37;
private javax.swing.JLabel jLabel38;
private javax.swing.JLabel jLabel39;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel40;
private javax.swing.JLabel jLabel41;
private javax.swing.JLabel jLabel42;
private javax.swing.JLabel jLabel43;
private javax.swing.JLabel jLabel44;
private javax.swing.JLabel jLabel45;
private javax.swing.JLabel jLabel46;
private javax.swing.JLabel jLabel47;
private javax.swing.JLabel jLabel48;
private javax.swing.JLabel jLabel49;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel50;
private javax.swing.JLabel jLabel51;
private javax.swing.JLabel jLabel52;
private javax.swing.JLabel jLabel53;
private javax.swing.JLabel jLabel54;
private javax.swing.JLabel jLabel55;
private javax.swing.JLabel jLabel56;
private javax.swing.JLabel jLabel57;
private javax.swing.JLabel jLabel58;
private javax.swing.JLabel jLabel59;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel60;
private javax.swing.JLabel jLabel61;
private javax.swing.JLabel jLabel62;
private javax.swing.JLabel jLabel63;
private javax.swing.JLabel jLabel64;
private javax.swing.JLabel jLabel65;
private javax.swing.JLabel jLabel66;
private javax.swing.JLabel jLabel67;
private javax.swing.JLabel jLabel68;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel70;
private javax.swing.JLabel jLabel71;
private javax.swing.JLabel jLabel72;
private javax.swing.JLabel jLabel73;
private javax.swing.JLabel jLabel74;
private javax.swing.JLabel jLabel75;
private javax.swing.JLabel jLabel76;
private javax.swing.JLabel jLabel77;
private javax.swing.JLabel jLabel78;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton17;
private javax.swing.JRadioButton jRadioButton18;
private javax.swing.JRadioButton jRadioButton19;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton20;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JRadioButton jRadioButton4;
private javax.swing.JRadioButton jRadioButton5;
private javax.swing.JRadioButton jRadioButton6;
private javax.swing.JRadioButton jRadioButton7;
private javax.swing.JRadioButton jRadioButton8;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane7;
private javax.swing.JScrollPane jScrollPane8;
private javax.swing.JTable jTable5;
private javax.swing.JTable jTableanalyze;
private javax.swing.JTable jTableconfirme;
private javax.swing.JTable jTableexcel;
private javax.swing.JTable jTablepayment;
private javax.swing.JTable jTableupdate;
private javax.swing.JTextField name;
private javax.swing.JTextField name1;
private javax.swing.JLabel name_Em;
private javax.swing.JLabel name_em2;
private javax.swing.JLabel name_em3;
private javax.swing.JTextField nameproduct;
private javax.swing.JTextField payment_input;
private javax.swing.JTextField payment_output;
private javax.swing.JTextField paymenttxt;
private javax.swing.JTextField phone;
private javax.swing.JTextField price;
private javax.swing.JTextField price1;
private javax.swing.JTextField quantity;
private javax.swing.JTextField searchtxt;
private javax.swing.JTextArea showbill;
private javax.swing.JTextField stock1;
private javax.swing.JTextField sumquantity;
private javax.swing.JTextField sumtotal;
private javax.swing.JPanel tap;
private javax.swing.JTextField total;
private javax.swing.JTextField type1;
private javax.swing.JTextField typename;
private javax.swing.JTextField year1;
// End of variables declaration//GEN-END:variables
}
<file_sep>
package sa;
import java.awt.CardLayout;
import java.sql.*;
import java.sql.Connection;
import javax.swing.JOptionPane;
public class Login_sa extends javax.swing.JFrame {
int action = 0;
public Login_sa() {
initComponents();
c1 = (CardLayout) jPanel1.getLayout();
}
public void close() {
this.setVisible(false);
this.dispose();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
user = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jPasswordField1 = new javax.swing.JPasswordField();
jButton1 = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jPasswordField2 = new javax.swing.JPasswordField();
user1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jPanel5 = new javax.swing.JPanel();
jLabel14 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jComboBox1 = new javax.swing.JComboBox();
jButton3 = new javax.swing.JButton();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setUndecorated(true);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.setBackground(new java.awt.Color(102, 102, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel1.setLayout(new java.awt.CardLayout());
jPanel4.setBackground(new java.awt.Color(102, 102, 255));
jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
user.setFont(new java.awt.Font("Rockwell", 0, 24)); // NOI18N
user.setToolTipText("");
jPanel4.add(user, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 310, 199, -1));
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/employee (1).png"))); // NOI18N
jLabel3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel3MouseClicked(evt);
}
});
jPanel4.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(1070, 550, 130, 110));
jLabel6.setBackground(new java.awt.Color(255, 255, 255));
jLabel6.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("username :");
jPanel4.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 310, -1, -1));
jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/motorcycle (1).png"))); // NOI18N
jPanel4.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, 530, 570));
jLabel4.setBackground(new java.awt.Color(255, 255, 255));
jLabel4.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 48)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Motorcycle \n parts store");
jPanel4.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 180, -1, 43));
jLabel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("X");
jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel1MouseClicked(evt);
}
});
jPanel4.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(1180, 10, 30, 30));
jLabel2.setBackground(new java.awt.Color(255, 255, 255));
jLabel2.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("password :");
jPanel4.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 380, -1, -1));
jPasswordField1.setFont(new java.awt.Font("Rockwell", 0, 24)); // NOI18N
jPanel4.add(jPasswordField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 380, 199, -1));
jButton1.setBackground(new java.awt.Color(0, 0, 0));
jButton1.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 18)); // NOI18N
jButton1.setForeground(new java.awt.Color(255, 255, 255));
jButton1.setText("Login");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel4.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(750, 470, 162, 56));
jPanel1.add(jPanel4, "card12");
jPanel2.setBackground(new java.awt.Color(102, 102, 255));
jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel10.setBackground(new java.awt.Color(255, 255, 255));
jLabel10.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 48)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("add employee ");
jPanel2.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 60, -1, 43));
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel7.setBackground(new java.awt.Color(255, 255, 255));
jLabel7.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 51, 102));
jLabel7.setText("CEO Only");
jPanel3.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 40, -1, 43));
jLabel8.setBackground(new java.awt.Color(255, 255, 255));
jLabel8.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel8.setText("username :");
jPanel3.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 130, -1, -1));
jLabel9.setBackground(new java.awt.Color(255, 255, 255));
jLabel9.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel9.setText("password :");
jPanel3.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 190, -1, -1));
jPasswordField2.setFont(new java.awt.Font("Rockwell", 0, 24)); // NOI18N
jPanel3.add(jPasswordField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 190, 199, -1));
user1.setFont(new java.awt.Font("Rockwell", 0, 24)); // NOI18N
user1.setToolTipText("");
jPanel3.add(user1, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 130, 199, -1));
jButton2.setBackground(new java.awt.Color(0, 0, 0));
jButton2.setFont(new java.awt.Font("Copperplate Gothic Bold", 1, 18)); // NOI18N
jButton2.setForeground(new java.awt.Color(255, 255, 255));
jButton2.setText("Login");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel3.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 260, 144, 53));
jPanel2.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 140, 530, 380));
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel14.setBackground(new java.awt.Color(255, 255, 255));
jLabel14.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel14.setText("Employee name :");
jPanel5.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 80, -1, -1));
jLabel11.setBackground(new java.awt.Color(255, 255, 255));
jLabel11.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel11.setText("Username :");
jPanel5.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 140, -1, -1));
jLabel12.setBackground(new java.awt.Color(255, 255, 255));
jLabel12.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel12.setText("Password :");
jPanel5.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 200, -1, -1));
jLabel13.setBackground(new java.awt.Color(255, 255, 255));
jLabel13.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 24)); // NOI18N
jLabel13.setText("Status :");
jPanel5.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 260, -1, -1));
jTextField1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField1.setEnabled(false);
jPanel5.add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 88, 200, 30));
jTextField2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField2.setEnabled(false);
jPanel5.add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 140, 200, 30));
jTextField3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField3.setEnabled(false);
jPanel5.add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 200, 200, 30));
jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " -Select-", "Admin", "CEO ", " " }));
jComboBox1.setEnabled(false);
jPanel5.add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 260, 180, 28));
jButton3.setBackground(new java.awt.Color(0, 0, 0));
jButton3.setFont(new java.awt.Font("Copperplate Gothic Bold", 1, 18)); // NOI18N
jButton3.setForeground(new java.awt.Color(255, 255, 255));
jButton3.setText("ADD");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jPanel5.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 320, 130, 40));
jPanel2.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 140, 580, 380));
jLabel15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/layout.png"))); // NOI18N
jLabel15.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel15MouseClicked(evt);
}
});
jPanel2.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(1130, 580, 70, 80));
jLabel16.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/Picture/back (1).png"))); // NOI18N
jLabel16.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel16MouseClicked(evt);
}
});
jPanel2.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 580, -1, -1));
jLabel17.setBackground(new java.awt.Color(255, 255, 255));
jLabel17.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 36)); // NOI18N
jLabel17.setForeground(new java.awt.Color(255, 255, 255));
jLabel17.setText("X");
jLabel17.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel17MouseClicked(evt);
}
});
jPanel2.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(1180, 10, 30, 30));
jPanel1.add(jPanel2, "card3");
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1230, 680));
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try
{
Connection c = Conection.getConnection();
String sql = "select * from login where username = ? and password = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, user.getText());
stmt.setString(2, String.valueOf(jPasswordField1.getPassword()));
ResultSet rs = stmt.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null,"ล็อกอินสำเร็จ");
// main main = new main();
String msg = user.getText();
new Main(msg).setVisible(true);
close();
// main.setVisible(true);
}else{
JOptionPane.showMessageDialog(null,"ล็อกอิน ล้มเหลว!");
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel1MouseClicked
private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked
c1.show(jPanel1, "card3");
}//GEN-LAST:event_jLabel3MouseClicked
private void jLabel17MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel17MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel17MouseClicked
private void jLabel16MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel16MouseClicked
c1.first(jPanel1);
}//GEN-LAST:event_jLabel16MouseClicked
private void jLabel15MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel15MouseClicked
if(action == 1){
Main main = new Main();
main.setVisible(true);
close();
//
String msg = user1.getText();
new Main(msg).setVisible(true);
}else
{
JOptionPane.showMessageDialog(null,"ต้องล็อกอินก่อน !");
}
}//GEN-LAST:event_jLabel15MouseClicked
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
try
{
Connection c = Conection.getConnection();
String sql = "select * from login where username = ? and password = ? and Status = ?";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, user1.getText());
stmt.setString(2, String.valueOf(jPasswordField2.getPassword()));
stmt.setString(3, "CEO");
ResultSet rs = stmt.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null,"ล็อกอินสำเร็จ");
jTextField1.setEnabled(true);
jTextField2.setEnabled(true);
jTextField3.setEnabled(true);
jComboBox1.setEnabled(true);
action = 1;
}else{
JOptionPane.showMessageDialog(null,"จำกัดการใช้แค่ CEO");
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
Connection c = Conection.getConnection();
try{
String sql = "INSERT INTO login (Log_name,Username,Password,Status) VALUES (?,?,?,?)";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, jTextField1.getText());
stmt.setString(2, jTextField2.getText());
stmt.setString(3, jTextField3.getText());
if(jComboBox1.getSelectedIndex()==0){
stmt.setString(4, "Admin");
}
if(jComboBox1.getSelectedIndex()==1){
stmt.setString(4, "CEO");
}
JOptionPane.showMessageDialog(null,"เพิมรหัสพนักงานเรียบร้อย");
stmt.executeUpdate();
} catch (Exception e) {e.printStackTrace();}
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}//GEN-LAST:event_jButton3ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Login_sa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login_sa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login_sa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login_sa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login_sa().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JPasswordField jPasswordField2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField user;
private javax.swing.JTextField user1;
// End of variables declaration//GEN-END:variables
private CardLayout c1;
}
| c65b8754aef2c7299df874e119952c5dc44dec82 | [
"Markdown",
"SQL",
"Java"
] | 4 | Markdown | FzBlackduck/JAVAGUI-Motorcycle_system | 59ee6fd75b824db22656b4234aa3203a76de1c3c | a6cf74f97e68399662b056a81207451a7c6e6f43 |
refs/heads/master | <repo_name>dinith72/DecoratorPattern-DesignPatterns<file_sep>/src/Beverages/Expresso.java
package Beverages;
// concrete implementation of a component
public class Expresso extends Beverage {
@Override
public String description() {
return "Expresso";
}
@Override
public Double cost() {
// this will return value as its components
return 199.0;
}
}
<file_sep>/src/Beverages/Condiments.java
package Beverages;
// all the decorators related to the type is extended from the this class
public abstract class Condiments extends Beverage {
@Override
public abstract String description() ;
@Override
public abstract Double cost() ;
}
| a4d9022f5f39e6c80efa031b042d3fd37224ede4 | [
"Java"
] | 2 | Java | dinith72/DecoratorPattern-DesignPatterns | 692a722dddf875c29e1d20150ee4939fa731c1d8 | d11138ccff95a50e1d585176d74516b97a3cf208 |
refs/heads/main | <repo_name>chfaraz/text-select-with-backend<file_sep>/components/postDetail.js
import React, { useContext, useState } from 'react';
const PostDetail = ({ title, img, img2 }) => {
const [state, setstate] = useState('');
return (
<div className="w-full mx-auto">
<div className="">
<img src={img} className="w-full h-auto" />
</div>
<h1 className="text-[44px] font-bold my-[10px]">{title}</h1>
<div className="flex">
<div className="p-[20px] w-[75%]">
<h2 className="text-[30px] font-bold bg-[#38c7b2] text-white w-[50%] mb-[10px]">What it is?</h2>
<p className="text-[20px] w-[75%] ">
Etiam dapibus volutpat felis at mollis. Nam ligula nisi, facilisis in libero iaculis, blandit tincidunt ipsum. Donec lorem sapien, lobortis quis efficitur et, sollicitudin ut turpis. Aliquam eu lacus at augue imperdiet ornare in quis ligula. Praesent posuere libero lectus, id ornare lacus molestie vel. Curabitur semper suscipit congue. Phasellus in mi enim. Suspendisse imperdiet porta odio. Mauris fermentum nibh libero, quis semper ipsum tempor sed. Sed in nibh purus. Integer vestibulum et urna sit amet accumsan. Aenean auctor lorem in eros tincidunt, vitae porttitor
neque imperdiet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
</p>
<h2 className="text-[30px] font-bold bg-[#38c7b2] text-white w-[75%] mt-[25px] mb-[10px]">Dificult But Lets Try To Understand!</h2>
<p className="text-[20px] w-[75%]">Duis tristique rhoncus maximus. Etiam blandit justo eros, sed mattis neque sollicitudin eu. Nunc at ligula ipsum. Fusce sit amet leo odio. Sed finibus at est quis laoreet. Aliquam viverra lacinia ligula ac dapibus. Nunc accumsan nulla mi, id gravida dolor varius id. Vestibulum mollis porttitor fringilla. Maecenas sollicitudin eros ac enim consequat finibus. Aliquam vehicula mauris in libero sagittis, at venenatis velit eleifend. Quisque bibendum mauris leo, facilisis tincidunt leo vestibulum sed. Quisque fringilla sagittis porttitor.</p>
<h2 className="text-[30px] font-bold bg-[#38c7b2] text-white w-[100%] mt-[25px] mb-[10px]">Take aways:</h2>
<p className="text-[20px] w-[75%]">Proin ac ante semper, malesuada nulla vel, varius ex. Morbi aliquam mollis hendrerit. Donec lobortis dolor quis turpis euismod, id scelerisque tellus fringilla. Phasellus fermentum venenatis felis sit amet rhoncus. Integer eu molestie urna, eu venenatis turpis. Donec velit eros, fermentum ac elit eget, luctus porttitor tortor. Suspendisse placerat nisl non sem laoreet, non posuere magna egestas.</p>
</div>
<div className="w-[25%]">
<img src={img2} className="w-full h-auto" />
</div>
</div>
</div>
);
};
export default PostDetail;
<file_sep>/public/index.js
import React, { useEffect, useState } from 'react';
import PostDetail from '../../components/postDetail';
import { gql, useQuery } from '@apollo/client';
import { useRouter } from 'next/router';
import { useAppContext } from '../../state';
import Post from '../../components/post';
const GET_MOVIES = gql`
query episodesByIds($id: [ID!]!) {
episodesByIds(ids: $id) {
id
name
air_date
episode
}
}
`;
const PostInfo = () => {
const dataa = useAppContext();
const router = useRouter();
const id = router.query.pid;
let movies;
console.log(router.query);
if (dataa.length !== 0) {
movies = dataa.find((e) => e.id === id);
console.log(dataa);
} else {
const { loading, data } = useQuery(GET_MOVIES, {
variables: { id: id },
});
console.log('ifaaaaaaaaaaaaaaaaaaaaaaa', data);
if (loading) return null;
movies = data.episodesByIds[0];
}
return (
<div>
<Post img={`${router.query.img}.webp`} h title={movies.name} time={movies.air_date} episode={movies.episode} />
{/* <PostDetail img="http://c.files.bbci.co.uk/4ABA/production/_117803191_gettyimages-1232003438.jpg" title="Art or just a crap?" img2="https://i.pinimg.com/originals/66/59/44/665944970605ed2273788a068895ea39.jpg" /> */}
</div>
);
};
export default PostInfo;
<file_sep>/pages/api/delete.js
import nextConnect from 'next-connect';
import middleware from '../../middleware/database';
var ObjectId = require('mongodb').ObjectID;
const handler = nextConnect();
handler.use(middleware);
handler.post(async (req, res) => {
let data = req.body;
let doc = await req.db.collection('posts').deleteOne({ selectedText: data.selectedText });
res.status(200).json({ message: 'ok' });
});
export default handler;
<file_sep>/components/post.js
import React from 'react';
const Post = ({ title, img, episode, time, h }) => {
return (
<section className={`bg-white rounded-md shadow-md overflow-hidden ${h ? 'mx-auto my-[50px] w-[80%]' : null}`}>
<div className={`w-full ${h ? 'h-auto' : 'h-[200px]'} overflow-hidden`}>
<img src={img} className="w-full h-auto" alt="Blog image" />
</div>
<h1 className="text-[25px] my-[10px]">{title}</h1>
<div className="flex justify-between px-[20px] mb-[20px]">
<p className="text-[12px]">Episode: {episode}</p>
<p className="text-[12px]">Date: {time}</p>
</div>
</section>
);
};
export default Post;
<file_sep>/components/popup.js
import React, { useState, useEffect, useRef } from 'react';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import axios from 'axios';
const popup = (props) => {
const [text, setText] = useState('');
const [error, setError] = useState(false);
const closePopup = () => {
props.setPopup(false);
setText('');
setError(false);
};
const setData = (e) => {
if (text !== '') {
const found = props.state.find((data) => props.selection === data.selectedText);
console.log(found);
found === undefined
? axios
.post('/api/postData', {
writtenText: text,
selectedText: props.selection,
})
.then(function (response) {
props.setState(
props.state.concat({
writtenText: text,
selectedText: props.selection,
})
);
})
.catch(function (error) {
console.log(error);
})
: toast.error('Please Delete The Previous One First!', {
position: 'top-right',
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
props.setPopup(false);
} else {
console.log('please enter some text');
setError(true);
}
var ele = document.getElementById('aa');
ele.style.display = 'none';
setText('');
};
const handleChange = (e) => {
setText(e.target.value);
setError(false);
};
return (
<div id="popup">
<Card className="">
<CardContent>
<TextField id="outlined-multiline-static" helperText={error ? "Can't be empty" : null} error={error} onChange={(e) => handleChange(e)} label="Enter Some Text" multiline rows={4} defaultValue="" variant="outlined" />
</CardContent>
<CardActions>
<div className="buttons">
<Button variant="contained" color="secondary" onClick={closePopup}>
Close
</Button>
<Button variant="contained" color="primary" onClick={(e) => setData(e)}>
Add
</Button>
</div>
</CardActions>
</Card>
</div>
);
};
export default popup;
<file_sep>/pages/index.js
import React, { useEffect, useState } from 'react';
import Post from '../components/post';
import Link from 'next/link';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import client from '../apollo-client';
import { gql } from '@apollo/client';
import { useRouter } from 'next/router';
import { useAppContext } from '../state';
const Posts = ({ data }) => {
const dataa = useAppContext();
console.log(dataa);
const [movies, setMovies] = useState(data.episodesByIds);
const router = useRouter();
useEffect(async () => {
if (dataa.length !== 0) {
console.log('if--------------------');
setMovies(dataa);
} else {
console.log('fetch your self');
const { data } = await client.query({
query: gql`
query {
episodesByIds(ids: [3, 4, 5, 6, 7, 8]) {
id
name
air_date
episode
}
}
`,
});
setMovies(data.episodesByIds);
}
}, []);
// const data = await res.json();
console.log(movies);
return (
<>
<AppBar position="static">
<Toolbar variant="dense">
<IconButton edge="start" className="" color="inherit" aria-label="menu">
<MenuIcon />
</IconButton>
<Typography variant="h6" color="inherit">
<Link href="/postInfo">Posts</Link>
</Typography>
</Toolbar>
</AppBar>
<div className="grid grid-cols-3 gap-[15px] p-[15px] bg-[#d5d5d5]">
{movies.map((movie, i) => {
return (
<div
key={i}
onClick={() =>
router.push({
pathname: '/postInfo/[pid]',
query: { pid: movie.id },
})
}
className="cursor-pointer"
>
<Post img={`${i + 1}.webp`} title={movie.name} time={movie.air_date} episode={movie.episode} />
</div>
);
})}
</div>
</>
);
};
export async function getServerSideProps() {
const { data } = await client.query({
query: gql`
query {
episodesByIds(ids: [3, 4, 5, 6, 7, 8]) {
id
name
air_date
episode
}
}
`,
});
return {
props: {
data,
},
};
}
export default Posts;
<file_sep>/state.js
import { createContext, useContext, useEffect, useState } from 'react';
import client from './apollo-client';
import { gql } from '@apollo/client';
const AppContext = createContext();
export function AppWrapper({ children, data }) {
const [state, setstate] = useState('');
useEffect(() => {
client
.query({
query: gql`
query {
episodesByIds(ids: [3, 4, 5, 6, 7, 8]) {
id
name
air_date
episode
}
}
`,
})
.then((data) => setstate(data.data.episodesByIds));
}, []);
return <AppContext.Provider value={state}>{children}</AppContext.Provider>;
}
export function useAppContext() {
return useContext(AppContext);
}
export async function getServerSideProps() {
const { data } = await client.query({
query: gql`
query {
episodesByIds(ids: [3, 4, 5, 6, 7, 8]) {
id
name
air_date
episode
}
}
`,
});
return {
props: {
data,
},
};
}
| 7355a262b9eefe4a717e0fe04148ad751e1bbb7a | [
"JavaScript"
] | 7 | JavaScript | chfaraz/text-select-with-backend | 42d10c23b9ae8218857290aa0cb062cb3a9fe899 | e88eb43a565453b25eb6000cca63ea698f8edb59 |
refs/heads/master | <repo_name>madc0w/doodles<file_sep>/init_doodles.js
function init() {
subDir = 'doodles';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 18-01-2015.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 17-04-2015.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 02-11-2014.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 14-11-2014.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 09-11-2014.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 03-29-2014.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 04-26-2014.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 2014-10-07.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 23-03-2014.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 14-12-2013.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 08-12-2013.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 18-11-2013.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 27-07-2013.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 21-07-2013.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 19-05-2013.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 06-07-2013.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 08-05-2013.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 01-05-2013.png';
isMouseOver[images.length] = true;
images[images.length] = 'doodle 28-04-2013.png';
isMouseOver[images.length] = false;
images[images.length] = 'doodler output 02-06-2013.PNG';
isMouseOver[images.length] = true;
images[images.length] = 'out2.png';
isMouseOver[images.length] = true;
images[images.length] = 'squiddy squiggle 30-06-2013.png';
isMouseOver[images.length] = false;
images[images.length] = 'squiggleface.PNG';
}
<file_sep>/portfolio.js
var isMouseOver = new Array();
var images = new Array();
var subDir;
init();
function displayAsBookmarks() {
displayImages(1);
}
function loadContactSheet() {
displayImages(3);
}
function displayImages(numCols) {
var imagesTable = document.getElementById('images');
var imagesTableHtml = '';
for (var i = 0; i < images.length; i++) {
var image = images[i];
if (i % numCols == 0) {
if (i > 0) {
imagesTableHtml += '</tr>';
}
imagesTableHtml += '<tr>';
}
imagesTableHtml += '<td>';
imagesTableHtml += '<img src="images/' + subDir + '/filled/' + image + '"/><br/>\n';
imagesTableHtml += '<div class="doodlesLink"><a href="https://fofolabs.com/doodles">fofolabs.com/doodles</a></div>';
imagesTableHtml += '</td>';
}
imagesTableHtml += '</tr>';
imagesTable.innerHTML = imagesTableHtml;
}
function load() {
var imagesDiv = document.getElementById('images');
var imagesDivHtml = '';
for (var i = 0; i < images.length; i++) {
var image = images[i];
imagesDivHtml += '<div class="imageDiv"><img id="image' + i + '" ';
if (isMouseOver.length > i && isMouseOver[i]) {
imagesDivHtml += 'onMouseOver="mouseOverImage(this);" onMouseOut="mouseOutImage(this);" ';
}
imagesDivHtml += 'src="images/' + subDir + '/filled/' + image + '"/>\n';
imagesDivHtml += '<div class="orderLink"><a href="mailto:<EMAIL>?subject=Order: ' + image
+ '&body=I would like to order this print, please.">Click here to order a print of this image.</a></div>';
imagesDivHtml += '</div>\n';
}
imagesDiv.innerHTML = imagesDivHtml;
if (isMouseOver.length > 0) {
var preloadCount = 0;
var preloadedCount = 0;
for (var i = 0; i < images.length; i++) {
if (isMouseOver.length > i && isMouseOver[i]) {
preloadCount++;
var img = new Image();
img.src = 'images/' + subDir + '/original/' + images[i];
img.onload = function () {
preloadedCount++;
if (preloadedCount == preloadCount) {
document.getElementById('loading').style.display = 'none';
}
};
}
}
}
}
function mouseOverImage(el) {
// $('#' + el.id).fadeOut();
el.src = el.src.replace('/filled/', '/original/');
// $('#' + el.id).fadeIn();
}
function mouseOutImage(el) {
// $('#' + el.id).fadeOut();
el.src = el.src.replace('/original/', '/filled/');
// $('#' + el.id).fadeIn();
}
| 97f904d6729fe92e65add66338b0e01a0f9466a2 | [
"JavaScript"
] | 2 | JavaScript | madc0w/doodles | b05f44e7768ff604cdfef2c10cfc7bc86d97971e | d6d560002fb44fadd3994214f86d5b88e92568d0 |
refs/heads/master | <file_sep># coding=utf-8
import numpy as np
from numpy import *
from numpy import linalg as la
import scipy.io
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.cross_validation import StratifiedKFold
from sklearn.metrics import roc_curve, auc
import argparse
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import ExtraTreesClassifier,AdaBoostClassifier
from xgboost.sklearn import XGBClassifier
def read_fasta_file(fasta_file):
seq_dict = {}
fp = open(fasta_file, 'r')
name = ''
# pdb.set_trace()
for line in fp:
# let's discard the newline at the end (if any)
line = line.rstrip()
# distinguish header from sequence
if line[0] == '>': # or line.startswith('>')
# it is the header
name = line[1:].upper() # discarding the initial >
seq_dict[name] = ''
else:
# it is sequence
seq_dict[name] = seq_dict[name] + line
fp.close()
return seq_dict
def TransDict_from_list(groups):
transDict = dict()
tar_list = ['0', '1', '2', '3', '4', '5', '6']
result = {}
index = 0
for group in groups:
g_members = sorted(group) # Alphabetically sorted list
for c in g_members:
# print('c' + str(c))
# print('g_members[0]' + str(g_members[0]))
result[c] = str(tar_list[index]) # K:V map, use group's first letter as represent.
index = index + 1
return result
def get_3_protein_trids():
nucle_com = []
chars = ['0', '1', '2', '3', '4', '5', '6']
base = len(chars)
end = len(chars) ** 3
for i in range(0, end):
n = i
ch0 = chars[n % base]
n = n / base
ch1 = chars[int(n % base)]
n = n / base
ch2 = chars[int(n % base)]
nucle_com.append(ch0 + ch1 + ch2)
return nucle_com
def get_4_trids():
nucle_com = []
chars = ['A', 'C', 'G', 'U']
base = len(chars)
end = len(chars) ** 4
for i in range(0, end):
n = i
ch0 = chars[n % base]
n = n / base
ch1 = chars[int(n % base)]
n = n / base
ch2 = chars[int(n % base)]
n = n / base
ch3 = chars[int(n % base)]
nucle_com.append(ch0 + ch1 + ch2 + ch3)
return nucle_com
def translate_sequence(seq, TranslationDict):
'''
Given (seq) - a string/sequence to translate,
Translates into a reduced alphabet, using a translation dict provided
by the TransDict_from_list() method.
Returns the string/sequence in the new, reduced alphabet.
Remember - in Python string are immutable..
'''
import string
from_list = []
to_list = []
for k, v in TranslationDict.items():
from_list.append(k)
to_list.append(v)
# TRANS_seq = seq.translate(str.maketrans(zip(from_list,to_list)))
TRANS_seq = seq.translate(str.maketrans(str(from_list), str(to_list)))
# TRANS_seq = maketrans( TranslationDict, seq)
return TRANS_seq
def get_RNA_seq_concolutional_array(seq, motif_len=4):
# data = {}
alpha = 'ACGT'
# for seq in seqs:
# for key, seq in seqs.iteritems():
row = (len(seq) + 2 * motif_len - 2)
new_array = np.zeros((row, 4))
for i, val in enumerate(seq):
if val not in 'ACGTN':
new_array[i] = np.array([0.25] * 4)
continue
if val == 'N' or i < motif_len or i > len(seq) - motif_len:
new_array[i] = np.array([0.25] * 4)
else:
index = alpha.index(val)
new_array[i][index] = 1
# data[key] = new_array
return new_array
def get_4_nucleotide_composition(tris, seq, pythoncount=True):
seq_len = len(seq)
tri_feature = [0] * len(tris)
k = len(tris[0])
note_feature = [[0 for cols in range(len(seq) - k + 1)] for rows in range(len(tris))]
if pythoncount:
for val in tris:
num = seq.count(val)
tri_feature.append(float(num) / seq_len)
else:
# tmp_fea = [0] * len(tris)
for x in range(len(seq) + 1 - k):
kmer = seq[x:x + k]
if kmer in tris:
ind = tris.index(kmer)
# tmp_fea[ind] = tmp_fea[ind] + 1
note_feature[ind][x] = note_feature[ind][x] + 1
# tri_feature = [float(val)/seq_len for val in tmp_fea] #tri_feature type:list len:256
u, s, v = la.svd(note_feature)
for i in range(len(s)):
tri_feature = tri_feature + u[i] * s[i] / seq_len
# print tri_feature
# pdb.set_trace()
return tri_feature
def prepare_RPI488_feature(extract_only_posi=False,
pseaac_file=None, deepmind=False, seperate=False, chem_fea=True):
print ('RPI488 dataset')
dbName = '488.mat'
interaction_pair = {}
RNA_seq_dict = {}
protein_seq_dict = {}
with open('ncRNA-protein/lncRNA-protein-488.txt', 'r') as fp:
for line in fp:
if line[0] == '>':
values = line[1:].strip().split('|')
label = values[1]
name = values[0].split('_')
protein = name[0] + '-' + name[1]
RNA = name[0] + '-' + name[2]
if label == 'interactive':
interaction_pair[(protein, RNA)] = 1
else:
interaction_pair[(protein, RNA)] = 0
index = 0
else:
seq = line[:-1]
if index == 0:
protein_seq_dict[protein] = seq
else:
RNA_seq_dict[RNA] = seq
index = index + 1
# name_list = read_name_from_lncRNA_fasta('ncRNA-protein/lncRNA_RNA.fa')
groups = ['AGV', 'ILFP', 'YMTS', 'HNQW', 'RK', 'DE', 'C']
group_dict = TransDict_from_list(groups)
protein_tris = get_3_protein_trids()
tris = get_4_trids()
# tris3 = get_3_trids()
train = []
label = []
chem_fea = []
proteinFea = []
# get protein feature
tempStruct = scipy.io.loadmat(dbName)
tempfea = tempStruct['fea']
proteinFea = tempfea[0, 0]
protein_index = 0
for key, val in interaction_pair.items():
protein, RNA = key[0], key[1]
# pdb.set_trace()
if RNA in RNA_seq_dict and protein in protein_seq_dict: # and protein_fea_dict.has_key(protein) and RNA_fea_dict.has_key(RNA):
label.append(val)
RNA_seq = RNA_seq_dict[RNA]
protein_seq = translate_sequence(protein_seq_dict[protein], group_dict)
seqName = 'F' + protein
seqName = seqName.replace("-", "_")
# proteinFea[protein_index][0]= proteinFea[protein_index][0]/len(protein_seq)
if deepmind:
RNA_tri_fea = get_RNA_seq_concolutional_array(RNA_seq)
protein_tri_fea = get_RNA_seq_concolutional_array(protein_seq)
train.append((RNA_tri_fea, protein_tri_fea))
else:
# pdb.set_trace()
RNA_tri_fea = get_4_nucleotide_composition(tris, RNA_seq, pythoncount=False)
# protein_tri_fea = get_4_nucleotide_composition(protein_tris, protein_seq, pythoncount =False)
protein_tri_fea = proteinFea[seqName][0]
# RNA_tri3_fea = get_4_nucleotide_composition(tris3, RNA_seq, pythoncount =False)
# RNA_fea = [RNA_fea_dict[RNA][ind] for ind in fea_imp]
# tmp_fea = protein_fea_dict[protein] + tri_fea #+ RNA_fea_dict[RNA]
if seperate:
tmp_fea = (protein_tri_fea, RNA_tri_fea)
# chem_tmp_fea = (protein_fea_dict[protein], RNA_fea_dict[RNA])
else:
tmp_fea = protein_tri_fea + RNA_tri_fea
# chem_tmp_fea = protein_fea_dict[protein] + RNA_fea_dict[RNA]
train.append(tmp_fea)
protein_index = protein_index + 1
# chem_fea.append(chem_tmp_fea)
else:
print (RNA, protein)
return np.array(train), label
def prepare_RPI1807_feature(graph=False, deepmind=False, seperate=False, chem_fea=True, dataset=''):
print('RPI-Pred data')
# name_list = read_name_from_fasta('ncRNA-protein/RNA_seq.fa')
seq_dict = read_fasta_file('ncRNA-protein/RPI1807_RNA_seq.fa')
protein_seq_dict = read_fasta_file('ncRNA-protein/RPI1807_protein_seq.fa')
groups = ['AGV', 'ILFP', 'YMTS', 'HNQW', 'RK', 'DE', 'C']
group_dict = TransDict_from_list(groups)
protein_tris = get_3_protein_trids()
tris = get_4_trids()
# pdb.set_trace()
train = []
label = []
chem_fea = []
tempStruct = scipy.io.loadmat(dataset)
tempfea = tempStruct['fea']
proteinFea = tempfea[0, 0]
# pdb.set_trace()
with open('ncRNA-protein/RPI1807_PositivePairs.csv', 'r') as fp:
for line in fp:
if 'Protein ID' in line:
continue
pro1, pro2 = line.rstrip().split('\t')
# pro1 = pro1.upper()
pro2 = pro2.upper()
if pro2 in seq_dict and pro1 in protein_seq_dict: # and protein_fea_dict.has_key(pro1) and RNA_fea_dict.has_key(pro2):
label.append(1)
RNA_seq = seq_dict[pro2]
protein_seq = translate_sequence(protein_seq_dict[pro1], group_dict)
seqName = 'F' + pro1
seqName = seqName.replace("-", "_")
if deepmind:
RNA_tri_fea = get_RNA_seq_concolutional_array(RNA_seq)
protein_tri_fea = get_RNA_seq_concolutional_array(protein_seq)
train.append((RNA_tri_fea, protein_tri_fea))
else:
RNA_tri_fea = get_4_nucleotide_composition(tris, RNA_seq, pythoncount=False)
protein_tri_fea = proteinFea[seqName][0]
# protein_tri_fea = get_4_nucleotide_composition(protein_tris, protein_seq, pythoncount =False)
# RNA_fea = [RNA_fea_dict[RNA][ind] for ind in fea_imp]
# tmp_fea = protein_fea_dict[protein] + tri_fea #+ RNA_fea_dict[RNA]
if seperate:
tmp_fea = (protein_tri_fea, RNA_tri_fea)
# chem_tmp_fea = (protein_fea_dict[pro1], RNA_fea_dict[pro2])
else:
tmp_fea = protein_tri_fea + RNA_tri_fea
# chem_tmp_fea = protein_fea_dict[pro1] + RNA_fea_dict[pro2]
train.append(tmp_fea)
# chem_fea.append(chem_tmp_fea)
else:
print (pro1, pro2)
with open('ncRNA-protein/RPI1807_NegativePairs.csv', 'r') as fp:
for line in fp:
if 'Protein ID' in line:
continue
pro1, pro2 = line.rstrip().split('\t')
# pro1 = pro1.upper()
pro2 = pro2.upper()
if pro2 in seq_dict and pro1 in protein_seq_dict: # and protein_fea_dict.has_key(pro1) and RNA_fea_dict.has_key(pro2):
label.append(0)
RNA_seq = seq_dict[pro2]
protein_seq = translate_sequence(protein_seq_dict[pro1], group_dict)
seqName = 'F' + pro1
seqName = seqName.replace("-", "_")
if deepmind:
RNA_tri_fea = get_RNA_seq_concolutional_array(RNA_seq)
protein_tri_fea = get_RNA_seq_concolutional_array(protein_seq)
train.append((RNA_tri_fea, protein_tri_fea))
else:
RNA_tri_fea = get_4_nucleotide_composition(tris, RNA_seq, pythoncount=False)
protein_tri_fea = proteinFea[seqName][0]
# protein_tri_fea = get_4_nucleotide_composition(protein_tris, protein_seq, pythoncount =False)
# RNA_fea = [RNA_fea_dict[RNA][ind] for ind in fea_imp]
# tmp_fea = protein_fea_dict[protein] + tri_fea #+ RNA_fea_dict[RNA]
if seperate:
tmp_fea = (protein_tri_fea, RNA_tri_fea)
# chem_tmp_fea = (protein_fea_dict[pro1], RNA_fea_dict[pro2])
else:
tmp_fea = protein_tri_fea + RNA_tri_fea
# chem_tmp_fea = protein_fea_dict[pro1] + RNA_fea_dict[pro2]
train.append(tmp_fea)
# chem_fea.append(chem_tmp_fea)
else:
print(pro1, pro2)
return np.array(train), label
def prepare_RPI2241_369_feature(rna_fasta_file, data_file, protein_fasta_file, extract_only_posi=False,
graph=False, deepmind=False, seperate=False, chem_fea=True, dataset=''):
seq_dict = read_fasta_file(rna_fasta_file)
protein_seq_dict = read_fasta_file(protein_fasta_file)
groups = ['AGV', 'ILFP', 'YMTS', 'HNQW', 'RK', 'DE', 'C']
group_dict = TransDict_from_list(groups)
protein_tris = get_3_protein_trids()
tris = get_4_trids()
train = []
label = []
chem_fea = []
# posi_set = set()
# pro_set = set()
tempStruct = scipy.io.loadmat(dataset)
tempfea = tempStruct['fea']
proteinFea = tempfea[0, 0]
with open(data_file, 'r') as fp:
for line in fp:
if line[0] == '#':
continue
protein, RNA, tmplabel = line.rstrip('\r\n').split('\t')
if RNA in seq_dict and protein in protein_seq_dict:
label.append(int(tmplabel))
RNA_seq = seq_dict[RNA]
protein_seq = translate_sequence(protein_seq_dict[protein], group_dict)
seqName = 'a' + protein
seqName = seqName.replace("-", "_")
if deepmind:
RNA_tri_fea = get_RNA_seq_concolutional_array(RNA_seq)
protein_tri_fea = get_RNA_seq_concolutional_array(protein_seq)
train.append((RNA_tri_fea, protein_tri_fea))
else:
RNA_tri_fea = get_4_nucleotide_composition(tris, RNA_seq, pythoncount=False)
# protein_tri_fea = get_4_nucleotide_composition(protein_tris, protein_seq, pythoncount =False)
protein_tri_fea = proteinFea[seqName][0]
if seperate:
tmp_fea = (protein_tri_fea, RNA_tri_fea)
else:
tmp_fea = protein_tri_fea + RNA_tri_fea
train.append(tmp_fea)
else:
print (RNA, protein)
return np.array(train), label
def get_data_deepmind(dataset, deepmind=False, seperate=True, chem_fea=False, extract_only_posi=False,
indep_test=False):
if dataset == 'RPI2241':
X, labels = prepare_RPI2241_369_feature('ncRNA-protein/RPI2241_rna.fa', 'ncRNA-protein/RPI2241_all.txt',
'ncRNA-protein/RPI2241_protein.fa', graph=False, deepmind=deepmind,
seperate=seperate, chem_fea=chem_fea, dataset='2241.mat')
elif dataset == 'RPI369':
X, labels = prepare_RPI2241_369_feature('ncRNA-protein/RPI369_rna.fa', 'ncRNA-protein/RPI369_all.txt',
'ncRNA-protein/RPI369_protein.fa', graph=False, deepmind=deepmind,
seperate=seperate, chem_fea=chem_fea, dataset='369.mat')
elif dataset == 'RPI488':
X, labels = prepare_RPI488_feature(deepmind=deepmind, seperate=seperate, chem_fea=chem_fea)
elif dataset == 'RPI1807':
X, labels = prepare_RPI1807_feature(graph=False, deepmind=deepmind, seperate=seperate, chem_fea=chem_fea,
dataset='1807.mat')
return X, labels
def plot_roc_curve(labels, probality, legend_text, auc_tag=True):
# fpr2, tpr2, thresholds = roc_curve(labels, pred_y)
fpr, tpr, thresholds = roc_curve(labels, probality) # probas_[:, 1])
roc_auc = auc(fpr, tpr)
if auc_tag:
rects1 = plt.plot(fpr, tpr, label=legend_text + ' (AUC=%6.3f) ' % roc_auc)
else:
rects1 = plt.plot(fpr, tpr, label=legend_text)
def calculate_performace(test_num, pred_y, labels):
tp = 0
fp = 0
tn = 0
fn = 0
for index in range(test_num):
if labels[index] == 1:
if labels[index] == pred_y[index]:
tp = tp + 1
else:
fn = fn + 1
else:
if labels[index] == pred_y[index]:
tn = tn + 1
else:
fp = fp + 1
acc = float(tp + tn) / test_num
precision = float(tp) / (tp + fp)
sensitivity = float(tp) / (tp + fn)
specificity = float(tn) / (tn + fp)
MCC = float(tp * tn - fp * fn) / (np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)))
return acc, precision, sensitivity, specificity, MCC
def transfer_array_format(data):
formated_matrix1 = []
formated_matrix2 = []
for val in data:
formated_matrix1.append(val[0])
formated_matrix2.append(val[1])
return np.array(formated_matrix1), np.array(formated_matrix2)
def transfer_label_from_prob(proba):
label = [1 if val >= 0.5 else 0 for val in proba]
return label
def preprocess_data(X, scaler=None, stand=True):
if not scaler:
if stand:
scaler = StandardScaler()
else:
scaler = MinMaxScaler()
scaler.fit(X)
X = scaler.transform(X)
return X
def get_blend_data(j, clf, skf, X_test, X_dev, Y_dev, blend_train, blend_test):
print ('Training classifier [%s]' % (j))
blend_test_j = np.zeros((X_test.shape[0], len(
skf))) # Number of testing data x Number of folds , we will take the mean of the predictions later
for i, (train_index, cv_index) in enumerate(skf):
print ('Fold [%s]' % (i))
# This is the training and validation set
X_train = X_dev[train_index]
Y_train = Y_dev[train_index]
X_cv = X_dev[cv_index]
Y_cv = Y_dev[cv_index]
clf.fit(X_train, Y_train)
# This output will be the basis for our blended classifier to train against,
# which is also the output of our classifiers
# blend_train[cv_index, j] = clf.predict(X_cv)
# blend_test_j[:, i] = clf.predict(X_test)
blend_train[cv_index, j] = clf.predict_proba(X_cv)[:, 1]
blend_test_j[:, i] = clf.predict_proba(X_test)[:, 1]
# Take the mean of the predictions of the cross validation set
blend_test[:, j] = blend_test_j.mean(1)
print('Y_dev.shape = %s' % (Y_dev.shape))
def RPI_SE(dataset):
X, labels = get_data_deepmind(dataset, seperate=True)
X_data1, X_data2 = transfer_array_format(X)
print (X_data1.shape, X_data2.shape)
X_data1 = preprocess_data(X_data1)
X_data2 = preprocess_data(X_data2)
# y,encoder = preprocess_labels(labels)
X_data = np.concatenate((X_data1, X_data2), axis=1)
y = np.array(labels, dtype=int)
num_cross_val = 5 # 5-fold
all_performance_xgb = []
all_performance_lgbm = []
all_performance_nb = []
all_performance_knn = []
all_performance_stack = []
all_performance_lstm = []
all_labels = []
all_prob = {}
num_classifier = 4
all_prob[0] = []
all_prob[1] = []
all_prob[2] = []
all_prob[3] = []
all_prob[4] = []
all_prob[5] = []
all_average = []
print(X_data.shape,X_data.shape[0],X_data.shape[1])
for fold in range(num_cross_val):
train = np.array([x for i, x in enumerate(X_data) if i % num_cross_val != fold])
test = np.array([x for i, x in enumerate(X_data) if i % num_cross_val == fold])
# train1 = np.array([x for i, x in enumerate(X_data1) if i % num_cross_val != fold])
# test1 = np.array([x for i, x in enumerate(X_data1) if i % num_cross_val == fold])
# train2 = np.array([x for i, x in enumerate(X_data2) if i % num_cross_val != fold])
# test2 = np.array([x for i, x in enumerate(X_data2) if i % num_cross_val == fold])
train_label = np.array([x for i, x in enumerate(y) if i % num_cross_val != fold])
test_label = np.array([x for i, x in enumerate(y) if i % num_cross_val == fold])
real_labels = []
for val in test_label:
if val == 1:
real_labels.append(1)
else:
real_labels.append(0)
train_label_new = []
for val in train_label:
if val == 1:
train_label_new.append(1)
else:
train_label_new.append(0)
blend_train = np.zeros((train.shape[0], num_classifier)) # Number of training data x Number of classifiers
blend_test = np.zeros((test.shape[0], num_classifier)) # Number of testing data x Number of classifiers
skf = list(StratifiedKFold(train_label_new, num_classifier))
#train, test, prefilter_train_bef, prefilter_test_bef = autoencoder_two_subnetwork_fine_tuning(train1, train2, train_label, test1, test2, test_label)
all_labels = all_labels + real_labels
tmp_aver = [0] * len(real_labels)
class_index = 0
print ('SVM')
svm = svm.SVC(kernel='rbf',probability=True)
svm.fit(train, train_label)
svm_proba = svm.predict_proba(test)[:, 1]
all_prob[0] = all_prob[0] + [val for val in svm_proba]
tmp_aver = [val1 + val2 / 4 for val1, val2 in zip(svm_proba, tmp_aver)]
y_pred_lgbm = transfer_label_from_prob(svm_proba)
# print proba
acc, precision, sensitivity, specificity, MCC = calculate_performace(len(real_labels), y_pred_lgbm, real_labels)
print (acc, precision, sensitivity, specificity, MCC)
all_performance_lgbm.append([acc, precision, sensitivity, specificity, MCC])
get_blend_data(class_index, svm, skf, test, train, np.array(train_label_new), blend_train, blend_test)
print ('---' * 50)
print ('XGB')
class_index = class_index + 1
xgb1 = XGBClassifier(max_depth=6,booster='gblinear')#learning_rate=0.1,max_depth=6, booster='gbtree'
xgb1.fit(train, train_label)
xgb_proba = xgb1.predict_proba(test)[:, 1]
all_prob[1] = all_prob[1] + [val for val in xgb_proba]
tmp_aver = [val1 + val2 / 4 for val1, val2 in zip(xgb_proba, tmp_aver)]
y_pred_xgb = transfer_label_from_prob(xgb_proba)
acc, precision, sensitivity, specificity, MCC = calculate_performace(len(real_labels), y_pred_xgb, real_labels)
print (acc, precision, sensitivity, specificity, MCC)
all_performance_xgb.append([acc, precision, sensitivity, specificity, MCC])
get_blend_data(class_index, xgb1, skf, test, train, np.array(train_label_new), blend_train, blend_test)
print ('---' * 50)
print ('ExtraTrees')
class_index = class_index + 1
etree = ExtraTreesClassifier()
etree.fit(train, train_label)
etree_proba = etree.predict_proba(test)[:, 1]
all_prob[2] = all_prob[2] + [val for val in etree_proba]
tmp_aver = [val1 + val2 / 4 for val1, val2 in zip(etree_proba, tmp_aver)]
y_pred_knn = transfer_label_from_prob(etree_proba)
# y_pred_stack = blcf.predict(test)
acc, precision, sensitivity, specificity, MCC = calculate_performace(len(real_labels), y_pred_knn, real_labels)
print (acc, precision, sensitivity, specificity, MCC)
all_performance_knn.append([acc, precision, sensitivity, specificity, MCC])
get_blend_data(class_index, etree, skf, test, train, np.array(train_label_new), blend_train, blend_test)
print ('---' * 50)
print ('AdaBoost')
class_index = class_index + 1
Ada = AdaBoostClassifier()
Ada.fit(train, train_label)
proba = Ada.predict_proba(test)[:, 1]
all_prob[3] = all_prob[3] + [val for val in proba]
tmp_aver = [val1 + val2 / 4 for val1, val2 in zip(proba, tmp_aver)]
y_pred_gnb = transfer_label_from_prob(proba)
# y_pred_stack = blcf.predict(test)
acc, precision, sensitivity, specificity, MCC = calculate_performace(len(real_labels), y_pred_gnb, real_labels)
print (acc, precision, sensitivity, specificity, MCC)
all_performance_nb.append([acc, precision, sensitivity, specificity, MCC])
get_blend_data(class_index, Ada, skf, test, train, np.array(train_label_new), blend_train, blend_test)
print ('---' * 50)
all_average = all_average + tmp_aver
print ("Stacked Ensemble")
#bclf = VotingClassifier(voting='soft',estimators=[('svm',gbm),('XGB',xgb1),('ET',knn),('adaB',gnb)],weights=[2,2,1,1])
bclf = LogisticRegression()
bclf.fit(blend_train, train_label_new)
stack_proba = bclf.predict_proba(blend_test)[:, 1]
all_prob[4] = all_prob[4] + [val for val in stack_proba]
y_pred_stack = transfer_label_from_prob(stack_proba)
# y_pred_stack = blcf.predict(test)
acc, precision, sensitivity, specificity, MCC = calculate_performace(len(real_labels), y_pred_stack,
real_labels)
print (acc, precision, sensitivity, specificity, MCC)
all_performance_stack.append([acc, precision, sensitivity, specificity, MCC])
print ('---' * 50)
'''
print "Average Ensemble"
y_pred_average = transfer_label_from_prob(tmp_aver)
acc, precision, sensitivity, specificity, MCC = calculate_performace(len(real_labels), y_pred_average, real_labels)
print acc, precision, sensitivity, specificity, MCC
all_performance_aver.append([acc, precision, sensitivity, specificity, MCC])
print '---' * 50
'''
print('mean performance of XGB')
print(np.mean(np.array(all_performance_xgb), axis=0))
print('---' * 50)
print('mean performance of SVM')
print(np.mean(np.array(all_performance_lgbm), axis=0))
print('---' * 50)
print('mean performance of AdaBoost')
print(np, mean(np.array(all_performance_nb), axis=0))
print('---' * 50)
print('mean performance of ExtraTrees')
print(np, mean(np.array(all_performance_knn), axis=0))
print('---' * 50)
# print('mean performance of lstm')
# print(np, mean(np.array(all_performance_lstm), axis=0))
# print('---' * 50)
print('mean performance of Stacked ensembling')
print(np.mean(np.array(all_performance_stack), axis=0))
print('---' * 50)
Figure = plt.figure()
plot_roc_curve(all_labels, all_prob[0], 'Kernal-SVM')
plot_roc_curve(all_labels, all_prob[1], 'XGBoost')
plot_roc_curve(all_labels, all_prob[2], 'ExtraTrees')
plot_roc_curve(all_labels, all_prob[3], 'AdaBoost')
plot_roc_curve(all_labels, all_prob[4], 'Stacked ensembling')
#plot_roc_curve(all_labels, all_prob[5], 'LSTM')
plot_roc_curve(all_labels, all_average, 'Average ensembling')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([-0.05, 1])
plt.ylim([0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC')
plt.legend(loc="lower right")
# plt.savefig(save_fig_dir + selected + '_' + class_type + '.png')
plt.show()
parser = argparse.ArgumentParser(description="""RPI-SE""")
parser.add_argument('-dataset',
type=str, help='which dataset you want to do 5-fold cross-validation')
parser.add_argument('-r',
type=str, help='RNA fasta file to store RNAs')
parser.add_argument('-p',
type=str, help='protein fasta file to store proteins')
args = parser.parse_args()
dataset = args.dataset
if dataset is not None:
RPI_SE(dataset)
else:
RNA_file = args.r
protein_file = args.p
if RNA_file is None or protein_file is None:
print('you must input RNA and protein fasta file')
'''
/**
* .,:,,, .::,,,::.
* .::::,,;;, .,;;:,,....:i:
* :i,.::::,;i:. ....,,:::::::::,.... .;i:,. ......;i.
* :;..:::;::::i;,,:::;:,,,,,,,,,,..,.,,:::iri:. .,:irsr:,.;i.
* ;;..,::::;;;;ri,,,. ..,,:;s1s1ssrr;,.;r,
* :;. ,::;ii;:, . ................... .;iirri;;;,,;i,
* ,i. .;ri:. ... ............................ .,,:;:,,,;i:
* :s,.;r:... ....................................... .::;::s;
* ,1r::. .............,,,.,,:,,........................,;iir;
* ,s;........... ..::.,;:,,. ...............,;1s
* :i,..,. .,:,,::,. .......... .......;1,
* ir,....:rrssr;:, ,,.,::. .r5S9989398G95hr;. ....,.:s,
* ;r,..,s9855513XHAG3i .,,,,,,,. ,S931,.,,.;s;s&BHHA8s.,..,..:r:
* :r;..rGGh, :SAG;;G@BS:.,,,,,,,,,.r83: hHH1sXMBHHHM3..,,,,.ir.
* ,si,.1GS, sBMAAX&MBMB5,,,,,,:,,.:&8 3@HXHBMBHBBH#X,.,,,,,,rr
* ;1:,,SH: .A@&&B#&8H#BS,,,,,,,,,.,5XS, 3@MHABM&59M#As..,,,,:,is,
* .rr,,,;9&1 hBHHBB&8AMGr,,,,,,,,,,,:h&&9s; r9&BMHBHMB9: . .,,,,;ri.
* :1:....:5&XSi;r8BMBHHA9r:,......,,,,:ii19GG88899XHHH&GSr. ...,:rs.
* ;s. .:sS8G8GG889hi. ....,,:;:,.:irssrriii:,. ...,,i1,
* ;1, ..,....,,isssi;, .,,. ....,.i1,
* ;h: i9HHBMBBHAX9: . ...,,,rs,
* ,1i.. :A#MBBBBMHB##s ....,,,;si.
* .r1,.. ,..;3BMBBBHBB#Bh. .. ....,,,,,i1;
* :h;.. .,..;,1XBMMMMBXs,.,, .. :: ,. ....,,,,,,ss.
* ih: .. .;;;, ;;:s58A3i,.. ,. ,.:,,. ...,,,,,:,s1,
* .s1,.... .,;sh, ,iSAXs;. ,. ,,.i85 ...,,,,,,:i1;
* .rh: ... rXG9XBBM#M#MHAX3hss13&&HHXr .....,,,,,,,ih;
* .s5: ..... i598X&&A&AAAAAA&XG851r: ........,,,,:,,sh;
* . ihr, ... . .. ........,,,,,;11:.
* ,s1i. ... ..,,,..,,,.,,.,,.,.. ........,,.,,.;s5i.
* .:s1r,...................... ..............;shs,
* . .:shr:. .... ..............,ishs.
* .,issr;,... ...........................,is1s;.
* .,is1si;:,....................,:;ir1sr;,
* ..:isssssrrii;::::::;;iirsssssr;:..
* .,::iiirsssssssssrri;;:.
*/
'''<file_sep># RPI-SE: A Stacking Ensemble Learning Framework for ncRNA-Protein Interactions Prediction Using Sequence Information
The interactions between non-coding RNAs and proteins play an essential role in many biological processes. A various of high-throughput experimental methods have been applied to detect ncRNA-protein interactions. However,they are time-consuming and expensive. In this study, we presented a novel stacking heterogeneous ensemble learning framework, RPI-SE, using logistic regression to integrate gradient boosting machine, support vector machine and extremely randomized tree algorithms, for effectively predicting ncRNA-protein interactions. More specifically, to fully exploit protein and RNA sequence information, Position Weight Matrix combined with Legendre Moments was applied to obtain protein evolutionary information. Meanwhile, k-mer sparse matrix was employed to extract efficient features from ncRNA sequences. Then, these discriminative features were fed into the ensemble learning framework to learn how to predict ncRNA-protein interactions. The accuracy and robustness of RPI-SE is evaluated on different types of dataset, including RNA-protein interactions and long ncRNA-protein interactions datasets, and compared with other state-of-the-art methods. Experimental results demonstrate that our method RPI-SE is competent for ncRNA-protein interactions prediction task and can achieve great prediction performance with high accurate and robustness. It’s anticipated that this study could advance the ncRNA-protein interactions related biomedical research.
## Dependency:
python 3.5
Numpy
XGBoost
scikit-learn
## Usage:
python RPI-SE.py -datatype=RPI369
Where RPI369 is RNA-protein interaction dataset, and RPI-SE will do 5-fold cross-validation for it. you can also choose other datasets, such as RPI488, RPI1807.
## Reference:
<NAME>., <NAME>., <NAME>. et al. RPI-SE: a stacking ensemble learning framework for ncRNA-protein interactions prediction using sequence information. BMC Bioinformatics 21, 60 (2020).
| af3abc54bc6a7cb43a283459d0ff3d3f72c5862f | [
"Markdown",
"Python"
] | 2 | Python | wenmm/RPI-SE | 06f1acb34b213f94740c967c5cef9138511e4baa | 9b104eee689c07e8d3bbd20e84e357088bbfb1bd |
refs/heads/master | <file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/5/9
* Time: 下午4:53
*/
namespace Sukui;
class Application{
public $httpServer;
public $context;
public $middleware = [];
public $fn;
public $defaultConfig = [
'port' => 8000,
'host' => '127.0.0.1'
];
public function __construct() {
$this->context = new ServerContext();
$this->context->app = $this;
}
public function addMiddleware(callable $fn){
$this->middleware[] = $fn;
return $this;
}
public function listen($port = 8000,array $config=[]){
$this->fn = compose($this->middleware);
$config = ['port'=>$port] + $config + $this->defaultConfig;
$this->httpServer = new \swoole_http_server($config['host'], $config['port'], SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
$this->httpServer->set($config);
$this->httpServer->on("request",[$this,"onRequest"]);
$this->httpServer->start();
}
public function onRequest(\swoole_http_request $req, \swoole_http_response $res){
$ctx = $this->createContext($req,$res);
$reqHandler = $this->makeRequestHandler($ctx);
$resHandler = $this->makeResponseHandler($ctx);
spawn($reqHandler,$resHandler);
}
protected function makeRequestHandler(ServerContext $context){
return function ()use($context){
yield Context::setCtx("ctx",$context);
$context->res->status(404);
$fn = $this->fn;
yield $fn($context);
};
}
protected function makeResponseHandler(ServerContext $context){
return function ($r=null,\Exception $ex = null)use ($context){
if($ex){
$this->handleError($context,$ex);
}else{
$this->respond($context);
}
};
}
protected function handleError(ServerContext $context,\Exception $ex=null){
if($ex === null){
return;
}
if($ex && $ex->getCode() !== 404){
}
$code = $ex->getCode();
$message = $ex->getMessage();
$context->res->status($code);
$context->res->header("Content-Type", "text");
$context->res->write($message);
$context->res->end();
}
protected function respond(ServerContext $context){
if($context->respond === false) return;
$body = $context->body;
$code = $context->status;
if($code !== null){
$context->res->status($code);
}
if($body !== null){
$context->write($body);
}
$context->res->end();
}
protected function createContext(\swoole_http_request $req, \swoole_http_response $res){
$context = clone $this->context;
$request = $context->request = new Request($this,$context,$req,$res);
$response = $context->response = new Response($this,$context,$req,$res);
$context->app = $this;
$context->req = $req;
$context->res = $res;
$context->response = $response;
$context->request = $request;
$request->originalUrl = $req->server['request_uri'];
$request->ip = $req->server['remote_addr'];
return $context;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/4/1
* Time: 上午10:35
*/
use Sukui\ServerContext;
use Sukui\SysCall;
use Sukui\Channel;
use Sukui\BufferChannel;
use Sukui\Task\Any;
use Sukui\Task\Async;
use Sukui\Task\AsyncTask;
use Sukui\Task\CallCC;
use Sukui\Task\All;
use Sukui\Task\FutureTask;
function spawn(){
$n = func_num_args();
if($n === 0){
return;
}
$task = func_get_arg(0);
$continuation = function(){};
$paren = null;
$ctx = [];
for ($i=1;$i<$n;$i++){
$arg = func_get_arg($i);
if(is_callable($arg)){
$continuation = $arg;
}elseif($arg instanceof Async){
$paren = $arg;
}elseif(is_array($arg)){
$ctx = $arg;
}
}
if(is_callable($task)){
try{
$task = $task();
}catch (\Exception $ex){
$continuation(null,$ex);
return;
}
}
if($task instanceof \Generator){
foreach ($ctx as $k => $v){
$task->k = $v;
}
(new AsyncTask($task,$paren))->begin($continuation);
}else{
$continuation($task,null);
}
}
function callCC(callable $fun,$timeout=0){
if($timeout>0){
$fun = timeoutWrapper($fun,$timeout);
}
return new CallCC($fun);
}
function async_sleep($ms){
return callCC(function($k)use($ms){
swoole_timer_after($ms,function () use ($k){
$k(null);
});
});
}
function async_dns_lookup($host,$timeout=0){
if($timeout>0){
return race([
callCC(function($k) use($host) {
swoole_async_dns_lookup($host, function($host, $ip) use($k) {
$k($ip);
});
}),
timeout($timeout)
]);
}else{
return callCC(function($k)use($host){
swoole_async_dns_lookup($host, function($host, $ip) use($k) {
$k($ip);
});
});
}
}
function once(callable $fun){
$has = false;
return function (...$args)use($fun,&$has){
if($has === false){
$fun(...$args);
$has = true;
}
};
}
function timeoutWrapper(callable $fun,$timeout){
return function ($k)use($fun,$timeout){
$k = once($k);
$fun($k);
swoole_timer_after($timeout,function()use($k){
$k(null,new \Exception("timeout"));
});
};
}
function await($task,...$args){
if($task instanceof \Generator){
return $task;
}
if(is_callable($task) && ! $task instanceof SysCall){
$gen = function()use($task,$args){
yield $task(...$args);
};
}else{
$gen = function () use ($task){
yield $task;
};
}
return $gen();
}
function race(array $tasks){
$tasks = array_map(__NAMESPACE__."\\await",$tasks);
return new SysCall(function(AsyncTask $parent) use ($tasks){
if(empty($tasks)){
return null;
}else{
return new Any($tasks,$parent);
}
});
}
function timeout($ms){
return callCC(function($k)use($ms){
swoole_timer_after($ms,function()use($k){
$k(null,new \Exception("timeout"));
});
});
}
function all(array $tasks){
$tasks = array_map(__NAMESPACE__."\\await",$tasks);
return new SysCall(function(AsyncTask $parent) use ($tasks){
if(empty($tasks)){
return null;
}else{
return new All($tasks,$parent);
}
});
}
function go(...$args){
spawn(...$args);
}
/**
* @param int $n
* @return Channel
*/
function chan($n=0){
if($n === 0){
return new Channel();
}else{
return new BufferChannel($n);
}
}
function fork($task,...$args){
$task = await($task);
return new SysCall(function(AsyncTask $parent)use($task){
return new FutureTask($task,$parent);
});
}
function array_right_reduce(array $input, callable $function, $initial = null)
{
return array_reduce(array_reverse($input, true), $function, $initial);
}
function compose(array $middleware)
{
return function(ServerContext $ctx = null) use($middleware) {
$ctx = $ctx ?: new ServerContext(); // Context 参见下文
return array_right_reduce($middleware, function($rightNext, $leftFn) use($ctx) {
return $leftFn($ctx, $rightNext);
}, null);
};
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/30
* Time: 上午11:32
*/
namespace Sukui\Task;
interface Async{
public function begin(callable $callback);
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/5/10
* Time: 上午10:02
*/
namespace Sukui\Middleware;
use Sukui\ServerContext;
class RequestTimeout implements Middleware {
public $timeout;
public $exception;
private $timerId = null;
public function __construct($timeout,\Exception $ex=null) {
$this->timeout = $timeout;
if($ex === null){
$this->exception = new \Exception("Reuest timeout",408);
}else{
$this->exception = $ex;
}
}
public function __invoke(ServerContext $ctx, $next) {
yield race([
callCC(function($k){
$this->timerId = swoole_timer_after($this->timeout, function() use ($k) {
$this->timerId = null;
$k(null, $this->exception);
});
}),
function()use($next){
yield $next;
if($this->timerId){
swoole_timer_clear($this->timerId);
}
}
]);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/28
* Time: 下午2:13
*/
require dirname(__FILE__)."/vendor/autoload.php";
/*
$pingCh = chan();
$pongCh = chan();
go(function ()use($pingCh,$pongCh){
while (true){
echo (yield $pingCh->recv());
yield $pongCh->send("Pong\n");
yield async_sleep(200);
}
});
go(function ()use($pingCh,$pongCh){
while (true){
echo (yield $pongCh->recv());
yield $pingCh->send("Ping\n");
yield async_sleep(100);
}
});
go(function ()use($pingCh){
echo "start up \n";
yield $pingCh->send("Ping\n");
});*/
/*go(function() {
$start = microtime(true);
$ch = chan();
// 开启一个新的协程,异步执行耗时任务
spawn(function() use($ch) {
yield async_sleep(1000);
yield $ch->send(42); // 通知+传送结果
});
$future = (yield fork(function (){
yield async_sleep(1000);
yield 43;
}));
// 阻塞等待超时,捕获到超时异常
try {
$r = (yield $future->get(100));
var_dump($r);
} catch (\Exception $ex) {
echo "get result timeout\n";
}
yield async_sleep(500);
$r = (yield $ch->recv()); // 阻塞等待结果
echo $r."\n"; // 42
$r = (yield $future->get());
echo $r."\n";
// 我们这里两个耗时任务并发执行,总耗时约1000ms
echo "cost ", microtime(true) - $start, "\n";
});*/
go(function() {
$start = microtime(true);
/** @var $future FutureTask */
$future = (yield fork(function() {
yield async_sleep(500);
yield 42;
}));
// 阻塞等待超时,捕获到超时异常
try {
$r = (yield $future->get(100));
var_dump($r);
} catch (\Exception $ex) {
echo "get result timeout\n";
}
yield async_sleep(1000);
// 因为我们只等待子任务100ms,我们的总耗时只有 1100ms
echo "cost ", microtime(true) - $start, "\n";
});
go(function() {
$start = microtime(true);
/** @var $future FutureTask */
$future = (yield fork(function() {
yield async_sleep(500);
yield 42;
throw new \Exception();
}));
yield async_sleep(1000);
// 子任务500ms前发生异常,已经处于完成状态
// 我们调用get会当即引发异常
try {
$r = (yield $future->get());
var_dump($r);
} catch (\Exception $ex) {
echo "something wrong in child task\n";
}
// 因为耗时任务并发执行,这里总耗时仅1000ms
echo "cost ", microtime(true) - $start, "\n";
});<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/31
* Time: 下午4:14
*/
namespace Sukui;
use Sukui\Task\Async;
class Context{
public static function getCtx($key,$default=null){
return new SysCall(function(Async $task) use ($key,$default){
while ($task->parent && $task = $task->parent);
if(isset($task->gen->generator->$key)){
return $task->gen->generator->$key;
}else{
return $default;
}
});
}
public static function setCtx($key,$val){
return new Syscall(function(Async $task) use($key, $val) {
while($task->parent && $task = $task->parent);
$task->gen->generator->$key = $val;
});
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/28
* Time: 下午2:13
*/
use Sukui\Client\HttpClient;
use Sukui\Task\AsyncDns;
use Sukui\Task\AsyncSleep;
use Sukui\Context;
require dirname(__FILE__)."/vendor/autoload.php";
//$test = new stdClass();
//$test->parent = new stdClass();
//while ($test->parent && $k = $test->parent);
//var_dump($k);
//exit();
function newSubGen(){
//yield 0;
throw new Exception("test");
yield 1;
}
function newGen()
{
try{
$r1 = (yield newSubGen());
}catch (Exception $e){
var_dump($e->getMessage());
}
$r2 = (yield 2);
//var_dump($r1,$r2);
$start = time();
yield new AsyncSleep();
echo time()-$start."\n";
$ip = (yield new AsyncDns());
yield "ip:{$ip}";
}
function setTask(){
yield Context::setCtx("test","gggg");
}
function ctxTest(){
yield setTask();
$test = (yield Context::getCtx("test"));
var_dump($test);
}
//$task = new AsyncTask(ctxTest());
$test = function ($result,$ex){
if($ex){
var_dump($ex->getMessage());
}else{
var_dump($result);
}
};
//$task->begin($test); // output: 12
/*spawn(function() {
try {
yield async_dns_lookup("www.xxx.com", 1);
} catch (\Exception $ex) {
echo $ex->getMessage(); // ex!
}
});*/
// 这里!
spawn(function() {
try{
$ip = (yield async_dns_lookup("www.baidu.com"));
$cli = new HttpClient($ip, 80);
$cli->setHeaders(["foo" => "bar"]);
$cli = (yield $cli->async_get("/"));
echo $cli->body, "\n";
$ip = (yield race([
async_dns_lookup("www.baidu.com"),
timeout(100)
]));
$res = (yield (new HttpClient($ip,80))->awaitGet("/"));
var_dump($res->statusCode);
$r = (yield all([
"bing" => async_dns_lookup("www.bing.com"),
"so" => async_dns_lookup("www.so.com"),
"baidu" => async_dns_lookup("www.baidu.com"),
]));
var_dump($r);
}catch (Exception $e){
var_dump($e->getMessage());
}
swoole_event_exit();
});
<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/4/25
* Time: 下午4:35
*/
namespace Sukui\Task;
final class FutureTask{
const PENDING = 1;
const DONE = 2;
const TIMEOUT = 3;
private $timerId;
private $cc;
public $state;
public $result;
public $ex;
public function __construct(\Generator $gen,AsyncTask $parent = null) {
$this->state = self::PENDING;
if($parent){
$asyncTask = new AsyncTask($gen,$parent);
}else{
$asyncTask = new AsyncTask($gen);
}
$asyncTask->begin(function($r,$ex=null){
if($this->state === self::TIMEOUT){
return ;
}
$this->state = self::DONE;
if($cc = $this->cc){
if($this->timerId){
swoole_timer_clear($this->timerId);
}
$cc($r,$ex);
}else{
$this->result = $r;
$this->ex = $ex;
}
});
}
public function get($timeout=0){
return callCC(function($cc)use($timeout){
if($this->state === self::DONE){
$cc($this->result,$this->ex);
}else{
$this->cc = $cc;
$this->getResukltTimeout($timeout);
}
});
}
private function getResukltTimeout($timeout){
if(!$timeout){
return ;
}
$this->timerId = swoole_timer_after($timeout, function() {
$this->state = self::TIMEOUT;
$cc = $this->cc;
$cc(null, new \Exception("timeout"));
});
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/5/9
* Time: 下午6:44
*/
namespace Sukui\Middleware;
use Sukui\ServerContext;
class NotFound implements Middleware {
public function __invoke(ServerContext $ctx, $next) {
yield $next;
if($ctx->status !== 404 || $ctx->body){
return;
}
$ctx->status = 404;
$ctx->body = "<h1>404 Not Found</h1>";
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/5/9
* Time: 下午6:47
*/
namespace Sukui;
use FastRoute\DataGenerator;
use FastRoute\Dispatcher;
use FastRoute\Dispatcher\GroupCountBased;
use FastRoute\RouteCollector;
use FastRoute\RouteParser;
class Router extends RouteCollector {
public $dispatcher = null;
public function __construct() {
$routeParser = new RouteParser\Std();
$dataGenerator = new DataGenerator\GroupCountBased();
parent::__construct($routeParser, $dataGenerator);
}
public function routes(){
$this->dispatcher = new GroupCountBased($this->getData());
return [$this,"dispatch"];
}
public function dispatch(ServerContext $context,$next){
if($this->dispatcher === null){
$this->routes();
}
$uri = $context->url;
if(false !== $pos = strpos($uri,"?")){
$uri = substr($uri,0,$pos);
}
$uri = rawurldecode($uri);
$routerInfo = $this->dispatcher->dispatch(strtoupper($context->method),$uri);
switch ($routerInfo[0]){
case Dispatcher::NOT_FOUND:
$context->status = 404;
yield $next;
break;
case Dispatcher::METHOD_NOT_ALLOWED:
$context->status = 405;
break;
case Dispatcher::FOUND:
$handler = $routerInfo[1];
$vars = $routerInfo[2];
yield $handler($context,$next,$vars);
break;
}
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/4/25
* Time: 下午2:40
*/
namespace Sukui;
class Channel{
public $recvQ;
public $sendQ;
public function __construct() {
$this->recvQ = new \SplQueue();
$this->sendQ = new \SplQueue();
}
public function send($val){
return callCC(function($cc)use($val){
if ($this->recvQ->isEmpty()) {
// 当chan没有接收者,发送者协程挂起(将$cc入列,不调用$cc回送数据)
$this->sendQ->enqueue([$cc, $val]);
} else {
// 当chan对端有接收者,将挂起接收者协程出列,
// 调用接收者$recvCc发送数据,运行接收者协程后继代码
// 执行完毕或者遇到Async挂起,$recvCc()调用返回,
// 调用$cc(),控制流回到发送者协程
$recvCc = $this->recvQ->dequeue();
$recvCc($val, null);
$cc(null, null);
}
});
}
public function recv(){
return callCC(function($cc){
if ($this->sendQ->isEmpty()) {
// 当chan没有发送者,接收者协程挂起(将$cc入列)
$this->recvQ->enqueue($cc);
} else {
// 当chan对端有发送者,将挂起发送者协程与待发送数据出列
// 调用发送者$sendCc发送数据,运行发送者协程后继代码
// 执行完毕或者遇到Async挂起,$sendCc()调用返回,
// 调用$cc(),控制流回到接收者协程
list($sendCc, $val) = $this->sendQ->dequeue();
$sendCc(null, null);
$cc($val, null);
}
});
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/5/9
* Time: 下午6:32
*/
namespace Sukui\Middleware;
use Sukui\ServerContext;
class ExceptionHandler implements Middleware {
public function __invoke(ServerContext $ctx, $next) {
try{
yield $next;
}catch (\Exception $ex){
$status = 500;
$code = $ex->getCode()?:0;
$msg = "Internal Error";
if ($ex instanceof HttpException) {
$status = $ex->status;
if ($ex->expose) {
$msg = $ex->getMessage();
}
}
$err = [ "code" => $code, "msg" => $msg ];
if ($ctx->accept("json")) {
$ctx->status = 200;
$ctx->body = $err;
} else {
$ctx->status = $status;
if ($status === 404) {
$ctx->body = 404;
} else if ($status === 500) {
$ctx->body = 500;
} else {
$ctx->body = 502;
}
}
}
}
}<file_sep># php-co-koa-code
for the code : https://github.com/youzan/php-co-koa
<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/4/25
* Time: 下午2:40
*/
namespace Sukui;
class BufferChannel{
public $cap;
public $queue;
public $recvCc;
public $sendCc;
public function __construct($cap) {
$this->cap = $cap;
$this->recvCc = new \SplQueue();
$this->sendCc = new \SplQueue();
$this->queue = new \SplQueue();
}
public function send($val){
return callCC(function($cc)use($val){
if($this->cap > 0){
$this->queue->enqueue($val);
$this->cap--;
$cc(null,null);
}else{
$this->sendCc->enqueue([$cc,$val]);
}
$this->sendPingPong();
});
}
public function sendPingPong(){
if(!$this->recvCc->isEmpty() && !$this->queue->isEmpty()){
$recvCc = $this->recvCc->dequeue();
$val = $this->queue->dequeue();
$this->cap++;
$recvCc($val);
if(!$this->sendCc->isEmpty() && $this->cap >0){
list($sendCc,$val) = $this->sendCc->dequeue();
$this->queue->enqueue($val);
$this->cap--;
$sendCc(null,null);
$this->sendPingPong();
}
}
}
public function recv(){
return callCC(function($cc){
if($this->sendCc->isEmpty()){
$this->recvCc->enqueue($cc);
}else{
$val = $this->queue->dequeue();
$this->cap++;
$cc($val,null);
}
$this->recvPingPong();
});
}
public function recvPingPong(){
if(!$this->sendCc->isEmpty() && !$this->cap > 0){
list($sendCc,$val) = $this->sendCc->dequeue();
$this->queue->enqueue($val);
$this->cap--;
$sendCc(null,null);
if(!$this->recvCc->isEmpty() && !$this->queue->isEmpty()){
$recvCc = $this->recvCc->dequeue();
$val = $this->queue->dequeue();
$this->cap++;
$recvCc($val,null);
$this->recvPingPong();
}
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/31
* Time: 下午4:02
*/
namespace Sukui;
use Sukui\Task\Async;
class SysCall{
private $fun;
public function __construct(callable $fun){
$this->fun = $fun;
}
public function __invoke(Async $task) {
$cc = $this->fun;
return $cc($task);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/5/9
* Time: 下午4:57
*/
namespace Sukui;
class ServerContext{
public $app;
public $request;
public $response;
public $req;
public $res;
public $state = [];
public $respond = true;
public $body;
public $status;
public function __call($name, $arguments) {
$fn = [$this->response,$name];
if(is_callable($fn)){
return $fn(...$arguments);
}else{
return null;
}
}
public function __get($name) {
return $this->request->$name;
}
public function __set($name, $value) {
$this->response->$name = $value;
}
public function _throw($status,$message){
if($message instanceof \Exception){
$ex = $message;
throw new \HttpException($status,$ex->getMessage(),$ex->getCode(),$ex->getPrevious());
}else{
throw new \HttpException($status,$message);
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/30
* Time: 上午10:35
*/
namespace Sukui\Task;
use Sukui\Gen\Gen;
use Sukui\SysCall;
final class AsyncTask implements Async
{
public $gen;
public $continuation;
public $parent;
public function __construct(\Generator $gen, Async $task = null)
{
$this->gen = new Gen($gen);
$this->parent = $task;
}
public function begin(callable $continuation)
{
$this->continuation = $continuation;
$this->next();
}
public function next($result = null,\Exception $ex = null)
{
try{
if($ex){
$this->gen->throw_($ex);
}else{
$value = $this->gen->send($result);
}
if ($this->gen->valid()) {
if($value instanceof SysCall){
$value = $value($this);
}
if($value instanceof \Generator){
$value = new self($value,$this);
}
if($value instanceof Async){
$async = $value;
$continuation = [$this,"next"];
$async->begin($continuation);
}else{
$this->next($value,null);
}
}else{
$cc = $this->continuation;
$cc($result,null);
}
}catch (\Exception $ex){
if($this->gen->valid()){
$this->next(null,$ex);
}else{
$cc = $this->continuation;
$cc($result,$ex);
}
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/31
* Time: 下午5:55
*/
namespace Sukui\Client;
class HttpClient extends \swoole_http_client
{
public function async_get($uri)
{
return callCC(function($k) use($uri) {
$this->get($uri, $k);
});
}
public function async_post($uri, $post)
{
return callCC(function($k) use($uri, $post) {
$this->post($uri, $post, $k);
});
}
public function async_execute($uri)
{
return callCC(function($k) use($uri) {
$this->execute($uri, $k);
});
}
public function awaitGet($uri,$timeout=1000){
return race([
callCC(function($k)use($uri){
$this->get($uri,$k);
}),
timeout($timeout)
]);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/5/9
* Time: 下午6:30
*/
namespace Sukui\Middleware;
use Sukui\ServerContext;
interface Middleware{
public function __invoke(ServerContext $ctx,$next);
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/5/9
* Time: 下午5:47
*/
require dirname(__FILE__)."/vendor/autoload.php";
$router = new \Sukui\Router();
$router->get("/user/{id:\d+}",function (\Sukui\ServerContext $context,$next,$vars){
$context->body = "user={$vars['id']}";
});
$router->addRoute(["GET","POST"],"/test",function (\Sukui\ServerContext $context,$next,$vars){
$context->body = "test";
});
$router->get("/timeout",function (\Sukui\ServerContext $context,$next,$vars){
yield async_sleep(1000);
});
$router->addGroup("/admin",function(\FastRoute\RouteCollector $router){
$router->addRoute("GET","/test1",function (\Sukui\ServerContext $context,$next,$vars){
$context->body = "admin/test1";
});
$router->addRoute("GET","/test2",function (\Sukui\ServerContext $context,$next,$vars){
$context->body = "admin/test2 with ".json_encode($vars);
});
});
$app = new \Sukui\Application();
$app->addMiddleware(new \Sukui\Middleware\RequestTimeout(200));
$app->addMiddleware($router->routes());
$app->addMiddleware(new \Sukui\Middleware\NotFound());
$app->listen();<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/30
* Time: 上午10:36
*/
namespace Sukui\Gen;
class Gen
{
public $isfirst = true;
public $generator;
public function __construct(\Generator $generator)
{
$this->generator = $generator;
}
public function valid()
{
return $this->generator->valid();
}
public function send($value = null)
{
if ($this->isfirst) {
$this->isfirst = false;
$data = $this->generator->current();
} else {
$data = $this->generator->send($value);
}
return $data;
}
public function throw_(\Exception $e){
return $this->generator->throw($e);
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/30
* Time: 下午2:07
*/
namespace Sukui\Task;
class AsyncDns implements Async {
public function begin(callable $cc){
swoole_async_dns_lookup("www.baidu.com",function ($host,$ip)use($cc){
$cc($ip);
});
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/31
* Time: 下午5:49
*/
namespace Sukui\Task;
class CallCC implements Async {
public $fun;
public function __construct(callable $fun) {
$this->fun = $fun;
}
public function begin(callable $callback) {
$fun = $this->fun;
$fun($callback);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: laogui
* Date: 17/3/30
* Time: 下午2:07
*/
namespace Sukui\Task;
class AsyncSleep implements Async {
public function begin(callable $cc){
swoole_timer_after(1000,$cc);
}
} | add1b005b08052c24daa9b55aad8e8c4bbddd0c9 | [
"Markdown",
"PHP"
] | 24 | PHP | ruziyi/php-co-koa-code | ad20f9b21b677868e270a8b4b7917f28de71bc90 | f53bc8e1c3058b6da5bdd1b718eb8088e5419fe3 |
refs/heads/master | <repo_name>mattwiz/Mountebank-Integration-Testing<file_sep>/test/FunctionApp.Tests/Fixtures/ServerFixture.cs
using System;
using System.Net;
namespace FunctionApp.Tests.Fixtures
{
/// <summary>
/// This represents the fixture entity for external API server.
/// </summary>
public abstract class ServerFixture
{
/// <summary>
/// Creates a new instance of the <see cref="ServerFixture"/> class.
/// </summary>
/// <param name="serverName">Mocking server name.</param>
/// <returns>Returns the new instance of the <see cref="ServerFixture"/> class.</returns>
public static ServerFixture CreateInstance(string serverName)
{
var type = Type.GetType($"FunctionApp.Tests.Fixtures.{serverName}ServerFixture");
var instance = (ServerFixture)Activator.CreateInstance(type);
return instance;
}
/// <summary>
/// Gets the URL for the health check.
/// </summary>
/// <param name="statusCode"><see cref="HttpStatusCode"/> value.</param>
/// <returns>Returns the URL for the health check.</returns>
public abstract string GetHealthCheckUrl(HttpStatusCode statusCode = HttpStatusCode.OK);
}
}<file_sep>/src/FunctionApp/Configurations/EndpointsSettings.cs
namespace FunctionApp.Configurations
{
/// <summary>
/// This represents the settings entity for endpoints.
/// </summary>
public class EndpointsSettings
{
/// <summary>
/// Gets or sets the endpoint for health check.
/// </summary>
public virtual string HealthCheck { get; set; }
}
}
<file_sep>/src/FunctionApp/Configurations/AppSettings.cs
using Aliencube.AzureFunctions.Extensions.Configuration.AppSettings;
using Aliencube.AzureFunctions.Extensions.Configuration.AppSettings.Extensions;
namespace FunctionApp.Configurations
{
/// <summary>
/// This represents the app settings entity.
/// </summary>
public class AppSettings : AppSettingsBase
{
/// <summary>
/// Initializes a new instance of the <see cref="AppSettings"/> class.
/// </summary>
public AppSettings()
{
this.ExternalApi = this.Config.Get<ExternalApiSettings>("ExternalApi");
}
/// <summary>
/// Gets the <see cref="ExternalApiSettings"/> instance.
/// </summary>
public ExternalApiSettings ExternalApi { get; }
}
}
<file_sep>/test/FunctionApp.Tests/HealthCheckHttpTriggerTests.cs
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Aliencube.AzureFunctions.Extensions.DependencyInjection.Abstractions;
using FluentAssertions;
using FunctionApp.Functions;
using FunctionApp.Tests.Fixtures;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace FunctionApp.Tests
{
[TestClass]
public class HealthCheckHttpTriggerTests
{
private const string CategoryIntegration = "Integration";
private const string CategoryE2E = "E2E";
private const string DefaultServerName = "Localhost";
private const string ServerNameKey = "ServerName";
private ServerFixture _fixture;
[TestInitialize]
public void Init()
{
var serverName = Environment.GetEnvironmentVariable(ServerNameKey);
if (string.IsNullOrWhiteSpace(serverName))
{
serverName = DefaultServerName;
}
this._fixture = ServerFixture.CreateInstance(serverName);
}
[TestMethod]
public void Given_Type_It_Should_Declare_Methods()
{
var method = typeof(HealthCheckHttpTrigger)
.Should().HaveMethod(nameof(HealthCheckHttpTrigger.PingAsync), new[] { typeof(HttpRequest), typeof(ILogger) })
.Which.Should().Return<Task<IActionResult>>()
.And.Subject;
method.GetCustomAttributes(typeof(FunctionNameAttribute), false)
.Should().ContainSingle()
.And.Subject.Single().As<FunctionNameAttribute>()
.Name.Should().Be(nameof(HealthCheckHttpTrigger.PingAsync));
var attribute = method.GetParameters().First().GetCustomAttributes(typeof(HttpTriggerAttribute), false)
.Should().ContainSingle()
.And.Subject.Single().As<HttpTriggerAttribute>();
attribute.AuthLevel.Should().Be(AuthorizationLevel.Function);
attribute.Methods.Should().ContainSingle()
.And.Subject.Single().Should().BeEquivalentTo("get");
attribute.Route.Should().BeEquivalentTo("ping");
}
[TestMethod]
public void Given_NullParameter_When_Instantiated_Then_Constructor_Should_Throw_Exception()
{
Action action = () => new HealthCheckHttpTrigger(null);
action.Should().Throw<ArgumentNullException>();
}
[TestMethod]
public async Task Given_Parameters_When_Invoked_Then_InvokeAsync_Should_Return_Result()
{
var function = new Mock<IHealthCheckFunction>();
var result = new OkResult();
function.Setup(p => p.InvokeAsync<HttpRequest, IActionResult>(It.IsAny<HttpRequest>(), It.IsAny<FunctionOptionsBase>()))
.ReturnsAsync(result);
var trigger = new HealthCheckHttpTrigger(function.Object);
var req = new Mock<HttpRequest>();
var log = new Mock<ILogger>();
var response = await trigger.PingAsync(req.Object, log.Object).ConfigureAwait(false);
response
.Should().BeOfType<OkResult>()
.And.Subject.As<OkResult>()
.StatusCode.Should().Be((int)HttpStatusCode.OK);
}
[TestMethod]
[TestCategory(CategoryIntegration)]
[TestCategory(CategoryE2E)]
public async Task Given_Url_When_Invoked_Then_Trigger_Should_Return_Healthy()
{
var uri = this._fixture.GetHealthCheckUrl();
using (var http = new HttpClient())
using (var res = await http.GetAsync(uri))
{
res.StatusCode.Should().Be(HttpStatusCode.OK);
}
}
[TestMethod]
[TestCategory(CategoryIntegration)]
public async Task Given_Url_When_Invoked_Then_Trigger_Should_Return_Unhealthy()
{
var uri = this._fixture.GetHealthCheckUrl(HttpStatusCode.InternalServerError);
using (var http = new HttpClient())
using (var res = await http.GetAsync(uri))
{
res.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
}
}
}
}<file_sep>/src/FunctionApp/Configurations/ExternalApiSettings.cs
namespace FunctionApp.Configurations
{
/// <summary>
/// This represents the settings entity for external API.
/// </summary>
public class ExternalApiSettings
{
/// <summary>
/// Gets or sets the base URI.
/// </summary>
public virtual string BaseUri { get; set; }
/// <summary>
/// Gets or sets the <see cref="EndpointsSettings"/> instance.
/// </summary>
public virtual EndpointsSettings Endpoints { get; set; }
}
}
<file_sep>/test/FunctionApp.Tests/Functions/HealthCheckFunctionTests.cs
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Aliencube.AzureFunctions.Extensions.DependencyInjection.Abstractions;
using FluentAssertions;
using FunctionApp.Configurations;
using FunctionApp.Functions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using WorldDomination.Net.Http;
namespace FunctionApp.Tests.Functions
{
[TestClass]
public class HealthCheckFunctionTests
{
[TestMethod]
public void Given_Type_It_Should_Inherit_BaseClass()
{
typeof(HealthCheckFunction)
.Should().BeDerivedFrom<FunctionBase<ILogger>>();
}
[TestMethod]
public void Given_Type_It_Should_Implement_Interfaces()
{
typeof(HealthCheckFunction)
.Should().Implement<IHealthCheckFunction>();
}
[TestMethod]
public void Given_Type_When_Instantiated_With_NullParameter_Then_Constructor_Should_Throw_Exception()
{
var settings = new Mock<ExternalApiSettings>();
var httpClient = new HttpClient();
Action action = () => new HealthCheckFunction(null, httpClient);
action.Should().Throw<ArgumentNullException>();
action = () => new HealthCheckFunction(settings.Object, null);
action.Should().Throw<ArgumentNullException>();
}
[TestMethod]
public async Task Given_Parameters_When_Invoked_With_OK_Then_InvokeAsync_Should_Return_Result()
{
var endpoints = new Mock<EndpointsSettings>();
endpoints.SetupGet(p => p.HealthCheck).Returns("ping");
var settings = new Mock<ExternalApiSettings>();
settings.SetupGet(p => p.BaseUri).Returns("http://localhost");
settings.SetupGet(p => p.Endpoints).Returns(endpoints.Object);
var message = new HttpResponseMessage(HttpStatusCode.OK);
var options = new HttpMessageOptions()
{
HttpMethod = HttpMethod.Get,
HttpResponseMessage = message
};
var handler = new FakeHttpMessageHandler(options);
var httpClient = new HttpClient(handler);
var function = new HealthCheckFunction(settings.Object, httpClient);
var req = new Mock<HttpRequest>();
var result = await function.InvokeAsync<HttpRequest, IActionResult>(req.Object)
.ConfigureAwait(false);
result
.Should().BeOfType<OkResult>()
.And.Subject.As<OkResult>()
.StatusCode.Should().Be((int)HttpStatusCode.OK);
}
[TestMethod]
public async Task Given_Parameters_When_Invoked_With_Error_Then_InvokeAsync_Should_Return_Result()
{
var endpoints = new Mock<EndpointsSettings>();
endpoints.SetupGet(p => p.HealthCheck).Returns("ping");
var settings = new Mock<ExternalApiSettings>();
settings.SetupGet(p => p.BaseUri).Returns("http://localhost");
settings.SetupGet(p => p.Endpoints).Returns(endpoints.Object);
var message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
var options = new HttpMessageOptions()
{
HttpMethod = HttpMethod.Get,
HttpResponseMessage = message
};
var handler = new FakeHttpMessageHandler(options);
var httpClient = new HttpClient(handler);
var function = new HealthCheckFunction(settings.Object, httpClient);
var req = new Mock<HttpRequest>();
var result = await function.InvokeAsync<HttpRequest, IActionResult>(req.Object)
.ConfigureAwait(false);
result
.Should().BeOfType<ObjectResult>()
.And.Subject.As<ObjectResult>()
.StatusCode.Should().Be((int)HttpStatusCode.InternalServerError);
}
}
}
<file_sep>/src/FunctionApp/Models/ErrorResponse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace FunctionApp.Models
{
/// <summary>
/// This represents the response model entity for error.
/// </summary>
public class ErrorResponse
{
/// <summary>
/// Initializes a new instance of the <see cref="ErrorResponse"/> class.
/// </summary>
public ErrorResponse()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ErrorResponse"/> class.
/// </summary>
/// <param name="ex"><see cref="Exception"/> instance.</param>
public ErrorResponse(Exception ex)
{
this.Message = ex.Message;
this.StackTrace = ex.StackTrace;
}
/// <summary>
/// Gets or sets the error message.
/// </summary>
[JsonProperty("message")]
public virtual string Message { get; set; }
/// <summary>
/// Gets the stack trace.
/// </summary>
[JsonProperty("stackTrace")]
public virtual List<string> StackTraces
{
get
{
return this.StackTrace
.Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
}
/// <summary>
/// Set the stack trace.
/// </summary>
[JsonIgnore]
public virtual string StackTrace { private get; set; }
}
}
<file_sep>/test/FunctionApp.Tests/Fixtures/FunctionAppServerFixture.cs
using System;
using System.Net;
namespace FunctionApp.Tests.Fixtures
{
/// <summary>
/// This represents the fixture entity for the Function app service.
/// </summary>
public class FunctionAppServerFixture : ServerFixture
{
private const string FunctionAppNameKey = "FunctionAppName";
private const string FunctionAuthKeyKey = "FunctionAuthKey";
private readonly string _functionAppName;
private readonly string _functionAuthKey;
/// <summary>
/// Initializes a new instance of the <see cref="FunctionAppServerFixture"/> class.
/// </summary>
public FunctionAppServerFixture()
{
this._functionAppName = Environment.GetEnvironmentVariable(FunctionAppNameKey);
this._functionAuthKey = Environment.GetEnvironmentVariable(FunctionAuthKeyKey);
}
/// <inheritdoc />
public override string GetHealthCheckUrl(HttpStatusCode statusCode = HttpStatusCode.OK)
{
return $"https://{this._functionAppName}.azurewebsites.net/api/ping?code={this._functionAuthKey}";
}
}
}<file_sep>/src/FunctionApp/Functions/IHealthCheckFunction.cs
using Aliencube.AzureFunctions.Extensions.DependencyInjection.Abstractions;
using Microsoft.Extensions.Logging;
namespace FunctionApp.Functions
{
/// <summary>
/// This provides interfaces to the <see cref="HealthCheckFunction"/> class.
/// </summary>
public interface IHealthCheckFunction : IFunction<ILogger>
{
}
}<file_sep>/src/FunctionApp/Functions/HealthCheckFunction.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Aliencube.AzureFunctions.Extensions.DependencyInjection.Abstractions;
using FunctionApp.Configurations;
using FunctionApp.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace FunctionApp.Functions
{
/// <summary>
/// This represents the function entity for health check.
/// </summary>
public class HealthCheckFunction : FunctionBase<ILogger>, IHealthCheckFunction
{
private readonly ExternalApiSettings _settings;
private readonly HttpClient _httpClient;
/// <summary>
/// Initializes a new instance of the <see cref="HealthCheckFunction"/> class.
/// </summary>
/// <param name="settings"><see cref="ExternalApiSettings"/> instance.</param>
/// <param name="httpClient"><see cref="HttpClient"/> instance.</param>
public HealthCheckFunction(ExternalApiSettings settings, HttpClient httpClient)
{
this._settings = settings ?? throw new ArgumentNullException(nameof(settings));
this._httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}
/// <inheritdoc />
public override async Task<TOutput> InvokeAsync<TInput, TOutput>(TInput input, FunctionOptionsBase options = null)
{
var result = (IActionResult)null;
var requestUri = $"{this._settings.BaseUri.TrimEnd('/')}/{this._settings.Endpoints.HealthCheck.TrimStart('/')}";
using (var response = await this._httpClient.GetAsync(requestUri).ConfigureAwait(false))
{
try
{
response.EnsureSuccessStatusCode();
result = new OkResult();
}
catch (Exception ex)
{
var error = new ErrorResponse(ex);
result = new ObjectResult(error) { StatusCode = (int)response.StatusCode };
}
}
return (TOutput)result;
}
}
}
<file_sep>/test/FunctionApp.Tests/Fixtures/LocalhostServerFixture.cs
using System.Net;
using MbDotNet;
using MbDotNet.Enums;
namespace FunctionApp.Tests.Fixtures
{
/// <summary>
/// This represents the fixture entity for the localhost server.
/// </summary>
public class LocalhostServerFixture : ServerFixture
{
private readonly MountebankClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="LocalhostServerFixture"/> class.
/// </summary>
public LocalhostServerFixture()
{
this._client = new MountebankClient();
}
/// <inheritdoc />
public override string GetHealthCheckUrl(HttpStatusCode statusCode = HttpStatusCode.OK)
{
this._client.DeleteImposter(8080);
var imposter = this._client.CreateHttpImposter(8080, statusCode.ToString());
imposter.AddStub().OnPathAndMethodEqual("/api/ping", Method.Get).ReturnsStatus(statusCode);
this._client.Submit(imposter);
return "http://localhost:7071/api/ping";
}
}
}<file_sep>/src/FunctionApp/HealthCheckHttpTrigger.cs
using System;
using System.Net;
using System.Threading.Tasks;
using FunctionApp.Functions;
using FunctionApp.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
namespace FunctionApp
{
/// <summary>
/// This represents the HTTP trigger entity for health check.
/// </summary>
public class HealthCheckHttpTrigger
{
private readonly IHealthCheckFunction _function;
/// <summary>
/// Initializes a new instance of the <see cref="HealthCheckHttpTrigger"/> class.
/// </summary>
/// <param name="function"></param>
public HealthCheckHttpTrigger(IHealthCheckFunction function)
{
this._function = function ?? throw new ArgumentNullException(nameof(function));
}
/// <summary>
/// Invokes a ping request.
/// </summary>
/// <param name="req"><see cref="HttpRequest"/> instance.</param>
/// <param name="log"><see cref="ILogger"/> instance.</param>
/// <returns>Returns the <see cref="IActionResult"/> instance.</returns>
[FunctionName(nameof(HealthCheckHttpTrigger.PingAsync))]
public async Task<IActionResult> PingAsync(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "ping")] HttpRequest req,
ILogger log)
{
this._function.Log = log;
var result = (IActionResult)null;
try
{
result = await this._function
.InvokeAsync<HttpRequest, IActionResult>(req)
.ConfigureAwait(false);
}
catch (Exception ex)
{
var error = new ErrorResponse(ex);
result = new ObjectResult(error) { StatusCode = (int)HttpStatusCode.InternalServerError };
}
return result;
}
}
}<file_sep>/src/FunctionApp/StartUp.cs
using System.Net.Http;
using FunctionApp.Configurations;
using FunctionApp.Functions;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(FunctionApp.StartUp))]
namespace FunctionApp
{
/// <summary>
/// This represents the IoC container entity.
/// </summary>
public class StartUp : FunctionsStartup
{
/// <inheritdoc />
public override void Configure(IFunctionsHostBuilder builder)
{
this.ConfigureHttpClient(builder.Services);
this.ConfigureAppSettings(builder.Services);
this.ConfigureFunctions(builder.Services);
}
private void ConfigureHttpClient(IServiceCollection services)
{
var httpClient = new HttpClient();
services.AddSingleton(httpClient);
//services.AddHttpClient<IHealthCheckFunction, HealthCheckFunction>();
}
private void ConfigureAppSettings(IServiceCollection services)
{
services.AddSingleton<AppSettings>();
services.AddSingleton(p => p.GetService<AppSettings>().ExternalApi);
}
private void ConfigureFunctions(IServiceCollection services)
{
services.AddTransient<IHealthCheckFunction, HealthCheckFunction>();
}
}
}
| 8d69903c2637babdf38903bd4d8f60486b61868e | [
"C#"
] | 13 | C# | mattwiz/Mountebank-Integration-Testing | 337eed4b8f5707d29f7d11225359990995bc6cdc | b8ea14d1eeb0d39227a93fd06a1a2cbc097a4236 |
refs/heads/master | <repo_name>byronjohnson/gulp-wordpress<file_sep>/gulpfile.js
// Load plugins
var gulp = require('gulp'),
sass = require('gulp-sass'),
babel = require('gulp-babel');
sourcemaps = require('gulp-sourcemaps'),
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer'),
cssnext = require('postcss-cssnext'),
precss = require('precss'),
minifycss = require('gulp-minify-css'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
imagemin = require('gulp-imagemin'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
notify = require('gulp-notify'),
cache = require('gulp-cache'),
livereload = require('gulp-livereload'),
del = require('del'),
browserSync = require('browser-sync'),
livereload = require('gulp-livereload');
// Styles
gulp.task('styles', function() {
var processors = [
cssnext({flexbox: true, browsers: ['last 2 versions' ,'iOS 6', 'iOS 7']}),
precss
];
return gulp.src('scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(postcss(processors))
.pipe(sourcemaps.write('.'))
.pipe(minifycss({processImport: false}))
.pipe(gulp.dest('./'))
.pipe(gulp.dest('dist/styles'))
.pipe(livereload())
.pipe(notify({ message: 'Styles task complete' }));
});
// Scripts
gulp.task('scripts', gulp.series(function() {
return gulp.src(['js/**/*.js' ])
.pipe(jshint('.jshintrc'))
.pipe(jshint.reporter('default'))
.pipe(concat('main.js'))
.pipe(babel({
presets: ['@babel/env']
}))
.pipe(gulp.dest('dist/scripts'))
.pipe(rename({ suffix: '.min' }))
.pipe(uglify())
.pipe(gulp.dest('dist/scripts'))
.pipe(notify({ message: 'Scripts task complete' }));
}));
// Images
gulp.task('images', gulp.series(function() {
return gulp.src('ui/**/*')
.pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))
.pipe(gulp.dest('dist/images'))
.pipe(notify({ message: 'Images task complete' }));
}));
// Clean
gulp.task('clean', gulp.series(function(done) {
del(['dist/assets/css', 'dist/assets/js', 'dist/assets/img'], done);
done();
}));
// Default task
// gulp.task('default', ['clean'], function() {
// gulp.start('styles', 'scripts', 'images');
// });
gulp.task('default', gulp.series('clean', gulp.parallel('styles', 'scripts', 'images'),
function (done) { done(); }
));
// Watch
gulp.task('watch', function(done) {
// Watch .scss files
gulp.watch('scss/**/*.scss', gulp.series('styles'));
// Watch .js files
gulp.watch('js/**/*.js', gulp.series('scripts'));
// Watch image files
gulp.watch('ui/**/*', gulp.series('images'));
// Create LiveReload server
livereload.listen();
// Watch any files in dist/, reload on change
gulp.watch(['dist/**']).on('change', livereload.changed);
done();
}); | 284d0d2d3d2d8d167ba7d8e4cc8f868fd984e479 | [
"JavaScript"
] | 1 | JavaScript | byronjohnson/gulp-wordpress | d28a1015f4272f9b4dbc03ad02b243db4ff3c910 | a3d25df0d3c260aa9fe6734a71a98dd148a168fb |
refs/heads/master | <repo_name>easychen/LazyPHP4<file_sep>/source/_lp/lib/functions.php
<?php
use \Lazyphp\Core\Database as Database ;
use \Lazyphp\Core\Datameta as Datameta ;
require_once FROOT . 'lib' . DS . 'flight' . DS . 'net' . DS . 'Response.php';
use \flight\net\Response as response;
// == 日志函数 ==========================
function dlog($log,$type='log',$css='')
{
$log_file = AROOT . 'compiled'.DS .'log.txt' ;
if( is_array($log) ) $log = print_r( $log , true );
if( is_writable( $log_file ) )
file_put_contents( $log_file, $log . '@'.time() . PHP_EOL , FILE_APPEND );
elseif( on_sae() )
{
sae_debug( $log );
}
}
// == 状态相关函数 ==========================
function is_devmode(){ return c('mode') == 'dev'; }
function on_sae(){ return defined('SAE_APPNAME'); }
// == 迅捷函数 ==========================
function t( $str ){ return trim($str); }
function u( $str ){ return urlencode($str); }
function i( $str ){ return intval($str); }
function z( $str ){ return strip_tags($str); }
function v( $str )
{
if(isset($_POST[$str]))
{
return $_POST[$str];
}
elseif(isset($_GET[$str]))
{
return $_GET[$str];
}
elseif(isset($_REQUEST[$str]))
{
return $_REQUEST[$str];
}
else
{
return false;
}
}
function g( $str ){ return isset( $GLOBALS[$str] ) ? $GLOBALS[$str] : false; }
function ne( $str ){ return strlen($str) > 0 ; }
function nz( $int ){ return intval($int) > 0 ; }
// 读取配置文件,支持二维数组(通过subkey
function c( $key , $subkey = null )
{
if( isset( $GLOBALS['lpconfig'][$key] ) )
{
if( $subkey != null && is_array( $GLOBALS['lpconfig'][$key] ) )
return $GLOBALS['lpconfig'][$key][$subkey];
else
return $GLOBALS['lpconfig'][$key];
}
else return false;
}
// == 数据库相关函数 ==========================
function s( $str ){ return trim(db()->quote($str),"'"); }
function db()
{
if( !isset( $GLOBALS['_LP4_DB'] ) )
$GLOBALS['_LP4_DB'] = new Database();
return $GLOBALS['_LP4_DB'];
}
function get_data( $sql )
{
return db()->getData($sql)->toArray();
}
function get_line( $sql )
{
return db()->getData($sql)->toLine();
}
function get_var( $sql )
{
return db()->getData($sql)->toVar();
}
function run_sql( $sql )
{
return db()->runSql( $sql );
}
function get_bind_params( $sql )
{
$reg = '/:([a-z_][0-9a-z_]*)/is';
if( preg_match_all($reg, $sql, $out) )
{
return $out[1];
}
return false;
}
function type2pdo( $type )
{
if( $type == 'int' )
{
return PDO::PARAM_INT;
}
else return PDO::PARAM_STR;
}
function load_data_from_file( $file , $pdo )
{
$sql_contents = preg_replace( "/(#.+[\r|\n]*)/" , '' , file_get_contents( $file ));
$sqls = split_sql_file( $sql_contents );
foreach ($sqls as $sql)
$pdo->exec( $sql );
}
function split_sql_file($sql, $delimiter = ';')
{
$sql = trim($sql);
$char = '';
$last_char = '';
$ret = array();
$string_start = '';
$in_string = FALSE;
$escaped_backslash = FALSE;
for ($i = 0; $i < strlen($sql); ++$i) {
$char = $sql[$i];
// if delimiter found, add the parsed part to the returned array
if ($char == $delimiter && !$in_string) {
$ret[] = substr($sql, 0, $i);
$sql = substr($sql, $i + 1);
$i = 0;
$last_char = '';
}
if ($in_string) {
// We are in a string, first check for escaped backslashes
if ($char == '\\') {
if ($last_char != '\\') {
$escaped_backslash = FALSE;
} else {
$escaped_backslash = !$escaped_backslash;
}
}
// then check for not escaped end of strings except for
// backquotes than cannot be escaped
if (($char == $string_start)
&& ($char == '`' || !(($last_char == '\\') && !$escaped_backslash))) {
$in_string = FALSE;
$string_start = '';
}
} else {
// we are not in a string, check for start of strings
if (($char == '"') || ($char == '\'') || ($char == '`')) {
$in_string = TRUE;
$string_start = $char;
}
}
$last_char = $char;
} // end for
// add any rest to the returned array
if (!empty($sql)) {
$ret[] = $sql;
}
return $ret;
}
// == 元数据构建相关函数 ==========================
function load_route_file( $force = false )
{
if( !file_exists(c('route_file')) || true == $force )
build_route_file();
if(!require c('route_file')) throw new \Exception("Build route file fail");
}
function build_route_file( $return = false )
{
$meta = array();
if($cfiles = glob( AROOT . 'controller' . DS . '*Controller.php' ))
foreach( $cfiles as $cfile )
require_once $cfile;
if($classes = get_declared_classes())
{
$ret = array();
foreach( $classes as $class )
{
if( end_with($class , 'Controller') )
{
// 开始遍历
$ref = new \ReflectionClass($class);
if($methods = $ref->getMethods())
foreach( $methods as $method )
{
$item = array();
if( $item['meta'] = format_meta(parse_comment( $method->getDocComment() )) )
{
$item['class'] = $class;
$item['method'] = $method->name;
$item['meta']['binding'] = get_param_info($method->getParameters());
if( isset( $item['meta']['LazyRoute'][0]['route'] ) )
$item['meta']['route'][] = array( 'uri' => $item['meta']['LazyRoute'][0]['route'] , 'params' => get_route_params($item['meta']['LazyRoute'][0]['route']));
$ret[] = $item;
}
}
}
}
if( count($ret) > 0 )
{
foreach( $ret as $method_info )
{
// 只处理标记了路由的方法
if( isset( $method_info['meta']['route'] ) )
{
//print_r( $method_info['meta']['route'] );
$key = cmkey( $method_info );
//echo "{$method_info['class']} , {$method_info['method']} = $key (build) \r\n";
$meta[$key] = $method_info['meta'];
// 生成路由部分代码
foreach( $method_info['meta']['route'] as $route )
{
$source[] = '$app->'."route('" . t($route['uri']) . "',array( '" . $method_info['class'] . "','" . $method_info['method'] . "'));";
}
}
}
}
}
$GLOBALS['meta'] = $meta;
if( isset( $source ) && is_array($source) && count($source) > 0 )
{
$source_code = build_source_code( $source , $meta );
if( $return ) return $source_code;
else save_route_file( $source_code );
}
}
function save_route_file($source_code)
{
$dir = dirname(c('route_file'));
if( !file_exists( $dir ) ) mkdir( $dir , 0777 );
if( !is_writable( $dir ) )
{
throw new \Exception( "compiled dir not writable" );
return false;
}
if( !file_put_contents(c('route_file'),$source_code) )
{
throw new \Exception( "Build route file fail" );
return false;
}
return true;
}
function get_param_info( $params )
{
if( !$params ) return false;
$ret = array();
foreach( $params as $param )
{
$info = array();
$info['name'] = $param->getName();
if( $param->isDefaultValueAvailable() ) $info['default'] = $param->getDefaultValue();
$ret[$info['name']] = $info;
}
return $ret;
}
function build_source_code( $source , $meta = null )
{
// header
$content = '<' . '?php ' . "\r\n" ;
$content .= 'namespace Lazyphp\Core {' . "\r\n" ;
// exception
$content .= build_exception_code();
$content .= '}' . "\r\n" ;
$content .= 'namespace{' . "\r\n" ;
// meta
if( is_array($meta) )
$content .= '$GLOBALS[\'meta\'] = ' . var_export( $meta , true ) .';'. "\r\n";
// route and exec
$content .= '$app = new \Lazyphp\Core\Application();' . "\r\n" ;
$content .= join( "\r\n" , $source )."\r\n" ;
$content .= '$app->run();'. "\r\n";
$content .= '}' . "\r\n" ;
return $content;
}
function build_exception_code()
{
if( !isset($GLOBALS['rest_errors'])
|| !is_array($GLOBALS['rest_errors'])
|| count($GLOBALS['rest_errors']) < 1 )
return "";
else
{
foreach( $GLOBALS['rest_errors'] as $key => $value )
$excode[] = 'Class '
. ucfirst(strtolower($key))
.'Exception extends \Lazyphp\Core\RestException {}';
if( isset( $excode ) && is_array( $excode ) )
{
$code = 'Class RestException extends \Exception {}'."\r\n";
$code .= join( "\r\n" , $excode )."\r\n";
return $code;
}
}
}
function cmkey( $array , $method = null )
{
if( is_array( $array ) && isset( $array['class'] ) && isset( $array['method'] ) )
return md5( $array['class'] . '-' .$array['method'] );
else
return md5( $array . '-' . $method );
}
function format_meta( $meta )
{
if( !is_array( $meta ) ) return false;
foreach( $meta as $key => $value )
{
if( function_exists( $func = 'meta_format_'.strtolower($key) ) && is_array( $value ) && count($value) > 0 )
$value = array_map( $func , $value );
$ret[$key] = $value;
}
return isset($ret)?$ret:false;
}
function meta_format_params( $value )
{
if( isset($value['check'] ))
{
$ret['name'] = $value['name'];
$func_string = $value['check'];
$ret['filters'] = array_map( "trim" , explode('|',$func_string ) );
}
else
{
$ret['name'] = $value['name'];
$ret['filters'] = array( 'donothing' );
}
if( isset($value['cnname']) ) $ret['cnname'] = $value['cnname'];
return $ret;
}
function meta_format_lazyroute( $value )
{
//print_r($value);
return array
(
'route' => $value['method'] . ' ' . $value['uri'],
'ApiMethod' => '(type="'.$value['method'].'")',
'ApiRoute' => '(name="' . str2api( $value['uri'] ) . '")'
);
}
function str2api( $str )
{
// TODO
// 需要一个更好的正则
$str = str_replace( '(' , '' , $str);
$str = str_replace( ')' , '' , $str);
$str = preg_replace( '/(:(.+?))\//' , '/' , $str);
$str = preg_replace( '/(:(.+?))$/' , '' , $str);
$str = preg_replace( '/@(.+?)\//is' , '{$1}/' , $str);
$str = preg_replace( '/@(.+?)$/is' , '{$1}' , $str);
return $str;
/*
$reg = '/([a-zA-Z_-0-9]+?)/is';
if( preg_match_all($reg, $str, $out) )
{
return $out;
}
*/
}
function get_route_params( $route )
{
$reg = '/@([a-z_][0-9a-z_]*)/is';
if( preg_match_all($reg, $route, $out) )
{
return $out[1];
}
return false;
}
/*
function meta_format_table( $value )
{
$table = t(reset($value));
$pdo = new PDO(c('database_dev','dsn'),c('database_dev','user'),c('database_dev','password')) ;
$datameta = new Datameta( $pdo );
$ret['fields'] = $datameta ->getTableCols($table);
$ret['names'] = $datameta->getFields($table);
return isset($ret)?$ret:false;
}
function meta_format_route( $value )
{
$ret['uri'] = join( " " , $value );
$ret['params'] = get_route_params($ret['uri']);
return $ret;
}
function get_route_params( $route )
{
$reg = '/@([a-z_][0-9a-z_]*)/is';
if( preg_match_all($reg, $route, $out) )
{
return $out[1];
}
return false;
}
function meta_format_auto_type_check( $value )
{
return join( "" , $value );
}
function meta_format_field_check( $value )
{
if($value){
if( strpos($value[0],':') !== false )
{
$tinfo = explode(':',t($value[0]));
$ret['name'] = array_shift( $tinfo );
$func_string = array_shift( $tinfo );
$ret['filters'] = array_map( "trim" , explode('|',$func_string ) );
}
else
{
$ret['name'] = $value[0];
$ret['filters'] = array( 'donothing' );
}
if( isset($value[1]) ) $ret['cnname'] = $value[1];
return $ret;
}else
{
return $value;
}
}
function get_auto_check_filters( $field , $check_null = false )
{
switch ( $field['type'] )
{
case 'int':
$ret[] = 'i';
break;
case 'bigint':
$ret[] = 'wintval';
break;
default:
$ret[] = c('default_string_filter_func');
}
if( $check_null && $field['notnull'] ) $ret[] = 'check_not_empty';
return $ret;
}
function get_filters_by_type( $type )
{
if( $type == 'int' ) return 'i';
if( $type == 'bigint' ) return 'wintval';
return c('default_string_filter_func');
}
function cnname( $name )
{
if( isset( $GLOBALS['meta_key']) && isset( $GLOBALS['meta'] ) )
{
if( isset( $GLOBALS['meta'][$GLOBALS['meta_key']]['table'][0]['fields'][$name] ) )
{
$cnname = $GLOBALS['meta'][$GLOBALS['meta_key']]['table'][0]['fields'][$name]['comment'];
return ne($cnname)?$cnname:$name;
}
}
return $name;
}
*/
function array_key_index( $key , $array )
{
$i = 0 ;
foreach( $array as $k => $v )
{
if( $k == $key ) return $i;
else $i++;
}
}
/*
function meta_format_input_field( $value )
{
$ret = array( 'name' => ltrim($value[0],'$') , 'type' => $value[1] , 'cnname' => trim($value[2],'"') );
if( strpos($value[1],':') !== false )
{
$tinfo = explode(':',t($value[1]));
$ret['type'] = array_shift( $tinfo );
$func_string = array_shift( $tinfo );
$ret['filters'] = array_map( "trim" , explode('|',$func_string ) );
}
return $ret;
}
function meta_format_return_field($value)
{
return array( 'name' => ltrim($value[0],'$') , 'type' => $value[1] );
}
function meta_format_param($value)
{
return array( 'name' => ltrim($value[0],'$') , 'type' => $value[1] );
}
*/
/*
function filter_intval( $string )
{
$func = end( explode('_',__FUNCTION__));
if( function_exists($func) )
return call_user_func( $func , $string );
}
*/
function str2value( $str , $tolower = 1 )
{
$arr=array();
preg_replace_callback('/(\w+)="(.*?)"/',function($m) use(&$arr,$tolower){
$key=$tolower?strtolower($m[1]):$m[1];
$arr[$key]=$m[2];
},$str);
return $arr;
}
function parse_comment( $comment )
{
$comment = str_replace(PHP_EOL, "\n", $comment);
$ret = false;
//echo $comment;
$reg = '/@Api(.+?)\((.+?)\)\s*$/im';
if( preg_match_all($reg,$comment,$out) )
{
$ret = array() ; $i = 0 ;
while( isset( $out[1][$i] ) )
{
$ret[$out[1][$i]][] = str2value( $out[2][$i] );
$i++;
}
}
// print_r( $ret );
return $ret;
}
// 支持双引号内部空格的参数explode
// by @luofei614
function explode_quote( $str )
{
$reg = '/"[^"]+"|[^\s]+/i';
if( preg_match_all($reg,$str,$out) )
return $out[0];
else
return $str;
}
function get_source_code( $class , $method )
{
$ref_class = new \ReflectionClass($class);
$ref_method = $ref_class->getMethod( $method );
$filename = $ref_class->getFileName();
$start_line = $ref_method->getStartLine() + 1; // it's actually - 1, otherwise you wont get the function() block
$end_line = $ref_method->getEndLine()-1;
$length = $end_line - $start_line;
$source = file($filename);
return $body = join(PHP_EOL, array_map( "trim" , array_slice($source, $start_line, $length) ));
//return str_replace( '{__THIS__CLASS__}' , $class , $body );
}
// == 格式检查相关函数 ==========================
function check_email( $string )
{
return filter_var($string, FILTER_VALIDATE_EMAIL);
}
function check_int( $string )
{
return is_numeric($string);
}
function check_not_empty( $string )
{
return ne($string);
}
function check_not_zero( $int )
{
return nz($int);
}
function donothing( $string ){ return $string; }
// == 字符串Helper函数 ==========================
function first( $array )
{
return is_array($array)?reset($array):false;
}
function last( $array )
{
return is_array($array)?end($array):false;
}
function end_with( $str , $find )
{
$end = mb_substr( $str , 0-mb_strlen( $find , 'UTF-8' ) );
return $end == $find;
}
function begin_with( $str , $find )
{
return mb_strpos( $str , $find , 0 , 'UTF-8' ) === 0 ;
}
function wintval( $string )
{
$array = str_split( $string );
$ret = '';
foreach( $array as $v )
{
if( is_numeric( $v ) ) $ret .= intval( $v );
}
return $ret;
}
function rremove( $string , $remove )
{
$len = mb_strlen($remove,'UTF-8');
if( mb_substr( $string , -$len , $len , 'UTF-8' ) == $remove )
{
return mb_substr( $string , 0 , mb_strlen( $string , 'UTF-8' ) - $len , 'UTF-8' );
}
}
function hclean( $string )
{
$string = strip_tags($string,'<p><a><b><i><blockquote><h1><h2><ol><ul><li><img><div><br><pre><strike>');
$string = checkhtml( $string );
$string = tidytag( $string );
return $string;
}
function tidytag( $content )
{
$reg = '/(\.=["\'].+?["\'])/is';
return preg_replace( $reg , '' , $content );
}
function checkhtml($html)
{
preg_match_all("/\<([^\<]+)\>/is", $html, $ms);
$searchs[] = '<';
$replaces[] = '<';
$searchs[] = '>';
$replaces[] = '>';
if($ms[1]) {
$allowtags = 'img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote|h1|h2|pre|strike';
$ms[1] = array_unique($ms[1]);
foreach ($ms[1] as $value) {
$searchs[] = "<".$value.">";
$value = str_replace('&', '_uch_tmp_str_', $value);
$value = dhtmlspecialchars($value);
$value = str_replace('_uch_tmp_str_', '&', $value);
$value = str_replace(array('\\','/*'), array('.','/.'), $value);
$skipkeys = array('onabort','onactivate','onafterprint','onafterupdate','onbeforeactivate','onbeforecopy','onbeforecut','onbeforedeactivate',
'onbeforeeditfocus','onbeforepaste','onbeforeprint','onbeforeunload','onbeforeupdate','onblur','onbounce','oncellchange','onchange',
'onclick','oncontextmenu','oncontrolselect','oncopy','oncut','ondataavailable','ondatasetchanged','ondatasetcomplete','ondblclick',
'ondeactivate','ondrag','ondragend','ondragenter','ondragleave','ondragover','ondragstart','ondrop','onerror','onerrorupdate',
'onfilterchange','onfinish','onfocus','onfocusin','onfocusout','onhelp','onkeydown','onkeypress','onkeyup','onlayoutcomplete',
'onload','onlosecapture','onmousedown','onmouseenter','onmouseleave','onmousemove','onmouseout','onmouseover','onmouseup','onmousewheel',
'onmove','onmoveend','onmovestart','onpaste','onpropertychange','onreadystatechange','onreset','onresize','onresizeend','onresizestart',
'onrowenter','onrowexit','onrowsdelete','onrowsinserted','onscroll','onselect','onselectionchange','onselectstart','onstart','onstop',
'onsubmit','onunload','javascript','script','eval','behaviour','expression','style');
$skipstr = implode('|', $skipkeys);
$value = preg_replace(array("/($skipstr)/i"), '.', $value);
if(!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) {
$value = '';
}
$replaces[] = empty($value)?'':"<".str_replace('"', '"', $value).">";
}
}
$html = str_replace($searchs, $replaces, $html);
return $html;
}
function dhtmlspecialchars($string, $flags = null)
{
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = dhtmlspecialchars($val, $flags);
}
} else {
if($flags === null) {
$string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);
if(strpos($string, '&#') !== false) {
$string = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
}
} else {
if(PHP_VERSION < '5.4.0') {
$string = htmlspecialchars($string, $flags);
} else {
if(strtolower(CHARSET) == 'utf-8') {
$charset = 'UTF-8';
} else {
$charset = 'ISO-8859-1';
}
$string = htmlspecialchars($string, $flags, $charset);
}
}
}
return $string;
}
// */
// == 请求相关函数 ==========================
function ajax_echo( $info )
{
if( !headers_sent() )
{
header("Content-Type:text/html;charset=utf-8");
header("Expires: Thu, 01 Jan 1970 00:00:01 GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
}
echo $info;
}
if (!function_exists('apache_request_headers'))
{
function apache_request_headers()
{
foreach($_SERVER as $key=>$value)
{
if (substr($key,0,5)=="HTTP_")
{
$key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
$out[$key]=$value;
}
else
{
$out[$key]=$value;
}
}
return $out;
}
}
function is_ajax_request()
{
$headers = apache_request_headers();
return (isset( $headers['X-Requested-With'] ) && ( $headers['X-Requested-With'] == 'XMLHttpRequest' )) || (isset( $headers['x-requested-with'] ) && ($headers['x-requested-with'] == 'XMLHttpRequest' ));
}
function is_json_request()
{
$headers = apache_request_headers();
return (isset( $headers['Content-Type'] ) && ( clean_header($headers['Content-Type']) == 'application/json' ));
}
// == 响应相关函数 ==========================
function response()
{
if( !isset( $GLOBALS['_LP4_RSP'] ) )
$GLOBALS['_LP4_RSP'] = new response();
return $GLOBALS['_LP4_RSP'];
}
function send_json( $obj )
{
response()
->status(200)
->header('Content-Type', 'application/json')
->write(json_encode( $obj ))
->send();
}
function send_result( $data )
{
$ret['code'] = 0 ;
$ret['message'] = '' ;
$ret['data'] = $data ;
send_json( $ret );
}
function send_error( $type , $info = null )
{
$error = get_error( $type );
if( $info != null )
$error['message'] = $error['message'].' -' . $info ;
send_json($error);
}
function get_error( $type )
{
if( !isset( $GLOBALS['rest_errors'][$type] ) )
$error = array( 'code' => 99999 , 'message' => '其他' );
else
$error = $GLOBALS['rest_errors'][$type];
return $error;
}
// ======= web 页面 ====
function render( $data = NULL , $layout = NULL , $sharp = 'default' )
{
if( $layout == null )
{
if( is_ajax_request() )
{
$layout = 'ajax';
}
elseif( is_mobile_request() )
{
$layout = 'mobile';
}
else
{
$layout = 'web';
}
}
$GLOBALS['layout'] = $layout;
$GLOBALS['sharp'] = $sharp;
$layout_file = AROOT . 'view/' . $layout . '/' . $sharp . '.tpl.php';
if( file_exists( $layout_file ) )
{
@extract( $data );
require( $layout_file );
}
else
{
$layout_file = FROOT . 'view/' . $layout . '/' . $sharp . '.tpl.php';
if( file_exists( $layout_file ) )
{
@extract( $data );
require( $layout_file );
}
}
}
function info_page( $info , $title = '系统消息' )
{
if( is_ajax_request() )
$layout = 'ajax';
else
$layout = 'web';
$data['top_title'] = $data['title'] = $title;
$data['info'] = $info;
render( $data , $layout , 'info' );
}
function is_mobile_request()
{
$_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
$mobile_browser = '0';
if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
$mobile_browser++;
if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))
$mobile_browser++;
if(isset($_SERVER['HTTP_X_WAP_PROFILE']))
$mobile_browser++;
if(isset($_SERVER['HTTP_PROFILE']))
$mobile_browser++;
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda','xda-'
);
if(in_array($mobile_ua, $mobile_agents))
$mobile_browser++;
if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
$mobile_browser++;
// Pre-final check to reset everything if the user is on Windows
if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
$mobile_browser=0;
// But WP7 is also Windows, with a slightly different characteristic
if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
$mobile_browser++;
if($mobile_browser>0)
return true;
else
return false;
}
// == REST错误类型定义和Exception元数据 ==========================
$GLOBALS['rest_errors']['ROUTE'] = array( 'code' => '10000' , 'message' => 'route error' );
$GLOBALS['rest_errors']['INPUT'] = array( 'code' => '10001' , 'message' => 'input error' );
$GLOBALS['rest_errors']['DATABASE'] = array( 'code' => '30001' , 'message' => 'database error' );
$GLOBALS['rest_errors']['DATA'] = array( 'code' => '40001' , 'message' => 'data error' );
$GLOBALS['rest_errors']['AUTH'] = array( 'code' => '20001' , 'message' => 'auth error' );
<file_sep>/source/view/web/default.tpl.php
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<!-- Required meta tags always come first -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title><?=$data['title'] . ' | ' . c('site_name');?></title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="http://lib.sinaapp.com/js/bootstrap/3.0.0/css/bootstrap.min.css"/>
<!-- <link rel="stylesheet" href="http://libs.useso.com/js/font-awesome/4.2.0/css/font-awesome.min.css"/> -->
<link rel="stylesheet" href="/assets/css/stylish-portfolio.css"/>
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" type="text/css" href="/assets/css/app.css"/>
<?php if( isset($data['css']) && is_array( $data['css'] ) ): ?>
<?php foreach( $data['css'] as $cfile ): ?><link rel="stylesheet" type="text/css" href="/assets/css/<?=$cfile?>"/>
<?php endforeach; ?>
<?php endif; ?>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<?php
$header_file = dirname( __FILE__ ) . DS . 'header.tpl.php';
if( file_exists( $header_file ) ) include( $header_file );
$mainfile = dirname( __FILE__ ) . DS . 'main' . DS . g('c') . '_' . g('a') . '.tpl.php';
if( file_exists( $mainfile ) ) include( $mainfile );
else echo "<div class='notice-box'>没有设置模板文件,如需获取JSON,请将Header的Content-Type设置为application/json</div>";
$footer_file = dirname( __FILE__ ) . DS . 'footer.tpl.php';
if( file_exists( $footer_file ) ) include( $footer_file );
?>
</body>
</html>
<file_sep>/source/compiled/route.php
<?php
namespace Lazyphp\Core {
Class RestException extends \Exception {}
Class RouteException extends \Lazyphp\Core\RestException {}
Class InputException extends \Lazyphp\Core\RestException {}
Class DatabaseException extends \Lazyphp\Core\RestException {}
Class DataException extends \Lazyphp\Core\RestException {}
Class AuthException extends \Lazyphp\Core\RestException {}
}
namespace{
$GLOBALS['meta'] = array (
'70c907e8750f400eb470132e210b44cb' =>
array (
'Description' =>
array (
0 =>
array (
'section' => 'Demo',
'description' => '默认提示',
),
),
'LazyRoute' =>
array (
0 =>
array (
'route' => 'GET /',
'ApiMethod' => '(type="GET")',
'ApiRoute' => '(name="/")',
),
),
'Return' =>
array (
0 =>
array (
'type' => 'object',
'sample' => '{\'code\': 0,\'message\': \'success\'}',
),
),
'binding' => false,
'route' =>
array (
0 =>
array (
'uri' => 'GET /',
'params' => false,
),
),
),
'039a3032e1bca4289db765365162086a' =>
array (
'Description' =>
array (
0 =>
array (
'section' => 'Demo',
'description' => '系统提示',
),
),
'LazyRoute' =>
array (
0 =>
array (
'route' => 'GET /info',
'ApiMethod' => '(type="GET")',
'ApiRoute' => '(name="/info")',
),
),
'Return' =>
array (
0 =>
array (
'type' => 'object',
'sample' => '{\'code\': 0,\'message\': \'success\'}',
),
),
'binding' => false,
'route' =>
array (
0 =>
array (
'uri' => 'GET /info',
'params' => false,
),
),
),
'dad1d61c907e5e6cd02b71724c5383e9' =>
array (
'Description' =>
array (
0 =>
array (
'section' => 'Demo',
'description' => '系统提示',
),
),
'LazyRoute' =>
array (
0 =>
array (
'route' => 'POST /postonly',
'ApiMethod' => '(type="POST")',
'ApiRoute' => '(name="/postonly")',
),
),
'Return' =>
array (
0 =>
array (
'type' => 'object',
'sample' => '{\'code\': 0,\'message\': \'success\'}',
),
),
'binding' => false,
'route' =>
array (
0 =>
array (
'uri' => 'POST /postonly',
'params' => false,
),
),
),
'eb12852dde30c86f2681120ef5001954' =>
array (
'Description' =>
array (
0 =>
array (
'section' => 'Demo',
'description' => '乘法接口',
),
),
'LazyRoute' =>
array (
0 =>
array (
'route' => 'GET|POST /demo/times',
'ApiMethod' => '(type="GET|POST")',
'ApiRoute' => '(name="/demo/times")',
),
),
'Params' =>
array (
0 =>
array (
'name' => 'first',
'filters' =>
array (
0 => 'check_not_empty',
),
'cnname' => '第一个数',
),
1 =>
array (
'name' => 'second',
'filters' =>
array (
0 => 'check_not_empty',
),
'cnname' => '第二个数',
),
),
'Return' =>
array (
0 =>
array (
'type' => 'object',
'sample' => '{\'code\': 0,\'message\': \'success\'}',
),
),
'binding' =>
array (
'first' =>
array (
'name' => 'first',
),
'second' =>
array (
'name' => 'second',
),
),
'route' =>
array (
0 =>
array (
'uri' => 'GET|POST /demo/times',
'params' => false,
),
),
),
);
$app = new \Lazyphp\Core\Application();
$app->route('GET /',array( 'Lazyphp\Controller\LazyphpController','index'));
$app->route('GET /info',array( 'Lazyphp\Controller\LazyphpController','info'));
$app->route('POST /postonly',array( 'Lazyphp\Controller\LazyphpController','post'));
$app->route('GET|POST /demo/times',array( 'Lazyphp\Controller\LazyphpController','demo'));
$app->run();
}
<file_sep>/source/controller/LazyphpController.php
<?php
namespace Lazyphp\Controller;
class LazyphpController
{
public function __construct()
{
}
/**
* 默认提示
* @ApiDescription(section="Demo", description="默认提示")
* @ApiLazyRoute(uri="/",method="GET")
* @ApiReturn(type="object", sample="{'code': 0,'message': 'success'}")
*/
public function index()
{
//return lp_throw( "UNKNOW" , "1233" );
//return send_result( db()->getData("SHOW TABLES ")->toArray() );
$data['title'] = $data['top_title'] = 'Version 4.6';
return send_result( $data );
}
/**
* 系统提示
* @ApiDescription(section="Demo", description="系统提示")
* @ApiLazyRoute(uri="/info",method="GET")
* @ApiReturn(type="object", sample="{'code': 0,'message': 'success'}")
*/
public function info()
{
//$data['notice'] = ;
return send_error('SYSTEM','这里是信息提示页面');
}
/**
* 系统提示
* @ApiDescription(section="Demo", description="系统提示")
* @ApiLazyRoute(uri="/postonly",method="POST")
* @ApiReturn(type="object", sample="{'code': 0,'message': 'success'}")
*/
public function post()
{
$data = ndb()->fetchAll("show tables");
return send_result( $data );
// $data['notice'] = ;
// return send_error('SYSTEM','POST测试');
}
/**
* Demo接口
* @ApiDescription(section="Demo", description="乘法接口")
* @ApiLazyRoute(uri="/demo/times",method="GET|POST")
* @ApiParams(name="first", type="string", nullable=false, description="first", check="check_not_empty", cnname="第一个数")
* @ApiParams(name="second", type="string", nullable=false, description="second", check="check_not_empty", cnname="第二个数")
* @ApiReturn(type="object", sample="{'code': 0,'message': 'success'}")
*/
public function demo($first,$second)
{
return send_result(intval($first)*intval($second));
}
}
<file_sep>/source/config/app.php
<?php
$GLOBALS['lpconfig']['site_name'] = 'LazyPHP4.6';
$GLOBALS['lpconfig']['site_domain'] = '';
$GLOBALS['lpconfig']['mode'] = 'dev';
if(!on_sae())
$GLOBALS['lpconfig']['buildeverytime'] = true;
<file_sep>/route.php
<?php
// 处理URL中包含+号的情况
$_SERVER["PHP_SELF"] = str_replace(' ', '+', $_SERVER["PHP_SELF"] );
$path = $_SERVER['DOCUMENT_ROOT'] . $_SERVER["PHP_SELF"];
$uri = $_SERVER["REQUEST_URI"];
//print_r( $_SERVER );
$GLOBALS['lpconfig']['env'] = 'dev';
// 如果文件和目录存在,直接访问
if (file_exists($path))
{
$path2 = pathinfo($_SERVER["SCRIPT_FILENAME"]);
$header = false;
if( $path2['extension'] == 'ttf' ) $header = 'application/font-sfnt';
if( $path2['extension'] == 'eot' ) $header = 'application/vnd.ms-fontobject';
if( $path2['extension'] == 'woff' ) $header = 'application/font-woff';
if( $header )
{
header("Content-Type: ".$header);
readfile($_SERVER["SCRIPT_FILENAME"]);
}
else
return false;
}
else
{
putenv("REQUEST_URI=".$_SERVER["REQUEST_URI"]);
header("Access-Control-Allow-Origin: *");
require __DIR__ . '/index.php';
}
<file_sep>/source/lib/functions.php
<?php
function table( $name )
{
if( !isset( $GLOBALS['LP_LDO_'.$name] ) )
{
$GLOBALS['LP_LDO_'.$name] = new \Lazyphp\Core\Ldo($name);
}
return $GLOBALS['LP_LDO_'.$name];
}
function ndb( $dsn = null, $user = null, $password = null )
{
if( $dsn === null )
{
$dsn = c('database','dsn');
$user = c('database','user');
$password = c('database','password');
}
$key = "_LP_NDB" . md5( $dsn.'.'.$user.'.'.$password );
if( !isset( $GLOBALS[$key] ) )
{
$GLOBALS[$key] = new Nette\Database\Connection($dsn, $user, $password);
}
return $GLOBALS[$key];
}
function lp_throw( $type , $info , $args = null )
{
if( !is_array( $args )) $args = [ $args ] ;
$code = isset( c('error_type')[$type] ) ? c('error_type')[$type] : 99999;
$message = '[' . $type . ']' . sprintf( $info , ...$args );
throw new \Lazyphp\Core\LpException( $message , $code , $info , $args );
}
function lp_now()
{
return date("Y-m-d H:i:s");
}
function lp_uid()
{
return isset( $_SESSION['uid'] ) ? intval( $_SESSION['uid'] ) : 0;
}
<file_sep>/index.php
<?php
/**
* LazyPHP4 - 面向API的轻框架
* @license BSD
* @author @Easy
* @Email <EMAIL>
*/
// 定义系统常量
define( 'DS' , DIRECTORY_SEPARATOR );
define( 'AROOT' , dirname( __FILE__ ) . DS . 'source' . DS );
// 载入核心框架初始化脚本
require 'source' . DS . '_lp' . DS .'lp.init.php';
<file_sep>/source/_lp/lib/Lazyphp/Core/Database.php
<?php
namespace Lazyphp\Core;
use \PDO as PDO;
class Database extends LpObject
{
var $result = false;
public function __construct( $dsn = null , $user = null , $password = <PASSWORD> )
{
if( is_object( $dsn ) && strtolower(get_class( $dsn )) == 'pdo' )
{
$this->pdo = $dsn;
}
else
{
if( $dsn == null )
{
$dsn = c('database','dsn');
$user = c('database','user');
$password = c('database','password');
}
$this->pdo = new PDO( $dsn , $user , $password );
}
if( is_devmode() )
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->exec("SET NAMES 'utf8mb4';");
}
// get data to result set
public function getData( $sql )
{
$args = func_get_args();
array_unshift($args, 'getdata');
return call_user_func_array(array($this, 'bindData'),$args );
}
public function runSql()
{
$args = func_get_args();
array_unshift($args, 'runsql');
return call_user_func_array(array($this, 'bindData'),$args );
}
/**
* bindData 用于处理带绑定支持的SQL
* 第一个参数为 TYPE , 当 TYPE = getdata 时,产生返回内容。否则为执行语句。
*/
protected function bindData()
{
$this->result=false;
$arg_num = func_num_args();
$arg_num = $arg_num - 1;
$args = func_get_args();
$type = array_shift($args);
if( $arg_num < 1 )
{
throw new \PdoException("NO SQL PASSBY");
return $this;
}
else
{
if( $arg_num == 1 )
{
$sql = $args[0];
}
else
{
// 绑定
$sql = array_shift($args);
if( $params = get_bind_params($sql) )
{
//$sth = $this->pdo->prepare( $sql );
$meta = $GLOBALS['meta'][$GLOBALS['meta_key']];
if( isset( $meta['table'][0]['fields'] ) )
$fields = $meta['table'][0]['fields'];
$replace = array();
foreach( $params as $param )
{
$value = array_shift( $args );
if( isset( $fields[$param] ) && type2pdo($fields[$param]['type']) == PDO::PARAM_INT )
{
$replace[':'.$param] = intval($value);
//$sth->bindValue(':'.$param, $value , type2pdo($fields[$param]['type']));
}
else
{
$replace[':'.$param] = "'" . s($value) . "'";
//$sth->bindValue(':'.$param, $value , PDO::PARAM_STR);
}
}
$sql = str_replace( array_keys($replace), array_values($replace), $sql );
}
}
if( 'getdata' == $type )
{
foreach( $this->pdo->query( $sql , PDO::FETCH_ASSOC ) as $item )
{
if( is_array($this->result) ) $this->result[] = $item;
else $this->result = array( '0' => $item );
}
}
else
{
$this->result = $this->pdo->exec( $sql );
}
//print_r( $this->result );
return $this;
}
return $this;
}
// export
public function toLine()
{
if( !isset($this->result) ) return false;
$ret = $this->result;
$this->result = null;
return first($ret);
}
public function toVar( $field = null )
{
if( !isset($this->result) ) return false;
$ret = $this->result;
$this->result = null;
if( $field == null )
return first(first($ret));
else
return isset($ret[0][$field])?$ret[0][$field]:false;
}
public function toArray()
{
if( !isset($this->result) ) return false;
$ret = $this->result;
$this->result = null;
return $ret;
}
public function col( $name )
{
return $this->toColumn($name);
}
public function toColumn( $name )
{
if( !isset($this->result) ) return false;
$rs = $this->result;
$this->result = null;
if( !isset( $rs ) || !is_array($rs) ) return false;
foreach( $rs as $line )
if( isset($line[$name]) ) $ret[] = $line[$name];
return isset($ret)?$ret:false;
}
public function index( $name )
{
return $this->toIndexedArray($name);
}
public function toIndexedArray( $name )
{
if( !isset($this->result) ) return false;
$rs = $this->result;
$this->result = null;
if( !isset( $rs ) || !is_array($rs) ) return false;
foreach( $rs as $line )
$ret[$line[$name]] = $line;
return isset($ret)?$ret:false;
}
public function quote( $string )
{
return $this->pdo->quote( $string );
}
public function lastId()
{
return $this->pdo->lastInsertId();
}
}
<file_sep>/README.md
LazyPHP4.6
[TOC]
# 更新日志
- 2020.12.28 调整目录结构,添加安装和开发命令(robo.li)
## 4.6 版本
- flightphp 更新
- 文档生成部分修正引用jquery时cdn失效的问题
- 方法头注释解析支持行尾空白格
- 添加 Nette Database Core ,通过 ndb() 方法全局引用,使用说明见 https://doc.nette.org/en/3.0/database-core
- 添加 robo 文件,支持安装、启动测试环境的命令
# LazyPHP3、LazyPHP4和LazyPHP4.5

先介绍下LazyPHP各个版本的关系。LazyPHP一直是我的自用框架,所以很大程序上它都是随着我所认为的开发趋势一步步演进的。
LP3形成于新浪云时期,它专注于降低学习成本。通过反向封装面向对象为函数接口,甚至能帮助不了解面向对象的程序员写出强壮的程序。因为逻辑的简单性,在SAE相关项目上大量使用。
LP4则是我创业后为JobDeer相关项目的需求而设计的版本。作为一家移动互联网时代的创业公司,我们需要通过一套框架来支持网站和客户端。LP3还停留在ajax渲染的时代,所以我面向API对LP进行了重新设计。
以下是LP4的特性:
## 为API设计
在古代,PHP通常被视为HTML和Data之间的胶水,用来渲染和输出页面。当手机成为人类身体的一部分后,我们发现几乎所有的网站、产品都不可避免的遇到一个需求:多平台整合。
### API先行
如果说响应式布局还能在不同大小的浏览器上为混合式编程挽回一点局面的话,在现在这个APP风行的年代,为了兼容各种客户端(iOS、Android、电视、平板、汽车、手表),业务数据必须变成API接口。MVC的模式变异了,M被彻底分离为接口。PHP未来的核心,将是处理API。
### 相关功能
LP4就是在这样一个背景下设计的,所以比起3,它增加了很多API相关的功能
- 整合flight,用于处理RestFul请求。
- controller支持函数注释,可用于指定路由、验证输入参数、生成交互式文档
- 为了能自动调整路由,提供了编译工具_build.php,用于生成meta文件和路由代码
具体起来呢,就这样:
```php
<?php
/**
* 文档分段信息
* @ApiDescription(section="User", description="查看用户详细信息")
* @ApiLazyRoute(uri="/user(/@id:[0-9]+",method="GET")
* @ApiParams(name="id", type="int", nullable=false, description="Uid", check="i|check_not_empty", cnname="用户ID")
* @ApiReturn(type="object", sample="{'id':123}")
*/
public function info($id)
{
if( !$user = db()->getData( "SELECT * FROM `user` WHERE `id` =:id LIMIT 1" , $id )->toLine() )
throw new \Lazyphp\core\DataException("UID 对应的用户数据不存在");
return send_result( $user );
}
?>
```
路由、输入检查和文档全部在注释中搞定,是不是很方便。
LP4的注释标记完全兼容[php-apidoc](https://github.com/calinrada/php-apidoc),但是扩展了两个标记。
#### @ApiLazyRoute ( 新增
指定方法对应的路由。method和uri部分都遵守[flightPHP](http://flightphp.com/learn)的语法。LP做的事情只是把它拼接起来。
#### @ApiParams ( 扩展
添加了 check和cnname两个属性,用来为参数指定检查函数,以及提供字段的中文解释(在错误提示时有用),如果不需要可以不写。
注意:文档生成已经默认整合到编译工具_build.php中了,生成好的文档在docs目录下。
## 规范化
- 引入了namespace和异常处理
- 整合了PHPUnit和Behat测试框架
- 整合了[Composer](https://getcomposer.org/),支持自动加载
- 整合了[Phinx](http://phinx.org/),可对数据库版本进行管理
## 自动化
- 整合LazyRest,通过可视化界面生成常规的接口代码(TODO)
# 手册和规范
## 安装
测试环境需要composer才能运行
### 安装composer
```
$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer
```
### 安装LP4依赖
```
$ cd where/lp4/root
$ composer install
```
### 运行
如果你在不可写的环境(比如SAE)运行LP4,请在上传代码前运行 php _build.php 来生成自动路由。
## 迅捷函数
- function t( $str ) // trim
- function u( $str ) // urlencode
- function i( $str ) // intval
- function z( $str ) // strip_tags
- function v( $str ) // $_REQUEST[$str]
- function g( $str ) // $GLOBALS[$str]
- function ne( $str ) // not emptyy
- function dlog($log) // 打印日志到文件
## 状态函数
- function is_devmode() // 开发模式
- function on_sae() // 是否运行于SAE
## 数据库相关函数
- function s( $str ) // escape
- function db() // 返回数据库对象
- function get_data( $sql ) // 根据SQL返回数组
- function get_line( $sql ) // 根据SQL返回单行数据
- function get_var( $sql ) // 根据SQL返回值
- function run_sql( $sql ) // 运行SQL
由于LP4在框架外层做了catch,所以数据库异常会被拦截,并以json格式输出。
LP4还提供了对象方式的数据库操作,返回结果更可控。
```php
<?php
db()->getData('SELECT * FROM `user`')->toArray(); // 返回数组
db()->getData('SELECT * FROM `user` WHERE `id` = :id' , $id )->toLine(); // 返回数组中的一行,参数绑定模式
db()->getData('SELECT COUNT(*) FROM `user`')->toVar(); // 返回具体数值
db()->getData('SELECT * FROM `user`')->toIndexedArray('id'); // 返回以ID字段为Key的数组
db()->getData('SELECT * FROM `user`')->toColumn('id'); // 返回ID字段值的一维数组
?>
```
### LDO
其实LP4还提供了一个针对表进行数据查询的对象 LDO , 首先从数据表new一个Ldo对象,然后就可以用getXXX语法来查询了。因为支持Limit以后,我实在没搞定正则,所以现在还有ByNothing这种奇葩结构。
嘛,在做简单查询时很好用,getAllById这样的。
```php
<?php
// 根据查询的函数名称自动生成查询语句
$member = new \Lazyphp\Core\Ldo('member');
$member->getAllById('1')->toLine();
$member->getNameById('1')->toVar();
$member->getDataById(array('name','avatar') , 1)->toLine();
$member->getAllByArray(array('name'=>'easy'))->toLine();
$member->findNameByNothing()->col('name');
$member->findNameByNothingLimit(array(2,5))->col('name');
?>
```
## Controller
和之前的版本一样,LP依然使用controller作为主入口。但访问路径从?a=&c=改为路由指定,因此,访问路径和controller名称以及method名称将不再有任何关联。
换句话说,你可以随意指定controller名称以及method名称,但注意其注释中的route不要重复,否则产生覆盖。
## 错误处理
在处理逻辑出错时可以直接抛出异常。
自带以下几类
```php
<?php
$GLOBALS['rest_errors']['ROUTE'] = array( 'code' => '10000' , 'message' => 'route error' );
$GLOBALS['rest_errors']['INPUT'] = array( 'code' => '10001' , 'message' => 'input error' );
$GLOBALS['rest_errors']['DATABASE'] = array( 'code' => '30001' , 'message' => 'database error' );
$GLOBALS['rest_errors']['DATA'] = array( 'code' => '40001' , 'message' => 'data error' );
?>
```
可在 _lp/lib/functions.php 文件尾部追加自己的错误类型。比如我们来添加一个时间异常。
第一步追加定义
```php
<?php
$GLOBALS['rest_errors']['TIME'] = array( 'code' => '888888' , 'message' => 'time system error' );
?>
```
然后就可以在controller的方法中抛出了
```
<?php
public function abc()
{
if( true ) throw new \Lazyphp\core\timeException("这里填写具体的错误信息");
}
?>
```
# LazyPHP4.5
LazyPHP4.5是LazyPHP4之上的一个版本,它将LazyPHP3的模板系统重新加了回来。之所以有这个版本,是因为我发现做一些小项目时,我们并不需要那么纯粹的API和客户端分离。毕竟全平台应用会消耗大量的时间,很多活动页面和MVP直接用PHP模板渲染来得更快。
当然,我可以用回LP3.1,但是用惯了LP4中的一些功能后,就各种回不去了。这不是正好有点时间么,所以顺手给LP4加上了模板系统。
## LP4.5的修改
### LP4易用性优化
#### 异常配置分离成独立文件
在LP4中,定义错误类型时,我们需要去 ```_lp/lib/functions.php``` 文件尾部追加自己的错误类型。LP4.5中,将这部分直接分离成了配置文件,直接修改 ```/config/exception.php``` 即可。
#### 添加默认页面和默认路由
LP4对新手有个大坑,就是配置完全正确时,访问根目录会提示404。这是因为演示用路由是 ```/demo/times/``` ,所以访问根目录404是正确的。
为了不让大家再次掉到坑里去,LP4.5中添加了根目录的演示页面。
#### 将配置文件中的自动编译打开,方便调试
LP4刚安装完时每次修改完代码都要运行 ```php _build.php``` 才能生效,这是因为配置文件中的开关默认关了。考虑到刚装完必然是要进行开发调试,LP4.5将其默认打开了。
```
$GLOBALS['lpconfig']['buildeverytime'] = true;
```
### 模板系统的引入
LP4.5引入了之前LP3的模板系统,但是又不完全一样,所以这一段请大家仔细读读。
#### 智能渲染
LP4.5引入了智能渲染的概念,简单的说,就是同一个页面,你要JSON我就按JSON渲染;你要Ajax我就按Ajax渲染;你要Web页面我就按Web来渲染。
具体的判断是根据请求头来识别的,不多说直接上代码:
```
function is_ajax_request()
{
$headers = apache_request_headers();
return (isset( $headers['X-Requested-With'] ) && ( $headers['X-Requested-With'] == 'XMLHttpRequest' )) || (isset( $headers['x-requested-with'] ) && ($headers['x-requested-with'] == 'XMLHttpRequest' ));
}
function is_json_request()
{
$headers = apache_request_headers();
return (isset( $headers['Content-Type'] ) && ( clean_header($headers['Content-Type']) == 'application/json' ));
}
```
这样会带来一个非常大的好处,就是我们的API接口和Web页面完全统一起来了,不用再为API写专门的代码了。
同时这也会带来一个潜在的安全大坑,因为以前我们用render去处理$data时,是在服务器端渲染的;而现在API和Web统一后,很多信息会通过JSON显示出来。类似对User表SELECT *,然后把密码吐出来这种事千万不要去做。
#### 模板目录
##### 目录变更
模板目录还是view,但下边直接就是具体的Layout类型了,去掉了之前多余的layout目录。
##### 模板文件路径和扩展名变更
- 模板文件名从原来的 ```$controller/$action.tpl.html ``` ,改成了 ```$controller_$action.tpl.php``` ,主要是为了减少目录层级。
- 注意模板文件后缀从 ```*.tpl.html``` 改为了 ```*.tpl.php``` ,主要是为了代码高亮和防泄漏。
##### 静态文件目录变更
静态文件从static目录改放到了assets目录。
##### 模板内的数组格式变更
因为使用模板直接渲染JSON对应的格式,所以多了一个data的维度。举个例子:
之前
```
$data['title'] = 'hi';
render( $data );
```
在模板里边直接用 $title就好。
现在
```
$data['title'] = 'hi';
send_result( $data );
```
在模板里边需要写成 $data['title']。因为send_result函数里,我们又包了一层:
```
function send_result( $data , $force_json = false )
{
$ret['code'] = 0 ;
$ret['message'] = '' ;
$ret['data'] = $data ;
if( is_json_request() || $force_json )
return send_json( $ret );
elseif( is_ajax_request() )
return render_ajax( $ret , 'default' );
else
return render_web( $ret , 'default' );
}
```
##### 其他调整
- 默认的Web布局从原来的两栏改为单栏。
- 更新Bootstrap到最新稳定版本3.3,同时还内置了Start Bootstrap的 ```Stylish Portfolio``` 模板,它是一个带侧栏菜单的Responsive模板,如果是给APP做Landing Page基本上直接改文字就可以了。
- 当然,国外的模板直接用不了的,所以还接地气的对CDN做了本土化,顺手把默认的背景图换成萌妹子了。

<file_sep>/RoboFile.php
<?php
/**
* This is project's console commands configuration for Robo task runner.
*
* @see http://robo.li/
*/
class RoboFile extends \Robo\Tasks
{
// define public methods as commands
public function install()
{
$this->_exec("cd source && composer install");
}
public function dev()
{
$this->_exec("php -S 0.0.0.0:8088 route.php");
}
}<file_sep>/source/RoboFile.php
<?php
/**
* This is project's console commands configuration for Robo task runner.
*
* @see http://robo.li/
*/
class RoboFile extends \Robo\Tasks
{
/**
* 初始化框架
*/
public function init()
{
$this->_exec("composer install");
}
/**
* 启动本地测试服务器
*/
public function dev()
{
$this->_exec("php -S 0.0.0.0:8000 route.php");
}
/**
* 编译
*/
public function build()
{
$this->_exec("php _build.php");
}
}<file_sep>/source/config/database.php
<?php
$GLOBALS['lpconfig']['site_db'] = 'c2';
// 兼容SAE
if( on_sae() )
{
$GLOBALS['lpconfig']['database'] = array
(
'adapter' => 'mysql',
'host' => SAE_MYSQL_HOST_M,
'name' => SAE_MYSQL_DB,
'user' => SAE_MYSQL_USER ,
'password' => <PASSWORD>,
'port' => SAE_MYSQL_PORT,
'charset' => 'utf8mb4'
);
$GLOBALS['lpconfig']['database']['dsn'] = $GLOBALS['lpconfig']['database']['adapter']
.':host=' . $GLOBALS['lpconfig']['database']['host']
. ';port=' . $GLOBALS['lpconfig']['database']['port']
. ';dbname=' . $GLOBALS['lpconfig']['database']['name']
. ';charset=' . $GLOBALS['lpconfig']['database']['charset'];
}
else
{
$GLOBALS['lpconfig']['database'] = array
(
'adapter' => 'mysql',
'host' => '127.0.0.1',
'name' => c('site_db'),
'user' => 'root',
'password' => '',
'port' => 3306,
'charset' => 'utf8mb4'
);
$GLOBALS['lpconfig']['database']['dsn'] = $GLOBALS['lpconfig']['database']['adapter']
.':host=' . $GLOBALS['lpconfig']['database']['host']
. ';port=' . $GLOBALS['lpconfig']['database']['port']
. ';dbname=' . $GLOBALS['lpconfig']['database']['name']
. ';charset=' . $GLOBALS['lpconfig']['database']['charset'];
}
$GLOBALS['lpconfig']['database_dev'] = array
(
'adapter' => 'mysql',
'host' => '127.0.0.1',
'name' => c('site_db'),
'user' => 'root',
'password' => '',
'port' => 3306,
'charset' => 'utf8mb4'
);
$GLOBALS['lpconfig']['database_dev']['dsn'] = $GLOBALS['lpconfig']['database_dev']['adapter']
.':host=' . $GLOBALS['lpconfig']['database_dev']['host']
. ';port=' . $GLOBALS['lpconfig']['database_dev']['port']
. ';dbname=' . $GLOBALS['lpconfig']['database_dev']['name']
. ';charset=' . $GLOBALS['lpconfig']['database_dev']['charset'];
<file_sep>/source/_build.php
<?php
if( !isset($argv) ) die('Please run it via commandline');
// build
/**** load lp framework ***/
define( 'DS' , DIRECTORY_SEPARATOR );
define( 'AROOT' , dirname( __FILE__ ) . DS );
// 定义常用跟路径
define( 'FROOT' , dirname( __FILE__ ) . DS . '_lp' . DS );
// 载入composer autoload
require AROOT . 'vendor' . DS . 'autoload.php';
require_once FROOT . 'lib' . DS . 'functions.php'; // 公用函数
require_once AROOT . 'lib' . DS . 'functions.php'; // 应用函数
require_once FROOT . 'config' . DS . 'core.php'; // 核心配置
require_once AROOT . 'config' . DS . 'database.php'; // 数据库配置
require_once AROOT . 'config' . DS . 'app.php'; // 应用配置
build_route_file();
// build doc
date_default_timezone_set('Asia/Chongqing');
use Lazyphp\Doc\Builder;
use Crada\Apidoc\Exception;
if($classes = get_declared_classes())
{
$ret = array();
foreach( $classes as $class )
{
if( end_with($class , 'Controller') )
{
$controll_classes[] = $class;
}
}
}
if( isset( $controll_classes ) )
{
$output_dir = AROOT.'docs';
$output_file = 'index.html'; // defaults to index.html
try {
$builder = new Builder($controll_classes, $output_dir, $output_file);
$builder->generate();
} catch (Exception $e) {
echo 'There was an error generating the documentation: ', $e->getMessage();
}
}
<file_sep>/source/view/web/footer.tpl.php
<!-- Footer -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-10 col-lg-offset-1 text-center">
<h4><strong>Theme by Start Bootstrap</strong>
</h4>
<p>3481 Melrose Place<br>Beverly Hills, CA 90210</p>
<ul class="list-unstyled">
<li><i class="fa fa-phone fa-fw"></i> (123) 456-7890</li>
<li><i class="fa fa-envelope-o fa-fw"></i> <a href="mailto:<EMAIL>"><EMAIL></a>
</li>
</ul>
<br>
<ul class="list-inline">
<li>
<a href="#"><i class="fa fa-facebook fa-fw fa-3x"></i></a>
</li>
<li>
<a href="#"><i class="fa fa-twitter fa-fw fa-3x"></i></a>
</li>
<li>
<a href="#"><i class="fa fa-dribbble fa-fw fa-3x"></i></a>
</li>
</ul>
<hr class="small">
<p class="text-muted">Copyright © Your Website 2015</p>
</div>
</div>
</div>
</footer>
<!-- jQuery first, then Bootstrap JS. -->
<script src="http://lib.sinaapp.com/js/jquery/2.2.4/jquery-2.2.4.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="http://lib.sinaapp.com/js/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<?php if( isset($data['js']) && is_array( $data['js'] ) ): ?>
<?php foreach( $data['js'] as $jfile ): ?><script type="text/javascript" src="/assets/script/<?=$jfile;?>" ></script>
<?php endforeach; ?>
<?php endif; ?>
<script type="text/javascript" src="/assets/script/app.js" ></script>
<!-- Custom Theme JavaScript -->
<script>
// Closes the sidebar menu
$("#menu-close").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
// Opens the sidebar menu
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
// Scrolls to the selected menu item on the page
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
<file_sep>/source/_lp/config/core.php
<?php
$GLOBALS['lpconfig']['app_name'] = 'LazyPHP4';
$GLOBALS['lpconfig']['lp_version'] = '0.1';
$GLOBALS['lpconfig']['route_file'] = AROOT . 'compiled' . DS .'route.php';
$GLOBALS['lpconfig']['default_string_filter_func'] = 'z';
$GLOBALS['lpconfig']['error_type'] = [
'INPUT'=>20001,
'AUTH'=>40001,
'NOTLOGIN'=>40301
];
<file_sep>/source/_lp/lib/Lazyphp/Core/LpException.php
<?php
namespace Lazyphp\Core;
class LpException extends \Exception
{
protected $message = 'Unknown exception';
protected $code = 0;
protected $info = "";
protected $args = [];
public function __construct($message, $code, $info, $args )
{
if (!$message) {
throw new $this('Unknown '. get_class($this));
}
parent::__construct($message, $code);
$this->info = $info;
$this->args = $args;
}
public function __toString()
{
return get_class($this) . " '{$this->message}'";
}
public function getInfo()
{
return $this->info;
}
public function getArgs()
{
return $this->args;
}
} | cc26684991a0c35aaceb1195da69e08d0dd85306 | [
"Markdown",
"PHP"
] | 17 | PHP | easychen/LazyPHP4 | 7180c1b9609286b519ff7265b87ddeeb058ea642 | 29f228cf7c135569ea8e3580c8f04f0b5d9483d9 |
refs/heads/master | <repo_name>mini-stack/face-recognition<file_sep>/人脸识别/摄像头_人脸识别.py
import cv2
detector_face = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
# 更改画面效果
# frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
faces = detector_face.detectMultiScale(frame, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow('Camera', frame)
key = cv2.waitKey(1)
if key == ord("q"):
break
if key == ord("s"):
cv2.imwrite("asd.png", frame)
cap.release()
cv2.destroyAllWindows()
| 3ee69cc23d8afacfd9bdc50cca278727bb92ff43 | [
"Python"
] | 1 | Python | mini-stack/face-recognition | b6a317ed27d785db4608724f102627f8797e2df5 | 7f55d1698509adde152d91c22b2276ace7d5eaa9 |
refs/heads/master | <repo_name>jrsearles/grunt-template-bundler<file_sep>/tasks/grunt_template_bundler.js
/*
* grunt-template-bundler
*
*
* Copyright (c) 2015 <NAME>
* Licensed under the MIT license.
*/
"use strict";
var minify = require("html-minifier").minify;
module.exports = function (grunt) {
grunt.registerMultiTask("templateBundle", "Grunt plugin which takes html files and ", function () {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
minify: true,
separator: grunt.util.linefeed,
wrapper: undefined,
minifyOptions: {
collapseWhitespace: true,
keepClosingSlash: true,
caseSensitive: true
}
});
// Iterate over all specified file groups.
this.files.forEach(function (file) {
// Concat specified files.
var output = file.src.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn("Source file \"" + filepath + "\" not found.");
return false;
} else {
return true;
}
}).map(function (filepath) {
var src = grunt.file.read(filepath);
if (options.minify) {
src = minify(src, options.minifyOptions);
}
if (options.wrapper) {
return options.wrapper(src, filepath);
}
return src;
}).join(grunt.util.normalizelf(options.separator));
grunt.file.write(file.dest, output);
grunt.log.writeln("File \"" + file.dest + "\" created.");
});
});
};
<file_sep>/README.md
# grunt-template-bundler
> Grunt plugin to concatenate and minify html templates
## Getting Started
This plugin requires Grunt.
If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
```shell
npm install grunt-template-bundler --save-dev
```
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
```js
grunt.loadNpmTasks('grunt-template-bundler');
```
## The "grunt-template-bundler" task
### Overview
In your project's Gruntfile, add a section named `templateBundle` to the data object passed into `grunt.initConfig()`.
```js
grunt.initConfig({
templateBundle: {
options: {
// Task-specific options go here.
},
your_target: {
// Target-specific file lists and/or options go here.
},
},
})
```
### Options
#### options.separator
Type: `String`
Default value: `newline`
A string value that is used to do something with whatever.
#### options.minify
Type: `Boolean`
Default value: `true`
Indicates whether to minify the html.
#### options.minifyOptions
Type: `Object`
Default value: `{
collapseWhitespace: true,
keepClosingSlash: true,
caseSensitive: true
}`
Minify options that are passed directly into the [HTML Minifier](https://github.com/kangax/html-minifier)
#### options.wrapper
Type: `Function`
Default value: `undefined`
If supplied this function will get the minified html and filepath as separate arguments and return a string which will be used in the output file.
## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).
## Release History
_(Nothing yet)_
## License
Copyright (c) 2015 <NAME>. Licensed under the MIT license.
<file_sep>/test/actual/template.js
jsMethod("<div data-bind=\"text: value\"/>");
jsMethod("<div>foo</div>"); | 2529af368a5bdcc94e27687e25080ef5f74dc5c6 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | jrsearles/grunt-template-bundler | fe27f1722eb03f70e171b9600c7ec0e551aa126a | 747e7d70cfc9d16e21320aa1bdeeda4f8b603037 |
refs/heads/master | <repo_name>leslieAIbin/Elasticsearch7.6.1-jd<file_sep>/src/main/java/com/zhangaibin/utils/HtmlParseUtil.java
package com.zhangaibin.utils;
import com.zhangaibin.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Leslie
* 2020/11/19 15:35
*/
public class HtmlParseUtil {
public static void main(String[] args) throws Exception {
new HtmlParseUtil().parseJD("大连理工").forEach(System.out::println);
}
public List<Content> parseJD(String keywords) throws Exception{
// 获取请求
// String url = "https://search.jd.com/Search?keyword=" + keywords+"&enc=utf-8";
// 指定编码集,防止中文乱码
Document document = null;
try {
document = Jsoup.parse(new URL("https://search.jd.com/Search?keyword=" + keywords + "&enc=utf-8"), 30000);
} catch (IOException e) {
System.out.println("---JDSearchHtmlParser.parse()失败---");
e.printStackTrace();
}
//解析网页(jsoup返回的document就是浏览器返回的Document对象)
//Document document = Jsoup.parse(new URL(url), 30000);
// 所有在js中的方法,都可以使用
Element element = document.getElementById("J_goodsList");
// 获取所有的li元素
Elements elements = element.getElementsByTag("li");
List<Content> goodList = new ArrayList<>();
// 获取元素内容,每个li标签
for (Element el : elements) {
String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
String price = el.getElementsByClass("p-price").eq(0).text();
String title = el.getElementsByClass("p-name").eq(0).text();
Content content = new Content();
content.setImg(img);
content.setPrice(price);
content.setTitle(title);
goodList.add(content);
}
return goodList;
}
}
<file_sep>/README.md
# ElasticSearch_jd
# 项目介绍
ElasticSearch入门,利用爬虫技术获取京东信息,放置到es,通过es进行检索
# 开发
1. IDEA 2019
2. SpringBoot
3. VUE
4. ElasticSearch 7.6.1
5. Jsoup
# 运行
1. 启动ElasticSear
2. 启动ElasticSearch-head
3. 运行主启动类EsJdApplication.class
4. 浏览器输入http://localhost:9090/parse/java (要爬取的书籍)(将爬取结果放入es)
5. http://localhost:9090 ,在搜索栏中输入java,就得到结果了,不过要先执行第4步,在es中有相应的东西才能有结果,目前中文不支持(即可以放进es,但得不到搜索结果)
# 参考
[狂神说](https://www.bilibili.com/video/BV17a4y1x7zq) 他公众号有相应资源
[nodejs安装](https://www.runoob.com/nodejs/nodejs-install-setup.html)
[cnpm安装](https://blog.csdn.net/wjnf012/article/details/80422313)
[ElasticSearch](https://mirrors.huaweicloud.com/elasticsearch/?C=N&O=D)
[logstash](https://mirrors.huaweicloud.com/logstash/?C=N&O=D)
[kibana](https://mirrors.huaweicloud.com/kibana/?C=N&O=D)
| 1cfd773baaa638438e64e0c013db2db511b52d65 | [
"Markdown",
"Java"
] | 2 | Java | leslieAIbin/Elasticsearch7.6.1-jd | e20ac21cf866168930be5da2deca2022d16ce772 | 29e537271429d5c7c7004bc674ab8388747a4d36 |
refs/heads/master | <repo_name>PankajPandey06/PageObjectModel<file_sep>/src/test/java/com/qa/testCases/LoginPageTest.java
package com.qa.testCases;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.qa.base.TestBase;
import com.qa.pages.BasePage;
import com.qa.pages.HomePage;
import com.qa.pages.LoginPage;
public class LoginPageTest extends TestBase {
BasePage basePage;
LoginPage loginPage;
HomePage homePage;
public LoginPageTest() {
super();
}
@BeforeMethod
public void setUp() {
initialization();
basePage = new BasePage();
loginPage = new LoginPage();
}
@Test(priority = 1)
public void loginPageTitleTest() {
String titleOfLoginpage = loginPage.verifyTitleOfLoginPage();
Assert.assertEquals(titleOfLoginpage, properties.getProperty("loginPageTitle"));
}
@Test(priority = 0)
public void loginButtonTest() {
basePage.clickOnLoginBtn();
}
@Test(priority = 2)
public void loginTest(){
basePage.clickOnLoginBtn();
homePage = loginPage.login(properties.getProperty("userName"), properties.getProperty("password"));
}
@AfterMethod
public void tearDown() {
teardown();
}
}
<file_sep>/src/main/java/com/qa/pages/SignUpPage.java
package com.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.qa.base.TestBase;
public class SignUpPage extends TestBase {
@FindBy(xpath = "//input[@name = 'email']")
WebElement emailId;
@FindBy(xpath = "//input[@name = 'phone']")
WebElement phone;
@FindBy(xpath = "//input[@name = 'terms']")
WebElement toc;
@FindBy(xpath = "//input[@class= 'search']")
WebElement dropDownCountry;
@FindBy(xpath = "//div[@class= 'recaptcha-checkbox-checkmark']")
WebElement captchaCheckbox;
@FindBy(xpath = "//button[contains(text(), 'Sign Up')]")
WebElement signUpButton;
// Initializing the Page Objects:
public SignUpPage() {
PageFactory.initElements(driver, this);
}
public String verifyTitleOfSignUpPage() {
return driver.getTitle();
}
}
<file_sep>/src/test/java/com/qa/testCases/BasePageTest.java
package com.qa.testCases;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.qa.base.TestBase;
import com.qa.pages.BasePage;
import com.qa.pages.SignUpPage;
public class BasePageTest extends TestBase {
BasePage basePage;
SignUpPage signUp;
public BasePageTest() {
super();
}
@BeforeMethod
public void setUp() {
initialization();
basePage = new BasePage();
}
@Test(priority = 1)
public void validateSignUpButtonTest() {
boolean signUpBtnFlag = basePage.validateSignUpbutton();
Assert.assertTrue(signUpBtnFlag);
}
@Test(priority = 2)
public void validateLoginButtonTest() {
boolean loginBtnFlag = basePage.validateLoginButton();
Assert.assertTrue(loginBtnFlag);
}
@Test(priority =3)
public void validateLoginTest(){
basePage.clickOnLoginBtn();
}
@AfterMethod
public void tearDown() {
teardown();
}
}
<file_sep>/src/test/java/com/qa/testCases/SignUpPageTest.java
package com.qa.testCases;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.qa.base.TestBase;
import com.qa.pages.BasePage;
import com.qa.pages.SignUpPage;
public class SignUpPageTest extends TestBase {
BasePage basePage;
SignUpPage signUpPage;
public SignUpPageTest() {
super();
}
@BeforeMethod
public void setUp() {
initialization();
basePage = new BasePage();
signUpPage = new SignUpPage();
}
@Test
public void verifyTitleOfSignUpPageTest() {
basePage.SignUpLandingpage();
String actualTitle = signUpPage.verifyTitleOfSignUpPage();
Assert.assertEquals(actualTitle, properties.getProperty("signUpPageTitle"));
}
@AfterMethod
public void tearDown() {
// teardown();
}
}
<file_sep>/target/classes/com/qa/config/config.properties
browser = chrome
URL = https://freecrm.com/
userName = your username
password = <PASSWORD>
signUpPageTitle = CRM
loginPageTitle = Free CRM software for any Business<file_sep>/src/main/java/com/qa/pages/LoginPage.java
package com.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.qa.base.TestBase;
public class LoginPage extends TestBase {
@FindBy(xpath = "//input[@name = 'email']")
WebElement emailId;
@FindBy(xpath = "//input[@name = '<PASSWORD>']")
WebElement password;
@FindBy(xpath = "//div[contains(text(), 'Login')]")
WebElement loginBtn;
@FindBy(xpath = "//a[contains(text(), 'Forgot ')]")
WebElement forgotPassword;
@FindBy(xpath = "//a[contains(text(), 'Classic CRM')]")
WebElement classicCRMLogin;
@FindBy(xpath = "//a[contains(text(), 'Sign Up')]")
WebElement singUpBtn;
// Initializing the Page Objects:
public LoginPage() {
PageFactory.initElements(driver, this);
}
public String verifyTitleOfLoginPage() {
return driver.getTitle();
}
public HomePage login(String em, String pwd) {
emailId.sendKeys(em);
password.sendKeys(pwd);
loginBtn.click();
return new HomePage();
}
}
| 9e629af7d1ca2d08679b73f6fdb5389f7ad3fa66 | [
"Java",
"INI"
] | 6 | Java | PankajPandey06/PageObjectModel | 6fc861fee6dfd5f5dae38761049d3d1404942230 | 0b403d36b599434b6147065c247bd1208fa362f3 |
refs/heads/master | <repo_name>CodeMeNawh/hangmanbitch<file_sep>/hang.py
import random
import time
import images
correctly_guessed_letters = []
incorrectly_guessed_letters = []
lives_left = 6
game_over = False
def intro():
print(" _ ")
print("| | ")
print("| |__ __ _ _ __ __ _ _ __ ___ __ _ _ __ ")
print("| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ ")
print("| | | | (_| | | | | (_| | | | | | | (_| | | | |")
print("|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|")
print(" __/ | ")
print(" |___/ ")
time.sleep(2)
def welcome():
name = input("""
==============================================
> Welcome to the HangYou Game ! Please enter your nickname: <""").capitalize()
time.sleep(2)
if name.isalpha() == True:
print("""
>>> Hi""", name, """glad to hang you here! <<<
The computer will randomly choose a word and you will try to guess it.
But you will fail!""")
time.sleep(1)
print("""================================================================""")
time.sleep(1)
print("""Hang in there!
""")
else:
print('Please enter your nickname using letters only')
name = input('Enter a game name here: ')
time.sleep(1)
print('Hi!', name, 'Follow the rules, they say!')
def choose_level():
level_mode = input(
"Enter level mode""\n""E for Easy""\n""H for Hard""\n").upper()
if level_mode == "E":
lives_left = 6
# print(images.HANGMAN[6 - lives_left])
else:
lives_left = 3
# print(images.HANGMAN[3 - lives_left])
return level_mode, lives_left
def get_word(level_mode):
taken_words = []
with open('countries-and-capitals.txt', 'r') as f:
for line in f:
word_taken = line.split(" | ")
if level_mode == "E":
taken_words.append(word_taken[0])
else:
taken_words.append(word_taken[1])
choosen_word = random.choice(taken_words)
print(choosen_word)
return choosen_word
def draw_word(choosen_word):
secret_word = ''
for i in range(0, len(choosen_word)):
letter = choosen_word[i]
if letter.lower() in correctly_guessed_letters:
secret_word += letter
elif letter == " ":
secret_word += " "
else:
secret_word += "_"
print("")
return secret_word.capitalize()
def get_one_valid_letter(choosen_word, lives_left):
# Will make sure the user types only 1 letter that has not been used before
is_letter_valid = False
while is_letter_valid is False:
letter = input("Enter guess letter: ")
letter = letter.strip().lower()
if len(letter) != 1:
print("Letter must be of length 1")
elif letter.isalpha():
if letter in correctly_guessed_letters or letter in incorrectly_guessed_letters:
print("You have already used the letter " +
letter + ", please try again")
else:
is_letter_valid = True
else:
print("Letter must be (a-z)")
return letter
def guess_letter(choosen_word, lives_left):
# Will check if the 1 letter guessed is correct or wrong and update global variables based on the result
letter = get_one_valid_letter(choosen_word, lives_left)
if letter in choosen_word.lower():
correctly_guessed_letters.append(letter)
else:
incorrectly_guessed_letters.append(letter)
lives_left -= 1
def check_game_over(choosen_word):
if lives_left <= 0:
game_over = True
return game_over
# draw_hangman()
# print("You lost! The word was " +
# choosen_word + ". Try again next time!")
if draw_word(choosen_word) == choosen_word:
print("You won bit ch!")
game_over = True
return game_over
def hangman_drawing(lives_left):
print(images.HANGMAN[6 - lives_left])
def main():
global game_over
intro()
welcome()
level_mode, lives = choose_level()
print(lives)
print(lives_left)
print(level_mode)
choosen_word = get_word(level_mode)
while game_over is False:
hangman_drawing(lives_left)
print(" ".join(draw_word(choosen_word)))
if len(incorrectly_guessed_letters) > 0:
print("Incorrect guesses: ")
print(incorrectly_guessed_letters)
print()
# printy by wiedziec
guess_letter(choosen_word, lives_left)
# printy gdzie jestem
check_game_over(choosen_word)
if __name__ == '__main__':
main()
| 4e1ce1876ad3fbc88ef6453b23b3f9b4d06bdeae | [
"Python"
] | 1 | Python | CodeMeNawh/hangmanbitch | e601b4da5ad1a9181d64196dde1db86fd8c20270 | 9dd83c6cc881dd275df368c9baf7a08016713138 |
refs/heads/master | <file_sep>source "https://rubygems.org"
gem 'aws-sdk', '>=2.6.42'
gem 'aws-sdk-core', '>=2.4.42'
gem 'aws-sdk-resources', '>=2.4.42'
gem 'aws-sdk-v1', '>=1.66.0'
gem 'zabbixapi', '>=3.1.0'
<file_sep>#! /usr/bin/env ruby
require 'aws-sdk-v1'
if ARGV.size < 6
puts "Usage: #{$PROGRAM_NAME} [REGION] [NAMESPACE] [METRIC_NAME] [DIMENTION_NAME] [DIMENTION_VALUE] [STATISTICS_TYPE](Average) [DIFFERENCE_TIME(sec)](600) [PERIOD(sec)](300)"
exit 1
end
region = ARGV[0]
namespace = ARGV[1]
metric_name = ARGV[2]
dime_name = ARGV[3]
dime_value = ARGV[4]
statistics_type = ARGV[5] || 'Average'
diff_time = ARGV[6] || '600'
period = ARGV[7] || '300'
AWS.config(
region: region
)
metrics = AWS::CloudWatch::Metric.new(
namespace,
metric_name,
dimensions: [
{ name: dime_name, value: dime_value }
]
)
stats = metrics.statistics(
start_time: Time.now - diff_time.to_i,
end_time: Time.now,
statistics: [statistics_type],
period: period.to_i
)
last_stats = stats.sort_by { |stat| stat[:timestamp] }.last
if last_stats.nil?
puts 0
else
puts last_stats[statistics_type.downcase.to_sym]
end
<file_sep>#!/bin/bash
#
# Caution! Call this script from Zabbix directly is very dangerous. Do not use in production!
AWSCMD="$1"
JQCMD="$2"
ZBXEL="$3"
FIRST=1
echo "{"
echo ' "data":['
while read line; do
if [ $FIRST != 0 ]; then
FIRST=0
else
ELEMENT="{ \"{#$ZBXEL}\":\"$ITEM\" },"
echo " $ELEMENT"
fi
ITEM=$line
done <<< "$(aws $AWSCMD | jq -r $JQCMD)"
ELEMENT="{ \"{#$ZBXEL}\":\"$ITEM\" }"
echo " $ELEMENT"
echo ' ]'
echo "}"
<file_sep>#!/bin/bash
cd /usr/lib/zabbix/externalscripts
#CloudWatchLogs
for i in `aws logs describe-log-groups | jq -r '.logGroups[].logGroupName'`; do MSG=`/usr/lib/zabbix/externalscripts/cw_log_filter.rb "$i" ERR 300`; zabbix_sender -z localhost -p 10051 -s "AWS-TEST" -k "LogGroup[$i]" -o "$MSG"; done
#SQS Message Count
for i in `aws sqs list-queues | jq -r ".QueueUrls[]"`;do ApproximateNumberOfMessages=`aws sqs get-queue-attributes --queue-url $i --attribute-names ApproximateNumberOfMessages | jq .Attributes.ApproximateNumberOfMessages`; zabbix_sender -z localhost -p 10051 -s "AWS-TEST" -k "MSG_COUNT[$i]" -o "$ApproximateNumberOfMessages"; done
<file_sep>AWS Integration for Zabbix: A little bit automation
=============
## Description
This fork designed for automate AWS monitoring via Zabbix
## Features
todo
## Installation
1. Create Read Only Audit and List Policy
2. Create Role with this Policy
3. Assign this role on EC2 instance where is Zabbix installed
## Original Authors
[tsubauaaa](https://github.com/tsubauaaa)
## About me
<NAME>
## License
[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
| 42a34ada39bc8bd9792a8ad6f6c77c51e11fe19a | [
"Markdown",
"Ruby",
"Shell"
] | 5 | Ruby | odessky/zabbix_aws_integration | 80ec011d0a9f4dbf28fb675751c25da170db56fa | 566ce9ac3164f07fb10789ad1d6dfc1d6af20be0 |
refs/heads/main | <repo_name>iamfoyez/YoutubePlayer<file_sep>/README.md
# YoutubePlayer
Small GUI youtube player
<file_sep>/run.py
import os
import sys
os.system("javac *.java")
os.system("java " + sys.argv[1])
os.system("rm *.class") | 86f2c6051a27ab8d2215e8ffce0e75df354e2efb | [
"Markdown",
"Python"
] | 2 | Markdown | iamfoyez/YoutubePlayer | dc8b1be768ad5c3da8bfdf50541a9f99fe0959c4 | 6702d69364559e75917e1971719bee28a7145f7c |
refs/heads/open365 | <repo_name>Open365/seahub<file_sep>/seahub/api2/endpoints/account.py
import logging
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
import seaserv
from seaserv import seafile_api, ccnet_threaded_rpc
from pysearpc import SearpcError
from seahub.api2.authentication import TokenAuthentication
from seahub.api2.serializers import AccountSerializer
from seahub.api2.utils import api_error, to_python_boolean
from seahub.api2.status import HTTP_520_OPERATION_FAILED
from seahub.base.accounts import User
from seahub.profile.models import Profile
from seahub.profile.utils import refresh_cache as refresh_profile_cache
from seahub.utils import is_valid_username
logger = logging.getLogger(__name__)
json_content_type = 'application/json; charset=utf-8'
class Account(APIView):
"""Query/Add/Delete a specific account.
Administator permission is required.
"""
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAdminUser, )
throttle_classes = (UserRateThrottle, )
def get(self, request, email, format=None):
if not is_valid_username(email):
return api_error(status.HTTP_404_NOT_FOUND, 'User not found.')
# query account info
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
return api_error(status.HTTP_404_NOT_FOUND, 'User not found.')
info = {}
info['email'] = user.email
info['id'] = user.id
info['is_staff'] = user.is_staff
info['is_active'] = user.is_active
info['create_time'] = user.ctime
info['total'] = seafile_api.get_user_quota(email)
info['usage'] = seafile_api.get_user_self_usage(email)
return Response(info)
def _update_account_profile(self, request, email):
name = request.DATA.get("name", None)
note = request.DATA.get("note", None)
if name is None and note is None:
return
profile = Profile.objects.get_profile_by_user(email)
if profile is None:
profile = Profile(user=email)
if name is not None:
# if '/' in name:
# return api_error(status.HTTP_400_BAD_REQUEST, "Nickname should not include '/'")
profile.nickname = name
if note is not None:
profile.intro = note
profile.save()
refresh_profile_cache(email)
def _update_account_quota(self, request, email):
storage = request.DATA.get("storage", None)
sharing = request.DATA.get("sharing", None)
if storage is None and sharing is None:
return
if storage is not None:
seafile_api.set_user_quota(email, int(storage))
# if sharing is not None:
# seafile_api.set_user_share_quota(email, int(sharing))
def _create_account(self, request, email):
copy = request.DATA.copy()
copy['email'] = email
serializer = AccountSerializer(data=copy)
if serializer.is_valid():
try:
user = User.objects.create_user(serializer.object['email'],
serializer.object['password'],
serializer.object['is_staff'],
serializer.object['is_active'])
except User.DoesNotExist as e:
logger.error(e)
return api_error(status.HTTP_403_FORBIDDEN,
'Fail to add user.')
self._update_account_profile(request, user.username)
resp = Response('success', status=status.HTTP_201_CREATED)
resp['Location'] = reverse('api2-account', args=[email])
return resp
else:
return api_error(status.HTTP_400_BAD_REQUEST, serializer.errors)
def _update_account(self, request, user):
password = request.DATA.get("password", None)
is_staff = request.DATA.get("is_staff", None)
if is_staff is not None:
try:
is_staff = to_python_boolean(is_staff)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST,
'%s is not a valid value' % is_staff)
is_active = request.DATA.get("is_active", None)
if is_active is not None:
try:
is_active = to_python_boolean(is_active)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST,
'%s is not a valid value' % is_active)
if password is not None:
user.set_password(password)
if is_staff is not None:
user.is_staff = is_staff
if is_active is not None:
user.is_active = is_active
result_code = user.save()
if result_code == -1:
return api_error(status.HTTP_403_FORBIDDEN,
'Fail to update user.')
self._update_account_profile(request, user.username)
try:
self._update_account_quota(request, user.username)
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED, 'Failed to set account quota')
is_trial = request.DATA.get("is_trial", None)
if is_trial is not None:
try:
from seahub_extra.trialaccount.models import TrialAccount
except ImportError:
pass
else:
try:
is_trial = to_python_boolean(is_trial)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST,
'%s is not a valid value' % is_trial)
if is_trial is True:
expire_date = timezone.now() + relativedelta(days=7)
TrialAccount.object.create_or_update(user.username,
expire_date)
else:
TrialAccount.objects.filter(user_or_org=user.username).delete()
return Response('success')
def post(self, request, email, format=None):
# migrate an account's repos and groups to an exist account
if not is_valid_username(email):
return api_error(status.HTTP_404_NOT_FOUND, 'User not found.')
op = request.DATA.get('op', '').lower()
if op == 'migrate':
from_user = email
to_user = request.DATA.get('to_user', '')
if not is_valid_username(to_user):
return api_error(status.HTTP_400_BAD_REQUEST, '%s is not valid email.' % to_user)
try:
user2 = User.objects.get(email=to_user)
except User.DoesNotExist:
return api_error(status.HTTP_400_BAD_REQUEST, '%s does not exist.' % to_user)
# transfer owned repos to new user
for r in seafile_api.get_owned_repo_list(from_user):
seafile_api.set_repo_owner(r.id, user2.username)
# transfer joined groups to new user
for g in seaserv.get_personal_groups_by_user(from_user):
if not seaserv.is_group_user(g.id, user2.username):
# add new user to the group on behalf of the group creator
ccnet_threaded_rpc.group_add_member(g.id, g.creator_name,
to_user)
if from_user == g.creator_name:
ccnet_threaded_rpc.set_group_creator(g.id, to_user)
return Response("success")
else:
return api_error(status.HTTP_400_BAD_REQUEST, 'Op can only be migrate')
def put(self, request, email, format=None):
if not is_valid_username(email):
return api_error(status.HTTP_404_NOT_FOUND, 'User not found.')
try:
user = User.objects.get(email=email)
return self._update_account(request, user)
except User.DoesNotExist:
return self._create_account(request, email)
def delete(self, request, email, format=None):
if not is_valid_username(email):
return api_error(status.HTTP_404_NOT_FOUND, 'User not found.')
# delete account
try:
user = User.objects.get(email=email)
user.delete()
return Response("success")
except User.DoesNotExist:
resp = Response("success", status=status.HTTP_202_ACCEPTED)
return resp
<file_sep>/seahub/forms.py
# encoding: utf-8
from django.conf import settings
from django import forms
from django.utils.translation import ugettext_lazy as _
from seaserv import seafserv_threaded_rpc, is_valid_filename
from pysearpc import SearpcError
from seahub.base.accounts import User
from seahub.constants import DEFAULT_USER, GUEST_USER
class AddUserForm(forms.Form):
"""
Form for adding a user.
"""
email = forms.EmailField()
role = forms.ChoiceField(choices=[(DEFAULT_USER, DEFAULT_USER),
(GUEST_USER, GUEST_USER)])
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
def clean_email(self):
email = self.cleaned_data['email']
try:
user = User.objects.get(email=email)
raise forms.ValidationError(_("A user with this email already exists."))
except User.DoesNotExist:
return self.cleaned_data['email']
def clean(self):
"""
Verifiy that the values entered into the two password fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.
"""
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two passwords didn't match."))
return self.cleaned_data
class RepoCreateForm(forms.Form):
"""
Form for creating repo and org repo.
"""
repo_name = forms.CharField(max_length=settings.MAX_FILE_NAME,
error_messages={
'required': _(u'Name can\'t be empty'),
'max_length': _(u'Name is too long (maximum is 255 characters)')
})
repo_desc = forms.CharField(max_length=100, error_messages={
'required': _(u'Description can\'t be empty'),
'max_length': _(u'Description is too long (maximum is 100 characters)')
})
encryption = forms.CharField(max_length=1)
uuid = forms.CharField(required=False)
magic_str = forms.CharField(required=False)
encrypted_file_key = forms.CharField(required=False)
def clean_repo_name(self):
repo_name = self.cleaned_data['repo_name']
if not is_valid_filename(repo_name):
error_msg = _(u"Name %s is not valid") % repo_name
raise forms.ValidationError(error_msg)
else:
return repo_name
def clean(self):
encryption = self.cleaned_data['encryption']
if int(encryption) == 0:
return self.cleaned_data
uuid = self.cleaned_data['uuid']
magic_str = self.cleaned_data['magic_str']
encrypted_file_key = self.cleaned_data['encrypted_file_key']
if not (uuid and magic_str and encrypted_file_key):
raise forms.ValidationError(_("Argument missing"))
return self.cleaned_data
class SharedRepoCreateForm(RepoCreateForm):
"""
Used for creating group repo and public repo
"""
permission = forms.ChoiceField(choices=(('rw', 'read-write'), ('r', 'read-only')))
class RepoRenameDirentForm(forms.Form):
"""
Form for rename a file/dir.
"""
oldname = forms.CharField(error_messages={'required': _("Oldname is required")})
newname = forms.CharField(max_length=settings.MAX_FILE_NAME,
error_messages={
'max_length': _("It's too long."),
'required': _("It's required."),
})
def clean_newname(self):
newname = self.cleaned_data['newname']
try:
if not is_valid_filename(newname):
error_msg = _(u'Name "%s" is not valid') % newname
raise forms.ValidationError(error_msg)
else:
return newname
except SearpcError, e:
raise forms.ValidationError(str(e))
class RepoNewDirentForm(forms.Form):
"""
Form for create a new empty dir or a new empty file.
"""
dirent_name = forms.CharField(max_length=settings.MAX_FILE_NAME,
error_messages={
'max_length': _("It's too long."),
'required': _("It's required."),
})
def clean_dirent_name(self):
dirent_name = self.cleaned_data['dirent_name']
try:
if not is_valid_filename(dirent_name):
error_msg = _(u'Name "%s" is not valid') % dirent_name
raise forms.ValidationError(error_msg)
else:
return dirent_name
except SearpcError, e:
raise forms.ValidationError(str(e))
class RepoPassowrdForm(forms.Form):
"""
Form for user to decrypt a repo in repo page.
"""
repo_id = forms.CharField(error_messages={'required': _('Repo id is required')})
username = forms.CharField(error_messages={'required': _('Username is required')})
password = forms.CharField(error_messages={'required': _('Password can\'t be empty')})
def clean(self):
if 'password' in self.cleaned_data:
repo_id = self.cleaned_data['repo_id']
username = self.cleaned_data['username']
password = <PASSWORD>['<PASSWORD>']
try:
seafserv_threaded_rpc.set_passwd(repo_id, username, password)
except SearpcError, e:
if e.msg == 'Bad arguments':
raise forms.ValidationError(_(u'Bad url format'))
elif e.msg == 'Incorrect password':
raise forms.ValidationError(_(u'Wrong password'))
elif e.msg == 'Internal server error':
raise forms.ValidationError(_(u'Internal server error'))
else:
raise forms.ValidationError(_(u'Decrypt library error'))
class SetUserQuotaForm(forms.Form):
"""
Form for setting user quota.
"""
email = forms.CharField(error_messages={'required': _('Email is required')})
space_quota = forms.IntegerField(min_value=0,
error_messages={'required': _('Space quota can\'t be empty'),
'min_value': _('Space quota is too low (minimum value is 0)')})
class RepoSettingForm(forms.Form):
"""
Form for saving repo settings.
"""
repo_name = forms.CharField(error_messages={'required': _('Library name is required')})
days = forms.IntegerField(required=False,
error_messages={'invalid': _('Please enter a number')})
def clean_repo_name(self):
repo_name = self.cleaned_data['repo_name']
if not is_valid_filename(repo_name):
error_msg = _(u"Name %s is not valid") % repo_name
raise forms.ValidationError(error_msg)
else:
return repo_name
class BatchAddUserForm(forms.Form):
"""
Form for importing users from CSV file.
"""
file = forms.FileField()
<file_sep>/tests/api/test_files.py
#coding: UTF-8
"""
Test file/dir operations.
"""
import posixpath
import pytest
import urllib
from urllib import urlencode, quote
import urlparse
from tests.common.utils import randstring, urljoin
from tests.api.apitestbase import ApiTestBase
class FilesApiTest(ApiTestBase):
def test_rename_file(self):
with self.get_tmp_repo() as repo:
name, furl = self.create_file(repo)
data = {
'operation': 'rename',
'newname': name + randstring(),
}
res = self.post(furl, data=data)
self.assertRegexpMatches(res.text, r'"http(.*)"')
def test_remove_file(self):
with self.get_tmp_repo() as repo:
_, furl = self.create_file(repo)
res = self.delete(furl)
self.assertEqual(res.text, '"success"')
def test_move_file(self):
with self.get_tmp_repo() as repo:
_, furl = self.create_file(repo)
# TODO: create another repo here, and use it as dst_repo
data = {
'operation': 'move',
'dst_repo': repo.repo_id,
'dst_dir': '/',
}
res = self.post(furl, data=data)
self.assertEqual(res.text, '"success"')
def test_copy_file(self):
with self.get_tmp_repo() as repo:
# TODO: create another repo here, and use it as dst_repo
# create sub folder(dpath)
dpath, _ = self.create_dir(repo)
# create tmp file in sub folder(dpath)
tmp_file = 'tmp_file.txt'
file_path = dpath + '/' + tmp_file
furl = repo.get_filepath_url(file_path)
data = {'operation': 'create'}
res = self.post(furl, data=data, expected=201)
# copy tmp file from sub folder(dpath) to dst dir('/')
data = {
'dst_repo': repo.repo_id,
'dst_dir': '/',
'operation': 'copy',
}
u = urlparse.urlparse(furl)
parsed_furl = urlparse.urlunparse((u.scheme, u.netloc, u.path, '', '', ''))
res = self.post(parsed_furl+ '?p=' + quote(file_path), data=data)
self.assertEqual(res.text, '"success"')
# get info of copied file in dst dir('/')
fdurl = repo.file_url + u'detail/?p=/%s' % quote(tmp_file)
detail = self.get(fdurl).json()
self.assertIsNotNone(detail)
self.assertIsNotNone(detail['id'])
def test_download_file(self):
with self.get_tmp_repo() as repo:
fname, furl = self.create_file(repo)
res = self.get(furl)
self.assertRegexpMatches(res.text, '"http(.*)/%s"' % quote(fname))
def test_download_file_without_reuse_token(self):
with self.get_tmp_repo() as repo:
fname, furl = self.create_file(repo)
res = self.get(furl)
self.assertRegexpMatches(res.text, '"http(.*)/%s"' % quote(fname))
# download for the first time
url = urllib.urlopen(res.text.strip('"'))
code = url.getcode()
self.assertEqual(code, 200)
# download for the second time
url = urllib.urlopen(res.text.strip('"'))
code = url.getcode()
self.assertEqual(code, 400)
def test_download_file_with_reuse_token(self):
with self.get_tmp_repo() as repo:
fname, furl = self.create_file(repo)
res = self.get(furl + '&reuse=1')
self.assertRegexpMatches(res.text, '"http(.*)/%s"' % quote(fname))
# download for the first time
url = urllib.urlopen(res.text.strip('"'))
code = url.getcode()
self.assertEqual(code, 200)
# download for the second time
url = urllib.urlopen(res.text.strip('"'))
code = url.getcode()
self.assertEqual(code, 200)
def test_download_file_from_history(self):
with self.get_tmp_repo() as repo:
fname, _ = self.create_file(repo)
file_history_url = urljoin(repo.repo_url, 'history/') + \
'?p=/%s' % quote(fname)
res = self.get(file_history_url).json()
commit_id = res['commits'][0]['id']
self.assertEqual(len(commit_id), 40)
data = {
'p': fname,
'commit_id': commit_id,
}
query = '?' + urlencode(data)
res = self.get(repo.file_url + query)
self.assertRegexpMatches(res.text, r'"http(.*)/%s"' % quote(fname))
def test_get_file_detail(self):
with self.get_tmp_repo() as repo:
fname, _ = self.create_file(repo)
fdurl = repo.file_url + u'detail/?p=/%s' % quote(fname)
detail = self.get(fdurl).json()
self.assertIsNotNone(detail)
self.assertIsNotNone(detail['id'])
self.assertIsNotNone(detail['mtime'])
self.assertIsNotNone(detail['type'])
self.assertIsNotNone(detail['name'])
self.assertIsNotNone(detail['size'])
def test_get_file_history(self):
with self.get_tmp_repo() as repo:
fname, _ = self.create_file(repo)
fhurl = repo.file_url + u'history/?p=%s' % quote(fname)
history = self.get(fhurl).json()
for commit in history['commits']:
self.assertIsNotNone(commit['rev_file_size'])
#self.assertIsNotNone(commit['rev_file_id']) #allow null
self.assertIsNotNone(commit['ctime'])
self.assertIsNotNone(commit['creator_name'])
self.assertIsNotNone(commit['creator'])
self.assertIsNotNone(commit['root_id'])
#self.assertIsNotNone(commit['rev_renamed_old_path']) #allow null
#self.assertIsNotNone(commit['parent_id']) #allow null
self.assertIsNotNone(commit['new_merge'])
self.assertIsNotNone(commit['repo_id'])
self.assertIsNotNone(commit['desc'])
self.assertIsNotNone(commit['id'])
self.assertIsNotNone(commit['conflict'])
#self.assertIsNotNone(commit['second_parent_id']) #allow null
def test_get_upload_link(self):
with self.get_tmp_repo() as repo:
upload_url = urljoin(repo.repo_url, 'upload-link')
res = self.get(upload_url)
self.assertRegexpMatches(res.text, r'"http(.*)/upload-api/[^/]+"')
def test_get_update_link(self):
with self.get_tmp_repo() as repo:
update_url = urljoin(repo.repo_url, 'update-link')
res = self.get(update_url)
self.assertRegexpMatches(res.text, r'"http(.*)/update-api/[^/]+"')
# def test_upload_file(self):
# # XXX: requests has problems when post a file whose name contains
# # non-ascii data
# fname = 'file-upload-test %s.txt' % randstring()
# furl = self.test_file_url + '?p=/%s' % quote(fname)
# self.delete(furl)
# upload_url = self.test_repo_url + u'upload-link/'
# res = self.get(upload_url)
# upload_api_url = re.match(r'"(.*)"', res.text).group(1)
# files = {
# 'file': (fname, 'Some lines in this file'),
# 'parent_dir': '/',
# }
# res = self.post(upload_api_url, files=files)
# self.assertRegexpMatches(res.text, r'\w{40,40}')
# def test_update_file(self):
# fname = 'file-update-test %s.txt' % randstring()
# _, furl = self.create_file(fname=fname)
# update_url = self.test_repo_url + u'update-link/'
# res = self.get(update_url)
# update_api_url = re.match(r'"(.*)"', res.text).group(1)
# files = {
# 'file': ('filename', 'Updated content of this file'),
# 'target_file': '/test_update.c'
# }
# res = self.post(update_api_url, files=files)
# self.assertRegexpMatches(res.text, r'\w{40,40}')
def test_get_upload_blocks_link(self):
with self.get_tmp_repo() as repo:
upload_blks_url = urljoin(repo.repo_url, 'upload-blks-link')
res = self.get(upload_blks_url)
self.assertRegexpMatches(res.text, r'"http(.*)/upload-blks-api/[^/]+"')
def test_get_update_blocks_link(self):
with self.get_tmp_repo() as repo:
update_blks_url = urljoin(repo.repo_url, 'update-blks-link')
res = self.get(update_blks_url)
self.assertRegexpMatches(res.text, r'"http(.*)/update-blks-api/[^/]+"')
def test_only_list_dir(self):
with self.get_tmp_repo() as repo:
self.create_file(repo)
self.create_dir(repo)
dirents = self.get(repo.dir_url + '?t=d').json()
self.assertHasLen(dirents, 1)
for dirent in dirents:
self.assertIsNotNone(dirent['id'])
self.assertIsNotNone(dirent['name'])
self.assertEqual(dirent['type'], 'dir')
def test_only_list_file(self):
with self.get_tmp_repo() as repo:
self.create_file(repo)
self.create_dir(repo)
dirents = self.get(repo.dir_url + '?t=f').json()
self.assertHasLen(dirents, 1)
for dirent in dirents:
self.assertIsNotNone(dirent['id'])
self.assertIsNotNone(dirent['name'])
self.assertIsNotNone(dirent['size'])
self.assertEqual(dirent['type'], 'file')
def test_list_dir_and_file(self):
with self.get_tmp_repo() as repo:
self.create_file(repo)
self.create_dir(repo)
dirents = self.get(repo.dir_url).json()
self.assertHasLen(dirents, 2)
for dirent in dirents:
self.assertIsNotNone(dirent['id'])
self.assertIsNotNone(dirent['name'])
self.assertIn(dirent['type'], ('file', 'dir'))
if dirent['type'] == 'file':
self.assertIsNotNone(dirent['size'])
def test_list_recursive_dir(self):
with self.get_tmp_repo() as repo:
# create test dir
data = {'operation': 'mkdir'}
dir_list = ['/1/', '/1/2/', '/1/2/3/', '/4/', '/4/5/', '/6/']
for dpath in dir_list:
durl = repo.get_dirpath_url(dpath)
self.post(durl, data=data, expected=201)
# get recursive dir
dirents = self.get(repo.dir_url + '?t=d&recursive=1').json()
self.assertHasLen(dirents, len(dir_list))
for dirent in dirents:
self.assertIsNotNone(dirent['id'])
self.assertEqual(dirent['type'], 'dir')
full_path = posixpath.join(dirent['parent_dir'], dirent['name']) + '/'
self.assertIn(full_path, dir_list)
def test_remove_dir(self):
with self.get_tmp_repo() as repo:
_, durl = self.create_dir(repo)
res = self.delete(durl)
self.assertEqual(res.text, u'"success"')
self.get(durl, expected=404)
def test_download_dir(self):
with self.get_tmp_repo() as repo:
dpath, _ = self.create_dir(repo)
query = '?p=%s' % quote(dpath)
ddurl = urljoin(repo.dir_url, 'download') + query
res = self.get(ddurl)
self.assertRegexpMatches(res.text,
r'"http(.*)/files/[^/]+/%s"' % quote(dpath[1:]))
def test_share_dir(self):
with self.get_tmp_repo() as repo:
dpath, _ = self.create_dir(repo)
query = '?p=%s' % quote(dpath)
share_dir_url = urljoin(repo.dir_url, 'share/') + query
with self.get_tmp_user() as user:
data = {
'emails': user.user_name,
's_type': 'd',
'path': '/',
'perm': 'r'
}
res = self.post(share_dir_url, data=data)
self.assertEqual(res.text, u'{}')
@pytest.mark.xfail
def test_create_dir_with_parents(self):
with self.get_tmp_repo() as repo:
path = u'/level1/level 2/level_3/目录4'
self.create_dir_with_parents(repo, path)
def create_dir_with_parents(self, repo, path):
data = {'operation': 'mkdir', 'create_parents': 'true'}
durl = repo.get_dirpath_url(path.encode('utf-8'))
self.post(durl, data=data, expected=201)
curpath = ''
# check the parents are created along the way
parts = path.split('/')
for i, name in enumerate(parts):
curpath += '/' + name
url = repo.get_dirpath_url(curpath.encode('utf-8'))
if i < len(parts) - 1:
assert self.get(url).json()[0]['name'] == parts[i+1]
else:
assert self.get(url).json() == []
<file_sep>/seahub/test_settings.py
from .settings import *
# no cache for testing
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
# enlarge api throttle
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES': {
'ping': '600/minute',
'anon': '5000/minute',
'user': '300/minute',
},
}
<file_sep>/seahub/test_utils.py
import os
from uuid import uuid4
from django.core.urlresolvers import reverse
from django.test import TestCase
from exam.decorators import fixture
from exam.cases import Exam
import seaserv
from seaserv import seafile_api, ccnet_threaded_rpc
from seahub.base.accounts import User
class Fixtures(Exam):
user_password = '<PASSWORD>'
admin_password = '<PASSWORD>'
@fixture
def user(self):
return self.create_user('<EMAIL>')
@fixture
def admin(self):
return self.create_user('<EMAIL>', is_staff=True)
@fixture
def repo(self):
r = seafile_api.get_repo(self.create_repo(name='test-repo', desc='',
username=self.user.username,
passwd=None))
return r
@fixture
def file(self):
return self.create_file(repo_id=self.repo.id,
parent_dir='/',
filename='test.txt',
username='<EMAIL>')
@fixture
def folder(self):
return self.create_folder(repo_id=self.repo.id,
parent_dir='/',
dirname='folder',
username='<EMAIL>')
@fixture
def group(self):
return self.create_group(group_name='test_group',
username=self.user.username)
def create_user(self, email=None, **kwargs):
if not email:
email = uuid4().hex + '@test.com'
kwargs.setdefault('email', email)
kwargs.setdefault('is_staff', False)
kwargs.setdefault('is_active', True)
return User.objects.create_user(password='<PASSWORD>', **kwargs)
def remove_user(self, email=None):
if not email:
email = self.user.username
try:
User.objects.get(email).delete()
except User.DoesNotExist:
pass
for g in seaserv.get_personal_groups_by_user(email):
ccnet_threaded_rpc.remove_group(g.id, email)
def create_repo(self, **kwargs):
repo_id = seafile_api.create_repo(**kwargs)
return repo_id
def remove_repo(self, repo_id=None):
if not repo_id:
repo_id = self.repo.id
return seafile_api.remove_repo(repo_id)
def create_file(self, **kwargs):
seafile_api.post_empty_file(**kwargs)
return kwargs['parent_dir'] + kwargs['filename']
def create_folder(self, **kwargs):
seafile_api.post_dir(**kwargs)
return kwargs['parent_dir'] + kwargs['dirname']
def remove_folder(self):
seafile_api.del_file(self.repo.id, os.path.dirname(self.folder),
os.path.basename(self.folder), self.user.username)
def create_group(self, **kwargs):
group_name = kwargs['group_name']
username = kwargs['username']
group_id = ccnet_threaded_rpc.create_group(group_name, username)
return ccnet_threaded_rpc.get_group(group_id)
def remove_group(self, group_id=None):
if not group_id:
group_id = self.group.id
return ccnet_threaded_rpc.remove_group(group_id, self.user.username)
class BaseTestCase(TestCase, Fixtures):
def login_as(self, user):
self.client.post(
reverse('auth_login'), {'login': user.username,
'password': '<PASSWORD>'}
)
<file_sep>/static/scripts/app/views/shared-repo.js
define([
'jquery',
'underscore',
'backbone',
'common'
], function($, _, Backbone, Common) {
'use strict';
var SharedRepoView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#shared-repo-tmpl').html()),
events: {
'mouseenter': 'showAction',
'mouseleave': 'hideAction',
'click .unshare-btn': 'removeShare'
},
initialize: function() {
},
removeShare: function(e) {
var _this = this,
success_callback = function(data) {
Common.feedback(gettext('Success'), 'success', Common.SUCCESS_TIMOUT);
_this.$el.remove();
_this.collection.remove(_this.model, {silent: true});
if (_this.collection.length == 0) {
$('#repos-shared-to-me table').hide();
$('#repos-shared-to-me .empty-tips').show();
};
};
$.ajax({
url: Common.getUrl({name: 'ajax_repo_remove_share'}),
type: 'POST',
beforeSend: Common.prepareCSRFToken,
data: {
'repo_id': this.model.get('id'),
'from': this.model.get('owner'),
'share_type': this.model.get('share_type')
},
dataType: 'json',
success: success_callback
});
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
showAction: function() {
this.$el.addClass('hl');
this.$el.find('.op-icon').removeClass('vh');
},
hideAction: function() {
this.$el.removeClass('hl');
this.$el.find('.op-icon').addClass('vh');
}
});
return SharedRepoView;
});
<file_sep>/static/scripts/app/views/share.js
define([
'jquery',
'underscore',
'backbone',
'common',
'jquery.ui.tabs',
'select2',
'app/views/folder-share-item'
], function($, _, Backbone, Common, Tabs, Select2, FolderShareItemView) {
'use strict';
var SharePopupView = Backbone.View.extend({
tagName: 'div',
id: 'share-popup',
template: _.template($('#share-popup-tmpl').html()),
initialize: function(options) {
this.is_repo_owner = options.is_repo_owner;
this.is_virtual = options.is_virtual;
this.user_perm = options.user_perm;
this.repo_id = options.repo_id;
this.repo_encrypted = options.repo_encrypted;
this.dirent_path = options.dirent_path;
this.obj_name = options.obj_name;
this.is_dir = options.is_dir;
this.render();
this.$el.modal({
appendTo: "#main",
focus: false,
containerCss: {"padding": 0}
});
$('#simplemodal-container').css({'width':'auto', 'height':'auto'});
this.$("#share-tabs").tabs();
if (!this.repo_encrypted) {
this.downloadLinkPanelInit();
}
if (this.is_dir) {
if (this.user_perm == 'rw' && !this.repo_encrypted) {
this.uploadLinkPanelInit();
}
if (!this.is_virtual && this.is_repo_owner) {
this.dirUserSharePanelInit();
this.dirGroupSharePanelInit();
var _this = this;
$(document).on('click', function(e) {
var target = e.target || event.srcElement;
if (!_this.$('.perm-edit-icon, .perm-toggle-select').is(target)) {
_this.$('.perm').removeClass('hide');
_this.$('.perm-toggle-select').addClass('hide');
}
});
}
}
},
render: function () {
this.$el.html(this.template({
title: gettext("Share {placeholder}")
.replace('{placeholder}', '<span class="op-target ellipsis ellipsis-op-target" title="' + Common.HTMLescape(this.obj_name) + '">' + Common.HTMLescape(this.obj_name) + '</span>'),
is_dir: this.is_dir,
is_repo_owner: this.is_repo_owner,
is_virtual: this.is_virtual,
user_perm: this.user_perm,
repo_id: this.repo_id,
repo_encrypted: this.repo_encrypted
}));
return this;
},
events: {
'mouseenter .checkbox-label': 'highlightCheckbox',
'mouseleave .checkbox-label': 'rmHighlightCheckbox',
'click .checkbox-orig': 'clickCheckbox',
// download link
'submit #generate-download-link-form': 'generateDownloadLink',
'click #send-download-link': 'showDownloadLinkSendForm',
'submit #send-download-link-form': 'sendDownloadLink',
'click #cancel-share-download-link': 'cancelShareDownloadLink',
'click #delete-download-link': 'deleteDownloadLink',
'click #generate-download-link-form .generate-random-password': 'generate<PASSWORD>DownloadPassword',
'click #generate-download-link-form .show-or-hide-password': 'showOrHideDownloadPassword',
// upload link
'submit #generate-upload-link-form': 'generateUploadLink',
'click #send-upload-link': 'showUploadLinkSendForm',
'submit #send-upload-link-form': 'sendUploadLink',
'click #cancel-share-upload-link': 'cancelShareUploadLink',
'click #delete-upload-link': 'deleteUploadLink',
'click #generate-upload-link-form .generate-random-password': 'generateRandomUploadPassword',
'click #generate-upload-link-form .show-or-hide-password': 'showOrHideUploadPassword',
// dir private share
'click #add-dir-user-share-item .submit': 'dirUserShare',
'click #add-dir-group-share-item .submit': 'dirGroupShare'
},
highlightCheckbox: function (e) {
$(e.currentTarget).addClass('hl');
},
rmHighlightCheckbox: function (e) {
$(e.currentTarget).removeClass('hl');
},
clickCheckbox: function(e) {
var el = e.currentTarget;
$(el).parent().toggleClass('checkbox-checked');
// for link options such as 'password', 'expire'
$(el).closest('.checkbox-label').next().toggleClass('hide');
},
downloadLinkPanelInit: function() {
var _this = this;
var after_op_success = function(data) {
_this.$('.loading-tip').hide();
if (data['download_link']) {
_this.download_link = data["download_link"]; // for 'link send'
_this.download_link_token = data["token"]; // for 'link delete'
_this.$('#download-link').html(data['download_link']);
_this.$('#direct-dl-link').html(data['download_link']+'?raw=1');
if (data['is_expired']) {
_this.$('#send-download-link').addClass('hide');
_this.$('#download-link, #direct-dl-link').append(' <span class="error">(' + gettext('Expired') + ')</span>');
}
_this.$('#download-link-operations').removeClass('hide');
} else {
_this.$('#generate-download-link-form').removeClass('hide');
}
};
// check if downloadLink exists
Common.ajaxGet({
'get_url': Common.getUrl({name: 'get_shared_download_link'}),
'data': {
'repo_id': this.repo_id,
'p': this.dirent_path,
'type': this.is_dir ? 'd' : 'f'
},
'after_op_success': after_op_success
});
},
generateRandomPassword: function(form) {
var random_password_length = app.pageOptions.share_link_password_min_length;
var random_password = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < random_password_length; i++) {
random_password += possible.charAt(Math.floor(Math.random() * possible.length));
}
$('input[name=password], input[name=password_again]', form).attr('type', 'text').val(random_password);
$('.show-or-hide-password', form)
.attr('title', gettext('Hide'))
.removeClass('icon-eye').addClass('icon-eye-slash');
},
generateRandomDownloadPassword: function() {
this.generateRandomPassword($('#generate-download-link-form'));
},
showOrHidePassword: function(form) {
var icon = $('.show-or-hide-password', form),
passwd_input = $('input[name=password], input[name=password_again]', form);
icon.toggleClass('icon-eye icon-eye-slash');
if (icon.hasClass('icon-eye')) {
icon.attr('title', gettext('Show'));
passwd_input.attr('type', 'password');
} else {
icon.attr('title', gettext('Hide'));
passwd_input.attr('type', 'text');
}
},
showOrHideDownloadPassword: function() {
this.showOrHidePassword($('#generate-download-link-form'));
},
generateLink: function(options) {
var link_type = options.link_type, // 'download' or 'upload'
form = options.form,
form_id = form.attr('id'),
use_passwd_checkbox = $('[name="use_passwd"]', form),
use_passwd = use_passwd_checkbox.prop('checked');
if (link_type == 'download') {
var set_expiration_checkbox = $('[name="set_expiration"]', form),
set_expiration = set_expiration_checkbox.prop('checked');
}
var post_data = {};
if (use_passwd) {
var passwd_input = $('[name="password"]', form),
passwd_again_input = $('[name="password_again"]', form),
passwd = $.trim(passwd_input.val()),
passwd_again = $.trim(passwd_again_input.val());
if (!passwd) {
Common.showFormError(form_id, gettext("Please enter password"));
return false;
}
if (passwd.length < app.pageOptions.share_link_password_min_length) {
Common.showFormError(form_id, gettext("Password is too short"));
return false;
}
if (!passwd_again) {
Common.showFormError(form_id, gettext("Please enter the password again"));
return false;
}
if (passwd != passwd_again) {
Common.showFormError(form_id, gettext("Passwords don't match"));
return false;
}
post_data["use_passwd"] = 1;
post_data["passwd"] = <PASSWORD>;
} else {
post_data["use_passwd"] = 0;
}
if (set_expiration) { // for upload link, 'set_expiration' is undefined
var expire_days_input = $('[name="expire_days"]', form),
expire_days = $.trim(expire_days_input.val());
if (!expire_days) {
Common.showFormError(form_id, gettext("Please enter days."));
return false;
}
if (Math.floor(expire_days) != expire_days || !$.isNumeric(expire_days)) {
Common.showFormError(form_id, gettext("Please enter valid days"));
return false;
};
post_data["expire_days"] = expire_days;
}
$('.error', form).addClass('hide').html('');
var gen_btn = $('[type="submit"]', form);
Common.disableButton(gen_btn);
$.extend(post_data, {
'repo_id': this.repo_id,
'p': this.dirent_path
});
if (link_type == 'download') {
$.extend(post_data, {
'type': this.is_dir? 'd' : 'f'
});
}
var _this = this;
var after_op_success = function(data) {
form.addClass('hide');
// restore form state
Common.enableButton(gen_btn);
if (use_passwd) {
use_passwd_checkbox.prop('checked', false)
.parent().removeClass('checkbox-checked')
// hide password input
.end().closest('.checkbox-label').next().addClass('hide');
passwd_input.val('');
passwd_again_input.val('');
}
if (set_expiration) {
set_expiration_checkbox.prop('checked', false)
.parent().removeClass('checkbox-checked')
// hide 'day' input
.end().closest('.checkbox-label').next().addClass('hide');
expire_days_input.val('');
}
if (link_type == 'download') {
_this.$('#download-link').html(data["download_link"]); // TODO: add 'click & select' func
_this.$('#direct-dl-link').html(data['download_link'] + '?raw=1');
_this.download_link = data["download_link"]; // for 'link send'
_this.download_link_token = data["token"]; // for 'link delete'
_this.$('#download-link-operations').removeClass('hide');
} else {
_this.$('#upload-link').html(data["upload_link"]);
_this.upload_link = data["upload_link"];
_this.upload_link_token = data["token"];
_this.$('#upload-link-operations').removeClass('hide');
}
};
Common.ajaxPost({
'form': form,
'post_url': options.post_url,
'post_data': post_data,
'after_op_success': after_op_success,
'form_id': form_id
});
},
generateDownloadLink: function() {
this.generateLink({
link_type: 'download',
form: this.$('#generate-download-link-form'),
post_url: Common.getUrl({name: 'get_shared_download_link'})
});
return false;
},
showDownloadLinkSendForm: function() {
this.$('#send-download-link, #delete-download-link').addClass('hide');
this.$('#send-download-link-form').removeClass('hide');
// no addAutocomplete for email input
},
sendLink: function(options) {
// options: {form:$obj, other_post_data:{}, post_url:''}
var form = options.form,
form_id = form.attr('id'),
email = $.trim($('[name="email"]', form).val()),
extra_msg = $('textarea[name="extra_msg"]', form).val();
if (!email) {
Common.showFormError(form_id, gettext("Please input at least an email."));
return false;
};
var submit_btn = $('[type="submit"]', form);
var sending_tip = $('.sending-tip', form);
Common.disableButton(submit_btn);
sending_tip.removeClass('hide');
var post_data = {
email: email,
extra_msg: extra_msg
};
$.extend(post_data, options.other_post_data);
var after_op_success = function(data) {
$.modal.close();
var msg = gettext("Successfully sent to {placeholder}")
.replace('{placeholder}', Common.HTMLescape(data['send_success'].join(', ')));
Common.feedback(msg, 'success');
if (data['send_failed'].length > 0) {
msg += '<br />' + gettext("Failed to send to {placeholder}")
.replace('{placeholder}', Common.HTMLescape(data['send_failed'].join(', ')));
Common.feedback(msg, 'info');
}
};
var after_op_error = function(xhr) {
sending_tip.addClass('hide');
Common.enableButton(submit_btn);
var err;
if (xhr.responseText) {
err = $.parseJSON(xhr.responseText).error;
} else {
err = gettext("Failed. Please check the network.");
}
Common.showFormError(form_id, err);
Common.enableButton(submit_btn);
};
Common.ajaxPost({
'form': form,
'post_url': options.post_url,
'post_data': post_data,
'after_op_success': after_op_success,
'after_op_error': after_op_error,
'form_id': form_id
});
},
sendDownloadLink: function() {
this.sendLink({
form: this.$('#send-download-link-form'),
other_post_data: {
file_shared_link: this.download_link,
file_shared_name: this.obj_name,
file_shared_type: this.is_dir ? 'd' : 'f'
},
post_url: Common.getUrl({name: 'send_shared_download_link'})
});
return false;
},
cancelShareDownloadLink: function() {
this.$('#send-download-link, #delete-download-link').removeClass('hide');
this.$('#send-download-link-form').addClass('hide');
},
deleteDownloadLink: function() {
var _this = this;
$.ajax({
url: Common.getUrl({name: 'delete_shared_download_link'}),
type: 'POST',
data: { 't': this.download_link_token },
beforeSend: Common.prepareCSRFToken,
dataType: 'json',
success: function(data) {
_this.$('#generate-download-link-form').removeClass('hide');
_this.$('#download-link-operations').addClass('hide');
}
});
},
uploadLinkPanelInit: function() {
var _this = this;
var after_op_success = function(data) {
if (data['upload_link']) {
_this.upload_link_token = data["token"];
_this.upload_link = data["upload_link"];
_this.$('#upload-link').html(data["upload_link"]); // TODO
_this.$('#upload-link-operations').removeClass('hide');
} else {
_this.$('#generate-upload-link-form').removeClass('hide');
}
};
// check if upload link exists
Common.ajaxGet({
'get_url': Common.getUrl({name: 'get_share_upload_link'}), // TODO
'data': {'repo_id': this.repo_id, 'p': this.dirent_path},
'after_op_success': after_op_success
});
},
generateRandomUploadPassword: function() {
this.generateRandomPassword($('#generate-upload-link-form'));
},
showOrHideUploadPassword: function() {
this.showOrHidePassword($('#generate-upload-link-form'));
},
generateUploadLink: function(e) {
this.generateLink({
link_type: 'upload',
form: this.$('#generate-upload-link-form'),
post_url: Common.getUrl({name: 'get_share_upload_link'})
});
return false;
},
showUploadLinkSendForm: function() {
this.$('#send-upload-link, #delete-upload-link').addClass('hide');
this.$('#send-upload-link-form').removeClass('hide');
// no addAutocomplete for email input
},
sendUploadLink: function() {
this.sendLink({
form: this.$('#send-upload-link-form'),
other_post_data: {
shared_upload_link: this.upload_link
},
post_url: Common.getUrl({name: 'send_shared_upload_link'})
});
return false;
},
cancelShareUploadLink: function() {
this.$('#send-upload-link, #delete-upload-link').removeClass('hide');
this.$('#send-upload-link-form').addClass('hide');
},
deleteUploadLink: function() {
var _this = this;
$.ajax({
url: Common.getUrl({name: 'delete_shared_upload_link'}),
type: 'POST',
data: { 't': this.upload_link_token },
beforeSend: Common.prepareCSRFToken,
dataType: 'json',
success: function(data) {
_this.$('#generate-upload-link-form').removeClass('hide');
_this.$('#upload-link-operations').addClass('hide');
}
});
},
dirUserSharePanelInit: function() {
var form = this.$('#dir-user-share');
$('[name="emails"]', form).select2($.extend({
width: '297px'
},Common.contactInputOptionsForSelect2()));
// show existing items
var $add_item = $('#add-dir-user-share-item');
var repo_id = this.repo_id,
path = this.dirent_path;
Common.ajaxGet({
'get_url': Common.getUrl({
name: 'dir_shared_items',
repo_id: repo_id
}),
'data': {
'p': path,
'share_type': 'user'
},
'after_op_success': function (data) {
$(data).each(function(index, item) {
var new_item = new FolderShareItemView({
'repo_id': repo_id,
'path': path,
'item_data': {
"user": item.user_info.name,
"user_name": item.user_info.nickname,
"perm": item.permission,
'for_user': true
}
});
$add_item.after(new_item.el);
});
}
});
form.removeClass('hide');
this.$('.loading-tip').hide();
},
dirGroupSharePanelInit: function() {
var form = this.$('#dir-group-share');
var groups = app.pageOptions.groups || [];
var g_opts = '';
for (var i = 0, len = groups.length; i < len; i++) {
g_opts += '<option value="' + groups[i].id + '" data-index="' + i + '">' + groups[i].name + '</option>';
}
$('[name="groups"]', form).html(g_opts).select2({
placeholder: gettext("Select groups"),
width: '297px',
escapeMarkup: function(m) { return m; }
});
// show existing items
var $add_item = $('#add-dir-group-share-item');
var repo_id = this.repo_id,
path = this.dirent_path;
Common.ajaxGet({
'get_url': Common.getUrl({
name: 'dir_shared_items',
repo_id: repo_id
}),
'data': {
'p': path,
'share_type': 'group'
},
'after_op_success': function (data) {
$(data).each(function(index, item) {
var new_item = new FolderShareItemView({
'repo_id': repo_id,
'path': path,
'item_data': {
"group_id": item.group_info.id,
"group_name": item.group_info.name,
"perm": item.permission,
'for_user': false
}
});
$add_item.after(new_item.el);
});
}
});
form.removeClass('hide');
this.$('.loading-tip').hide();
},
dirUserShare: function () {
var panel = $('#dir-user-share');
var form = this.$('#add-dir-user-share-item');
var emails_input = $('[name="emails"]', form),
emails = emails_input.val(); // string
if (!emails) {
return false;
}
var $add_item = $('#add-dir-user-share-item');
var repo_id = this.repo_id,
path = this.dirent_path;
var perm = $('[name="permission"]', form).val();
$.ajax({
url: Common.getUrl({
name: 'dir_shared_items',
repo_id: repo_id
}) + '?p=' + encodeURIComponent(path),
dataType: 'json',
method: 'PUT',
beforeSend: Common.prepareCSRFToken,
traditional: true,
data: {
'share_type': 'user',
'username': emails.split(','),
'permission': perm
},
success: function(data) {
$(data.success).each(function(index, item) {
var new_item = new FolderShareItemView({
'repo_id': repo_id,
'path': path,
'item_data': {
"user": item.user_info.name,
"user_name": item.user_info.nickname,
"perm": item.permission,
'for_user': true
}
});
$add_item.after(new_item.el);
});
emails_input.select2("val", "");
if (data.failed.length > 0) {
var err_msg = '';
$(data.failed).each(function(index, item) {
err_msg += Common.HTMLescape(item.email) + ': ' + item.error_msg + '<br />';
});
$('.error', panel).html(err_msg).removeClass('hide');
}
},
error: function(xhr) {
var err_msg;
if (xhr.responseText) {
var parsed_resp = $.parseJSON(xhr.responseText);
err_msg = parsed_resp.error||parsed_resp.error_msg;
} else {
err_msg = gettext("Failed. Please check the network.")
}
$('.error', panel).html(err_msg).removeClass('hide');
}
});
},
dirGroupShare: function () {
var panel = $('#dir-group-share');
var form = this.$('#add-dir-group-share-item');
var groups_input = $('[name="groups"]', form),
groups = groups_input.val(); // null or [group.id]
if (!groups) {
return false;
}
var $add_item = $('#add-dir-group-share-item');
var repo_id = this.repo_id,
path = this.dirent_path;
var perm = $('[name="permission"]', form).val();
$.ajax({
url: Common.getUrl({
name: 'dir_shared_items',
repo_id: repo_id
}) + '?p=' + encodeURIComponent(path),
dataType: 'json',
method: 'PUT',
beforeSend: Common.prepareCSRFToken,
traditional: true,
data: {
'share_type': 'group',
'group_id': groups,
'permission': perm
},
success: function(data) {
$(data.success).each(function(index, item) {
var new_item = new FolderShareItemView({
'repo_id': repo_id,
'path': path,
'item_data': {
"group_id": item.group_info.id,
"group_name": item.group_info.name,
"perm": item.permission,
'for_user': false
}
});
$add_item.after(new_item.el);
});
groups_input.select2("val", "");
if (data.failed.length > 0) {
var err_msg = '';
$(data.failed).each(function(index, item) {
err_msg += Common.HTMLescape(item.group_name) + ': ' + item.error_msg + '<br />';
});
$('.error', panel).html(err_msg).removeClass('hide');
}
},
error: function(xhr) {
var err_msg;
if (xhr.responseText) {
var parsed_resp = $.parseJSON(xhr.responseText);
err_msg = parsed_resp.error||parsed_resp.error_msg;
} else {
err_msg = gettext("Failed. Please check the network.")
}
$('.error', panel).html(err_msg).removeClass('hide');
}
});
}
});
return SharePopupView;
});
<file_sep>/seahub/utils/__init__.py
# encoding: utf-8
import os
import re
import urllib
import urllib2
import uuid
import logging
import hashlib
import tempfile
import locale
import ConfigParser
import mimetypes
import contextlib
from datetime import datetime
from urlparse import urlparse, urljoin
import json
import ccnet
from constance import config
import seaserv
from seaserv import seafile_api
from django.core.urlresolvers import reverse
from django.core.mail import EmailMessage
from django.shortcuts import render_to_response
from django.template import RequestContext, Context, loader
from django.utils.translation import ugettext as _
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotModified
from django.utils.http import urlquote
from django.utils.html import escape
from django.views.static import serve as django_static_serve
from seahub.api2.models import Token, TokenV2
import seahub.settings
from seahub.settings import SITE_NAME, MEDIA_URL, LOGO_PATH
try:
from seahub.settings import EVENTS_CONFIG_FILE
except ImportError:
EVENTS_CONFIG_FILE = None
try:
from seahub.settings import EMAIL_HOST
IS_EMAIL_CONFIGURED = True
except ImportError:
IS_EMAIL_CONFIGURED = False
try:
from seahub.settings import CLOUD_MODE
except ImportError:
CLOUD_MODE = False
try:
from seahub.settings import ENABLE_INNER_FILESERVER
except ImportError:
ENABLE_INNER_FILESERVER = True
try:
from seahub.settings import CHECK_SHARE_LINK_TRAFFIC
except ImportError:
CHECK_SHARE_LINK_TRAFFIC = False
def is_cluster_mode():
cfg = ConfigParser.ConfigParser()
if 'SEAFILE_CENTRAL_CONF_DIR' in os.environ:
confdir = os.environ['SEAFILE_CENTRAL_CONF_DIR']
else:
confdir = os.environ['SEAFILE_CONF_DIR']
conf = os.path.join(confdir, 'seafile.conf')
cfg.read(conf)
if cfg.has_option('cluster', 'enabled'):
enabled = cfg.getboolean('cluster', 'enabled')
else:
enabled = False
if enabled:
logging.debug('cluster mode is enabled')
else:
logging.debug('cluster mode is disabled')
return enabled
CLUSTER_MODE = is_cluster_mode()
try:
from seahub.settings import OFFICE_CONVERTOR_ROOT
except ImportError:
OFFICE_CONVERTOR_ROOT = ''
try:
from seahub.settings import OFFICE_CONVERTOR_NODE
except ImportError:
OFFICE_CONVERTOR_NODE = False
from seahub.utils.file_types import *
from seahub.utils.htmldiff import HtmlDiff # used in views/files.py
EMPTY_SHA1 = '0000000000000000000000000000000000000000'
MAX_INT = 2147483647
PREVIEW_FILEEXT = {
TEXT: ('ac', 'am', 'bat', 'c', 'cc', 'cmake', 'cpp', 'cs', 'css', 'diff', 'el', 'h', 'html', 'htm', 'java', 'js', 'json', 'less', 'make', 'org', 'php', 'pl', 'properties', 'py', 'rb', 'scala', 'script', 'sh', 'sql', 'txt', 'text', 'tex', 'vi', 'vim', 'xhtml', 'xml', 'log', 'csv', 'groovy', 'rst', 'patch', 'go'),
IMAGE: ('gif', 'jpeg', 'jpg', 'png', 'ico', 'bmp'),
GIMP: ('avi', 'cel', 'fits', 'fli', 'hrz', 'miff', 'pcx', 'pix', 'pnm', 'ps', 'sgi', 'sunras', 'tga', 'tiff', 'xbm', 'xcf', 'xwd', 'xpm'),
DOCUMENT: ('doc', 'docx', 'ppt', 'pptx'),
SPREADSHEET: ('xls', 'xlsx', 'ods', 'fods'),
# SVG: ('svg',),
PDF: ('pdf',),
OPENDOCUMENT: ('odt', 'fodt', 'odp', 'fodp'),
MARKDOWN: ('markdown', 'md'),
VIDEO: ('mp4', 'ogv', 'webm', 'flv', 'wmv'),
AUDIO: ('mp3', 'oga', 'ogg'),
'3D': ('stl', 'obj'),
}
def gen_fileext_type_map():
"""
Generate previewed file extension and file type relation map.
"""
d = {}
for filetype in PREVIEW_FILEEXT.keys():
for fileext in PREVIEW_FILEEXT.get(filetype):
d[fileext] = filetype
return d
FILEEXT_TYPE_MAP = gen_fileext_type_map()
def render_permission_error(request, msg=None, extra_ctx=None):
"""
Return permisson error page.
"""
ctx = {}
ctx['error_msg'] = msg or _('permission error')
if extra_ctx:
for k in extra_ctx:
ctx[k] = extra_ctx[k]
return render_to_response('permission_error.html', ctx,
context_instance=RequestContext(request))
def render_error(request, msg=None, extra_ctx=None):
"""
Return normal error page.
"""
ctx = {}
ctx['error_msg'] = msg or _('Internal error')
if extra_ctx:
for k in extra_ctx:
ctx[k] = extra_ctx[k]
return render_to_response('error.html', ctx,
context_instance=RequestContext(request))
def list_to_string(l):
"""
Return string of a list.
"""
return ','.join(l)
def get_fileserver_root():
""" Construct seafile fileserver address and port.
Returns:
Constructed fileserver root.
"""
return config.FILE_SERVER_ROOT
def get_inner_fileserver_root():
"""Construct inner seafile fileserver address and port.
Inner fileserver root allows Seahub access fileserver through local
address, thus avoiding the overhead of DNS queries, as well as other
related issues, for example, the server can not ping itself, etc.
Returns:
http://127.0.0.1:<port>
"""
return seahub.settings.INNER_FILE_SERVER_ROOT
def gen_token(max_length=5):
"""
Generate a random token.
"""
return uuid.uuid4().hex[:max_length]
def normalize_cache_key(value, prefix=None, token=None, max_length=200):
"""Returns a cache key consisten of ``value`` and ``prefix`` and ``token``. Cache key
must not include control characters or whitespace.
"""
key = value if prefix is None else prefix + value
key = key if token is None else key + '_' + token
return urlquote(key)[:max_length]
def get_repo_last_modify(repo):
""" Get last modification time for a repo.
If head commit id of a repo is provided, we use that commit as last commit,
otherwise falls back to getting last commit of a repo which is time
consuming.
"""
if repo.head_cmmt_id is not None:
last_cmmt = seaserv.get_commit(repo.id, repo.version, repo.head_cmmt_id)
else:
logger = logging.getLogger(__name__)
logger.info('[repo %s] head_cmmt_id is missing.' % repo.id)
last_cmmt = seafile_api.get_commit_list(repo.id, 0, 1)[0]
return last_cmmt.ctime if last_cmmt else 0
def calculate_repos_last_modify(repo_list):
""" Get last modification time for repos.
"""
for repo in repo_list:
repo.latest_modify = get_repo_last_modify(repo)
def normalize_dir_path(path):
"""Add '/' at the end of directory path if necessary.
"""
if path[-1] != '/':
path = path + '/'
return path
def normalize_file_path(path):
"""Remove '/' at the end of file path if necessary.
"""
return path.rstrip('/')
# modified from django1.5:/core/validators, and remove the support for single
# quote in email address
email_re = re.compile(
r"(^[-!#$%&*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
# quoted-string, see also http://tools.ietf.org/html/rfc2822#section-3.2.5
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"'
r')@((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)$)' # domain
r'|\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$', re.IGNORECASE) # literal form, ipv4 address (SMTP 4.1.3)
def is_valid_email(email):
"""A heavy email format validation.
"""
return True if email_re.match(email) is not None else False
def is_valid_username(username):
"""Check whether username is valid, currently only email can be a username.
"""
return is_valid_email(username)
def is_ldap_user(user):
"""Check whether user is a LDAP user.
"""
return user.source == 'LDAP' or user.source == 'LDAPImport'
def check_filename_with_rename(repo_id, parent_dir, filename):
cmmts = seafile_api.get_commit_list(repo_id, 0, 1)
latest_commit = cmmts[0] if cmmts else None
if not latest_commit:
return ''
# TODO: what if parrent_dir does not exist?
dirents = seafile_api.list_dir_by_commit_and_path(repo_id, latest_commit.id,
parent_dir.encode('utf-8'))
def no_duplicate(name):
for dirent in dirents:
if dirent.obj_name == name:
return False
return True
def make_new_name(filename, i):
base, ext = os.path.splitext(filename)
if ext:
new_base = "%s (%d)" % (base, i)
return new_base + ext
else:
return "%s (%d)" % (filename, i)
if no_duplicate(filename):
return filename
else:
i = 1
while True:
new_name = make_new_name (filename, i)
if no_duplicate(new_name):
return new_name
else:
i += 1
def get_user_repos(username, org_id=None):
"""
Get all repos that user can access, including owns, shared, public, and
repo in groups.
If ``org_id`` is not None, get org repos that user can access.
"""
if org_id is None:
owned_repos = seaserv.list_personal_repos_by_owner(username)
shared_repos = seafile_api.get_share_in_repo_list(username, -1, -1)
groups_repos = []
for group in seaserv.get_personal_groups_by_user(username):
# TODO: use seafile_api.get_group_repos
groups_repos += seaserv.get_group_repos(group.id, username)
if CLOUD_MODE:
public_repos = []
else:
public_repos = seaserv.list_inner_pub_repos(username)
for r in shared_repos + public_repos:
# collumn names in shared_repo struct are not same as owned or group
# repos.
r.id = r.repo_id
r.name = r.repo_name
r.desc = r.repo_desc
r.last_modify = r.last_modified
else:
owned_repos = seafile_api.get_org_owned_repo_list(org_id, username)
shared_repos = seafile_api.get_org_share_in_repo_list(org_id, username,
-1, -1)
groups_repos = []
for group in seaserv.get_org_groups_by_user(org_id, username):
groups_repos += seafile_api.get_org_group_repos(org_id, group.id)
public_repos = seaserv.seafserv_threaded_rpc.list_org_inner_pub_repos(org_id)
for r in shared_repos + groups_repos + public_repos:
# collumn names in shared_repo struct are not same as owned
# repos.
r.id = r.repo_id
r.name = r.repo_name
r.desc = r.repo_desc
r.last_modify = r.last_modified
return (owned_repos, shared_repos, groups_repos, public_repos)
def get_file_type_and_ext(filename):
"""
Return file type and extension if the file can be previewd online,
otherwise, return unknown type.
"""
fileExt = os.path.splitext(filename)[1][1:].lower()
filetype = FILEEXT_TYPE_MAP.get(fileExt)
if filetype:
return (filetype, fileExt)
else:
return ('Unknown', fileExt)
def get_file_revision_id_size(repo_id, commit_id, path):
"""Given a commit and a file path in that commit, return the seafile id
and size of the file blob
"""
repo = seafile_api.get_repo(repo_id)
dirname = os.path.dirname(path)
filename = os.path.basename(path)
seafdir = seafile_api.list_dir_by_commit_and_path(repo_id, commit_id, dirname)
for dirent in seafdir:
if dirent.obj_name == filename:
file_size = seafile_api.get_file_size(repo.store_id, repo.version,
dirent.obj_id)
return dirent.obj_id, file_size
return None, None
def new_merge_with_no_conflict(commit):
"""Check whether a commit is a new merge, and no conflict.
Arguments:
- `commit`:
"""
if commit.second_parent_id is not None and commit.new_merge is True and \
commit.conflict is False:
return True
else:
return False
def get_commit_before_new_merge(commit):
"""Traverse parents of ``commit``, and get a commit which is not a new merge.
Pre-condition: ``commit`` must be a new merge and not conflict.
Arguments:
- `commit`:
"""
assert new_merge_with_no_conflict(commit) is True
while(new_merge_with_no_conflict(commit)):
p1 = seaserv.get_commit(commit.repo_id, commit.version, commit.parent_id)
p2 = seaserv.get_commit(commit.repo_id, commit.version, commit.second_parent_id)
commit = p1 if p1.ctime > p2.ctime else p2
assert new_merge_with_no_conflict(commit) is False
return commit
def gen_inner_file_get_url(token, filename):
"""Generate inner fileserver file url.
If ``ENABLE_INNER_FILESERVER`` set to False(defaults to True), will
returns outer fileserver file url.
Arguments:
- `token`:
- `filename`:
Returns:
e.g., http://127.0.0.1:<port>/files/<token>/<filename>
"""
if ENABLE_INNER_FILESERVER:
return '%s/files/%s/%s' % (get_inner_fileserver_root(), token,
urlquote(filename))
else:
return gen_file_get_url(token, filename)
def get_max_upload_file_size():
"""Get max upload file size from config file, defaults to no limit.
Returns ``None`` if this value is not set.
"""
return seaserv.MAX_UPLOAD_FILE_SIZE
def gen_block_get_url(token, blkid):
"""
Generate fileserver block url.
Format: http://<domain:port>/blks/<token>/<blkid>
"""
if blkid:
return '%s/blks/%s/%s' % (get_fileserver_root(), token, blkid)
else:
return '%s/blks/%s/' % (get_fileserver_root(), token)
def gen_file_get_url(token, filename):
"""
Generate fileserver file url.
Format: http://<domain:port>/files/<token>/<filename>
"""
return '%s/files/%s/%s' % (get_fileserver_root(), token, urlquote(filename))
def gen_file_upload_url(token, op, hostname=None):
url = '%s/%s/%s' % (get_fileserver_root(), op, token)
if hostname:
parsed_url = urlparse(url)
if parsed_url.port:
hostname += ':' + str(parsed_url.port)
parsed_url = parsed_url._replace(netloc=hostname)
url = parsed_url.geturl()
return url
def get_ccnet_server_addr_port():
"""get ccnet server host and port"""
return seaserv.CCNET_SERVER_ADDR, seaserv.CCNET_SERVER_PORT
def string2list(string):
"""
Split string contacted with different separators to a list, and remove
duplicated strings.
"""
tmp_str = string.replace(';', ',').replace('\n', ',').replace('\r', ',')
# Remove empty and duplicate strings
s = set()
for e in tmp_str.split(','):
e = e.strip(' ')
if not e:
continue
s.add(e)
return [ x for x in s ]
# def get_cur_ctx(request):
# ctx_dict = request.session.get('current_context', {
# 'base_template': 'myhome_base.html',
# 'org_dict': None})
# return ctx_dict
# def set_cur_ctx(request, ctx_dict):
# request.session['current_context'] = ctx_dict
# request.user.org = ctx_dict.get('org_dict', None)
def is_org_context(request):
"""An organization context is a virtual private Seafile instance on cloud
service.
Arguments:
- `request`:
"""
return request.cloud_mode and request.user.org is not None
# def check_and_get_org_by_repo(repo_id, user):
# """
# Check whether repo is org repo, get org info if it is, and set
# base template.
# """
# org_id = get_org_id_by_repo_id(repo_id)
# if org_id > 0:
# # this repo is org repo, get org info
# org = get_org_by_id(org_id)
# org._dict['is_staff'] = is_org_staff(org_id, user)
# org._dict['email'] = user
# base_template = 'org_base.html'
# else:
# org = None
# base_template = 'myhome_base.html'
# return org, base_template
def check_and_get_org_by_group(group_id, user):
"""
Check whether repo is org repo, get org info if it is, and set
base template.
"""
org_id = seaserv.get_org_id_by_group(group_id)
if org_id > 0:
# this repo is org repo, get org info
org = seaserv.get_org_by_id(org_id)
org._dict['is_staff'] = seaserv.is_org_staff(org_id, user)
org._dict['email'] = user
base_template = 'org_base.html'
else:
org = None
base_template = 'myhome_base.html'
return org, base_template
# events related
if EVENTS_CONFIG_FILE:
parsed_events_conf = ConfigParser.ConfigParser()
parsed_events_conf.read(EVENTS_CONFIG_FILE)
import seafevents
EVENTS_ENABLED = True
SeafEventsSession = seafevents.init_db_session_class(EVENTS_CONFIG_FILE)
@contextlib.contextmanager
def _get_seafevents_session():
try:
session = SeafEventsSession()
yield session
finally:
session.close()
def _same_events(e1, e2):
"""Two events are equal should follow two rules:
1. event1.repo_id = event2.repo_id
2. event1.commit.creator = event2.commit.creator
3. event1.commit.desc = event2.commit.desc
"""
if hasattr(e1, 'commit') and hasattr(e2, 'commit'):
if e1.repo_id == e2.repo_id and \
e1.commit.desc == e2.commit.desc and \
e1.commit.creator_name == e2.commit.creator_name:
return True
return False
def _get_events(username, start, count, org_id=None):
ev_session = SeafEventsSession()
valid_events = []
total_used = 0
try:
next_start = start
while True:
events = _get_events_inner(ev_session, username, next_start,
count, org_id)
if not events:
break
for e1 in events:
duplicate = False
for e2 in valid_events:
if _same_events(e1, e2): duplicate = True; break
new_merge = False
if hasattr(e1, 'commit') and e1.commit and \
new_merge_with_no_conflict(e1.commit):
new_merge = True
if not duplicate and not new_merge:
valid_events.append(e1)
total_used = total_used + 1
if len(valid_events) == count:
break
if len(valid_events) == count:
break
next_start = next_start + len(events)
finally:
ev_session.close()
for e in valid_events: # parse commit description
if hasattr(e, 'commit'):
e.commit.converted_cmmt_desc = convert_cmmt_desc_link(e.commit)
e.commit.more_files = more_files_in_commit(e.commit)
return valid_events, start + total_used
def _get_events_inner(ev_session, username, start, limit, org_id=None):
'''Read events from seafevents database, and remove events that are
no longer valid
Return 'limit' events or less than 'limit' events if no more events remain
'''
valid_events = []
next_start = start
while True:
if org_id > 0:
events = seafevents.get_org_user_events(ev_session, org_id,
username, next_start,
limit)
else:
events = seafevents.get_user_events(ev_session, username,
next_start, limit)
if not events:
break
for ev in events:
if ev.etype == 'repo-update':
repo = seafile_api.get_repo(ev.repo_id)
if not repo:
# delete the update event for repo which has been deleted
seafevents.delete_event(ev_session, ev.uuid)
continue
if repo.encrypted:
repo.password_set = seafile_api.is_password_set(
repo.id, username)
ev.repo = repo
ev.commit = seaserv.get_commit(repo.id, repo.version, ev.commit_id)
valid_events.append(ev)
if len(valid_events) == limit:
break
if len(valid_events) == limit:
break
next_start = next_start + len(valid_events)
return valid_events
def get_user_events(username, start, count):
"""Return user events list and a new start.
For example:
``get_user_events('<EMAIL>', 0, 10)`` returns the first 10
events.
``get_user_events('<EMAIL>', 5, 10)`` returns the 6th through
15th events.
"""
return _get_events(username, start, count)
def get_org_user_events(org_id, username, start, count):
return _get_events(username, start, count, org_id=org_id)
def get_log_events_by_time(log_type, tstart, tend):
"""Return log events list by start/end timestamp. (If no logs, return 'None')
"""
with _get_seafevents_session() as session:
events = seafevents.get_event_log_by_time(session, log_type, tstart, tend)
return events if events else None
def generate_file_audit_event_type(e):
return {
'file-download-web': ('web', ''),
'file-download-share-link': ('share-link',''),
'file-download-api': ('API', e.device),
'repo-download-sync': ('download-sync', e.device),
'repo-upload-sync': ('upload-sync', e.device),
}[e.etype]
def get_file_audit_events_by_path(email, org_id, repo_id, file_path, start, limit):
"""Return file audit events list by file path. (If no file audit, return 'None')
For example:
``get_file_audit_events_by_path(email, org_id, repo_id, file_path, 0, 10)`` returns the first 10
events.
``get_file_audit_events_by_path(email, org_id, repo_id, file_path, 5, 10)`` returns the 6th through
15th events.
"""
with _get_seafevents_session() as session:
events = seafevents.get_file_audit_events_by_path(session,
email, org_id, repo_id, file_path, start, limit)
return events if events else None
def get_file_audit_events(email, org_id, repo_id, start, limit):
"""Return file audit events list. (If no file audit, return 'None')
For example:
``get_file_audit_events(email, org_id, repo_id, 0, 10)`` returns the first 10
events.
``get_file_audit_events(email, org_id, repo_id, 5, 10)`` returns the 6th through
15th events.
"""
with _get_seafevents_session() as session:
events = seafevents.get_file_audit_events(session, email, org_id, repo_id, start, limit)
return events if events else None
def get_file_update_events(email, org_id, repo_id, start, limit):
"""Return file update events list. (If no file update, return 'None')
For example:
``get_file_update_events(email, org_id, repo_id, 0, 10)`` returns the first 10
events.
``get_file_update_events(email, org_id, repo_id, 5, 10)`` returns the 6th through
15th events.
"""
with _get_seafevents_session() as session:
events = seafevents.get_file_update_events(session, email, org_id, repo_id, start, limit)
return events if events else None
def get_perm_audit_events(email, org_id, repo_id, start, limit):
"""Return repo perm events list. (If no repo perm, return 'None')
For example:
``get_repo_perm_events(email, org_id, repo_id, 0, 10)`` returns the first 10
events.
``get_repo_perm_events(email, org_id, repo_id, 5, 10)`` returns the 6th through
15th events.
"""
with _get_seafevents_session() as session:
events = seafevents.get_perm_audit_events(session, email, org_id, repo_id, start, limit)
return events if events else None
def get_virus_record(repo_id=None, start=-1, limit=-1):
with _get_seafevents_session() as session:
r = seafevents.get_virus_record(session, repo_id, start, limit)
return r if r else []
def handle_virus_record(vid):
with _get_seafevents_session() as session:
return True if seafevents.handle_virus_record(session, vid) == 0 else False
def get_virus_record_by_id(vid):
with _get_seafevents_session() as session:
return seafevents.get_virus_record_by_id(session, vid)
else:
EVENTS_ENABLED = False
def get_user_events():
pass
def get_log_events_by_time():
pass
def get_org_user_events():
pass
def generate_file_audit_event_type():
pass
def get_file_audit_events_by_path():
pass
def get_file_audit_events():
pass
def get_file_update_events():
pass
def get_perm_audit_events():
pass
def get_virus_record():
pass
def handle_virus_record():
pass
def get_virus_record_by_id(vid):
pass
def calc_file_path_hash(path, bits=12):
if isinstance(path, unicode):
path = path.encode('UTF-8')
path_hash = hashlib.md5(urllib2.quote(path)).hexdigest()[:bits]
return path_hash
def get_service_url():
"""Get service url from seaserv.
"""
return config.SERVICE_URL
def get_server_id():
"""Get server id from seaserv.
"""
return getattr(seaserv, 'SERVER_ID', '-')
def get_site_scheme_and_netloc():
"""Return a string contains site scheme and network location part from
service url.
For example:
>>> get_site_scheme_and_netloc("https://example.com:8000/seafile/")
https://example.com:8000
"""
parse_result = urlparse(get_service_url())
return "%s://%s" % (parse_result.scheme, parse_result.netloc)
def send_html_email(subject, con_template, con_context, from_email, to_email,
reply_to=None):
"""Send HTML email
"""
base_context = {
'url_base': get_site_scheme_and_netloc(),
'site_name': SITE_NAME,
'media_url': MEDIA_URL,
'logo_path': LOGO_PATH,
}
t = loader.get_template(con_template)
con_context.update(base_context)
headers = {}
if IS_EMAIL_CONFIGURED:
if reply_to is not None:
headers['Reply-to'] = reply_to
msg = EmailMessage(subject, t.render(Context(con_context)), from_email,
to_email, headers=headers)
msg.content_subtype = "html"
msg.send()
def gen_dir_share_link(token):
"""Generate directory share link.
"""
return gen_shared_link(token, 'd')
def gen_file_share_link(token):
"""Generate file share link.
"""
return gen_shared_link(token, 'f')
def gen_shared_link(token, s_type):
service_url = get_service_url()
assert service_url is not None
service_url = service_url.rstrip('/')
if s_type == 'f':
return '%s/f/%s/' % (service_url, token)
else:
return '%s/d/%s/' % (service_url, token)
def gen_shared_upload_link(token):
service_url = get_service_url()
assert service_url is not None
service_url = service_url.rstrip('/')
return '%s/u/d/%s/' % (service_url, token)
def show_delete_days(request):
if request.method == 'GET':
days_str = request.GET.get('days', '')
elif request.method == 'POST':
days_str = request.POST.get('days', '')
else:
days_str = ''
try:
days = int(days_str)
except ValueError:
days = 7
return days
def is_textual_file(file_type):
"""
Check whether a file type is a textual file.
"""
if file_type == TEXT or file_type == MARKDOWN:
return True
else:
return False
def redirect_to_login(request):
from django.conf import settings
login_url = settings.LOGIN_URL
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
def mkstemp():
'''Returns (fd, filepath), the same as tempfile.mkstemp, except the
filepath is encoded in UTF-8
'''
fd, path = tempfile.mkstemp()
system_encoding = locale.getdefaultlocale()[1]
if system_encoding is not None:
path_utf8 = path.decode(system_encoding).encode('UTF-8')
return fd, path_utf8
else:
return fd, path
# File or directory operations
FILE_OP = ('Added', 'Modified', 'Renamed', 'Moved',
'Added directory', 'Renamed directory', 'Moved directory')
OPS = '|'.join(FILE_OP)
CMMT_DESC_PATT = re.compile(r'(%s) "(.*)"\s?(and \d+ more (?:files|directories))?' % OPS)
API_OPS = '|'.join((OPS, 'Deleted', 'Removed'))
API_CMMT_DESC_PATT = r'(%s) "(.*)"\s?(and \d+ more (?:files|directories))?' % API_OPS
def convert_cmmt_desc_link(commit):
"""Wrap file/folder with ``<a></a>`` in commit description.
"""
repo_id = commit.repo_id
cmmt_id = commit.id
conv_link_url = reverse('convert_cmmt_desc_link')
def link_repl(matchobj):
op = matchobj.group(1)
file_or_dir = matchobj.group(2)
remaining = matchobj.group(3)
tmp_str = '%s "<a href="%s?repo_id=%s&cmmt_id=%s&nm=%s" class="normal">%s</a>"'
if remaining:
return (tmp_str + ' %s') % (op, conv_link_url, repo_id, cmmt_id, urlquote(file_or_dir),
escape(file_or_dir), remaining)
else:
return tmp_str % (op, conv_link_url, repo_id, cmmt_id, urlquote(file_or_dir), escape(file_or_dir))
return re.sub(CMMT_DESC_PATT, link_repl, commit.desc)
def api_tsstr_sec(value):
"""Turn a timestamp to string"""
try:
return datetime.fromtimestamp(value).strftime("%Y-%m-%d %H:%M:%S")
except:
return datetime.fromtimestamp(value/1000000).strftime("%Y-%m-%d %H:%M:%S")
def api_convert_desc_link(e):
"""Wrap file/folder with ``<a></a>`` in commit description.
"""
commit = e.commit
repo_id = commit.repo_id
cmmt_id = commit.id
def link_repl(matchobj):
op = matchobj.group(1)
file_or_dir = matchobj.group(2)
remaining = matchobj.group(3)
tmp_str = '%s "<span class="file-name">%s</span>"'
if remaining:
url = reverse('api_repo_history_changes', args=[repo_id])
e.link = "%s?commit_id=%s" % (url, cmmt_id)
e.dtime = api_tsstr_sec(commit.props.ctime)
return (tmp_str + ' %s') % (op, file_or_dir, remaining)
else:
diff_result = seafile_api.diff_commits(repo_id, '', cmmt_id)
if diff_result:
for d in diff_result:
if file_or_dir not in d.name:
# skip to next diff_result if file/folder user clicked does not
# match the diff_result
continue
if d.status == 'add' or d.status == 'mod':
e.link = "api://repo/%s/files/?p=/%s" % (repo_id, d.name)
elif d.status == 'mov':
e.link = "api://repo/%s/files/?p=/%s" % (repo_id, d.new_name)
elif d.status == 'newdir':
e.link = "api://repo/%s/dir/?p=/%s" % (repo_id, d.name)
else:
continue
return tmp_str % (op, file_or_dir)
e.desc = re.sub(API_CMMT_DESC_PATT, link_repl, commit.desc)
MORE_PATT = r'and \d+ more (?:files|directories)'
def more_files_in_commit(commit):
"""Check whether added/deleted/modified more files in commit description.
"""
return True if re.search(MORE_PATT, commit.desc) else False
# file audit related
FILE_AUDIT_ENABLED = False
if EVENTS_CONFIG_FILE:
def check_file_audit_enabled():
enabled = seafevents.is_audit_enabled(parsed_events_conf)
if enabled:
logging.debug('file audit: enabled')
else:
logging.debug('file audit: not enabled')
return enabled
FILE_AUDIT_ENABLED = check_file_audit_enabled()
# office convert related
HAS_OFFICE_CONVERTER = False
if EVENTS_CONFIG_FILE:
def check_office_converter_enabled():
enabled = seafevents.is_office_converter_enabled(parsed_events_conf)
if enabled:
logging.debug('office converter: enabled')
else:
logging.debug('office converter: not enabled')
return enabled
def get_office_converter_html_dir():
return seafevents.get_office_converter_html_dir(parsed_events_conf)
def get_office_converter_limit():
return seafevents.get_office_converter_limit(parsed_events_conf)
HAS_OFFICE_CONVERTER = check_office_converter_enabled()
if HAS_OFFICE_CONVERTER:
OFFICE_HTML_DIR = get_office_converter_html_dir()
OFFICE_PREVIEW_MAX_SIZE, OFFICE_PREVIEW_MAX_PAGES = get_office_converter_limit()
all_doc_types = PREVIEW_FILEEXT[DOCUMENT] + PREVIEW_FILEEXT[OPENDOCUMENT]
PREVIEW_FILEEXT[DOCUMENT] = all_doc_types
PREVIEW_FILEEXT.pop(OPENDOCUMENT)
FILEEXT_TYPE_MAP = gen_fileext_type_map()
from seafevents.office_converter import OfficeConverterRpcClient
office_converter_rpc = None
def _get_office_converter_rpc():
global office_converter_rpc
if office_converter_rpc is None:
pool = ccnet.ClientPool(
seaserv.CCNET_CONF_PATH,
central_config_dir=seaserv.SEAFILE_CENTRAL_CONF_DIR
)
office_converter_rpc = OfficeConverterRpcClient(pool)
return office_converter_rpc
def office_convert_cluster_token(file_id):
from django.core import signing
s = '-'.join([file_id, datetime.now().strftime('%Y%m%d')])
return signing.Signer().sign(s)
def _office_convert_token_header(file_id):
return {
'X-Seafile-Office-Preview-Token': office_convert_cluster_token(file_id),
}
def cluster_delegate(delegate_func):
'''usage:
@cluster_delegate(funcA)
def func(*args):
...non-cluster logic goes here...
- In non-cluster mode, this decorator effectively does nothing.
- In cluster mode, if this node is not the office convert node,
funcA is called instead of the decorated function itself
'''
def decorated(func):
def real_func(*args, **kwargs):
cluster_internal = kwargs.pop('cluster_internal', False)
if CLUSTER_MODE and not OFFICE_CONVERTOR_NODE and not cluster_internal:
return delegate_func(*args)
else:
return func(*args)
return real_func
return decorated
def delegate_add_office_convert_task(file_id, doctype, raw_path):
url = urljoin(OFFICE_CONVERTOR_ROOT, '/office-convert/internal/add-task/')
data = urllib.urlencode({
'file_id': file_id,
'doctype': doctype,
'raw_path': raw_path,
})
headers = _office_convert_token_header(file_id)
ret = do_urlopen(url, data=data, headers=headers).read()
return json.loads(ret)
def delegate_query_office_convert_status(file_id, page):
url = urljoin(OFFICE_CONVERTOR_ROOT, '/office-convert/internal/status/')
url += '?file_id=%s&page=%s' % (file_id, page)
headers = _office_convert_token_header(file_id)
ret = do_urlopen(url, headers=headers).read()
return json.loads(ret)
def delegate_get_office_converted_page(request, repo_id, commit_id, path, static_filename, file_id):
url = urljoin(OFFICE_CONVERTOR_ROOT,
'/office-convert/internal/static/%s/%s%s/%s' % (
repo_id, commit_id, urlquote(path), urlquote(static_filename)))
url += '?file_id=' + file_id
headers = _office_convert_token_header(file_id)
timestamp = request.META.get('HTTP_IF_MODIFIED_SINCE')
if timestamp:
headers['If-Modified-Since'] = timestamp
try:
ret = do_urlopen(url, headers=headers)
data = ret.read()
except urllib2.HTTPError, e:
if timestamp and e.code == 304:
return HttpResponseNotModified()
else:
raise
content_type = ret.headers.get('content-type', None)
if content_type is None:
dummy, ext = os.path.splitext(os.path.basename(path))
content_type = mimetypes.types_map.get(ext, 'application/octet-stream')
resp = HttpResponse(data, content_type=content_type)
if 'last-modified' in ret.headers:
resp['Last-Modified'] = ret.headers.get('last-modified')
return resp
@cluster_delegate(delegate_add_office_convert_task)
def add_office_convert_task(file_id, doctype, raw_path):
rpc = _get_office_converter_rpc()
d = rpc.add_task(file_id, doctype, raw_path)
return {
'exists': False,
}
@cluster_delegate(delegate_query_office_convert_status)
def query_office_convert_status(file_id, page):
rpc = _get_office_converter_rpc()
d = rpc.query_convert_status(file_id, page)
ret = {}
if d.error:
ret['error'] = d.error
ret['status'] = 'ERROR'
else:
ret['success'] = True
ret['status'] = d.status
ret['info'] = d.info
return ret
@cluster_delegate(delegate_get_office_converted_page)
def get_office_converted_page(request, repo_id, commit_id, path, static_filename, file_id):
return django_static_serve(request,
os.path.join(file_id, static_filename),
document_root=OFFICE_HTML_DIR)
def prepare_converted_html(raw_path, obj_id, doctype, ret_dict):
try:
add_office_convert_task(obj_id, doctype, raw_path)
except:
logging.exception('failed to add_office_convert_task:')
return _(u'Internal error')
return None
# search realted
HAS_FILE_SEARCH = False
if EVENTS_CONFIG_FILE:
def check_search_enabled():
enabled = False
if hasattr(seafevents, 'is_search_enabled'):
enabled = seafevents.is_search_enabled(parsed_events_conf)
if enabled:
logging.debug('search: enabled')
else:
logging.debug('search: not enabled')
return enabled
HAS_FILE_SEARCH = check_search_enabled()
TRAFFIC_STATS_ENABLED = False
if EVENTS_CONFIG_FILE and hasattr(seafevents, 'get_user_traffic_stat'):
TRAFFIC_STATS_ENABLED = True
def get_user_traffic_stat(username):
session = SeafEventsSession()
try:
stat = seafevents.get_user_traffic_stat(session, username)
finally:
session.close()
return stat
def get_user_traffic_list(month, start=0, limit=25):
session = SeafEventsSession()
try:
stat = seafevents.get_user_traffic_list(session, month, start, limit)
finally:
session.close()
return stat
else:
def get_user_traffic_stat(username):
pass
def get_user_traffic_list():
pass
def user_traffic_over_limit(username):
"""Return ``True`` if user traffic over the limit, otherwise ``False``.
"""
if not CHECK_SHARE_LINK_TRAFFIC:
return False
from seahub_extra.plan.models import UserPlan
from seahub_extra.plan.settings import PLAN
up = UserPlan.objects.get_valid_plan_by_user(username)
plan = 'Free' if up is None else up.plan_type
traffic_limit = int(PLAN[plan]['share_link_traffic']) * 1024 * 1024 * 1024
try:
stat = get_user_traffic_stat(username)
except Exception as e:
logger = logging.getLogger(__name__)
logger.error('Failed to get user traffic stat: %s' % username,
exc_info=True)
return True
if stat is None: # No traffic record yet
return False
month_traffic = stat['file_view'] + stat['file_download'] + stat['dir_download']
return True if month_traffic >= traffic_limit else False
def is_user_password_strong(password):
"""Return ``True`` if user's password is STRONG, otherwise ``False``.
STRONG means password has at least USER_PASSWORD_STRENGTH_LEVEL(3) types of the bellow:
num, upper letter, lower letter, other symbols
"""
if len(password) < config.USER_PASSWORD_MIN_LENGTH:
return False
else:
num = 0
for letter in password:
# get ascii dec
# bitwise OR
num |= get_char_mode(ord(letter))
if calculate_bitwise(num) < config.USER_PASSWORD_STRENGTH_LEVEL:
return False
else:
return True
def get_char_mode(n):
"""Return different num according to the type of given letter:
'1': num,
'2': upper_letter,
'4': lower_letter,
'8': other symbols
"""
if (n >= 48 and n <= 57): #nums
return 1;
if (n >= 65 and n <= 90): #uppers
return 2;
if (n >= 97 and n <= 122): #lowers
return 4;
else:
return 8;
def calculate_bitwise(num):
"""Return different level according to the given num:
"""
level = 0
for i in range(4):
# bitwise AND
if (num&1):
level += 1
# Right logical shift
num = num >> 1
return level
def do_md5(s):
if isinstance(s, unicode):
s = s.encode('UTF-8')
return hashlib.md5(s).hexdigest()
def do_urlopen(url, data=None, headers=None):
headers = headers or {}
req = urllib2.Request(url, data=data, headers=headers)
ret = urllib2.urlopen(req)
return ret
def is_pro_version():
if EVENTS_CONFIG_FILE:
return True
else:
return False
def clear_token(username):
'''
clear web api and repo sync token
when delete/inactive an user
'''
Token.objects.filter(user = username).delete()
TokenV2.objects.filter(user = username).delete()
seafile_api.delete_repo_tokens_by_email(username)
def send_perm_audit_msg(etype, from_user, to, repo_id, path, perm):
"""Send repo permission audit msg.
Arguments:
- `etype`: add/modify/delete-repo-perm
- `from_user`: email
- `to`: email or group_id or all(public)
- `repo_id`: origin repo id
- `path`: dir path
- `perm`: r or rw
"""
msg = 'perm-update\t%s\t%s\t%s\t%s\t%s\t%s' % \
(etype, from_user, to, repo_id, path, perm)
msg_utf8 = msg.encode('utf-8')
try:
seaserv.send_message('seahub.stats', msg_utf8)
except Exception as e:
logger.error("Error when sending perm-audit-%s message: %s" %
(etype, str(e)))
def get_origin_repo_info(repo_id):
repo = seafile_api.get_repo(repo_id)
if repo.origin_repo_id is not None:
origin_repo_id = repo.origin_repo_id
origin_path = repo.origin_path
return (origin_repo_id, origin_path)
return (None, None)
def within_time_range(d1, d2, maxdiff_seconds):
'''Return true if two datetime.datetime object differs less than the given seconds'''
delta = d2 - d1 if d2 > d1 else d1 - d2
# delta.total_seconds() is only available in python 2.7+
diff = (delta.microseconds + (delta.seconds + delta.days*24*3600) * 1e6) / 1e6
return diff < maxdiff_seconds
def is_org_repo_creation_allowed(request):
"""Whether or not allow a user create organization library.
"""
if request.user.is_staff:
return True
else:
return config.ENABLE_USER_CREATE_ORG_REPO
<file_sep>/seahub/profile/views.py
# encoding: utf-8
from django.conf import settings
import json
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import messages
from django.utils.translation import ugettext as _
import seaserv
from seaserv import seafile_api
from forms import DetailedProfileForm
from models import Profile, DetailedProfile
from utils import refresh_cache
from seahub.auth.decorators import login_required
from seahub.utils import is_org_context, is_pro_version, is_valid_username
from seahub.base.accounts import User
from seahub.base.templatetags.seahub_tags import email2nickname
from seahub.contacts.models import Contact
from seahub.options.models import UserOptions, CryptoOptionNotSetError
from seahub.utils import is_ldap_user
from seahub.views import get_owned_repo_list
@login_required
def edit_profile(request):
"""
Show and edit user profile.
"""
username = request.user.username
form_class = DetailedProfileForm
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
form.save(username=username)
messages.success(request, _(u'Successfully edited profile.'))
# refresh nickname cache
refresh_cache(request.user.username)
return HttpResponseRedirect(reverse('edit_profile'))
else:
messages.error(request, _(u'Failed to edit profile'))
else:
profile = Profile.objects.get_profile_by_user(username)
d_profile = DetailedProfile.objects.get_detailed_profile_by_user(
username)
init_dict = {}
if profile:
init_dict['nickname'] = profile.nickname
init_dict['intro'] = profile.intro
init_dict['login_id'] = profile.login_id
init_dict['contact_email'] = profile.contact_email
if d_profile:
init_dict['department'] = d_profile.department
init_dict['telephone'] = d_profile.telephone
form = form_class(init_dict)
# common logic
try:
server_crypto = UserOptions.objects.is_server_crypto(username)
except CryptoOptionNotSetError:
# Assume server_crypto is ``False`` if this option is not set.
server_crypto = False
sub_lib_enabled = UserOptions.objects.is_sub_lib_enabled(username)
default_repo_id = UserOptions.objects.get_default_repo(username)
if default_repo_id:
default_repo = seafile_api.get_repo(default_repo_id)
else:
default_repo = None
owned_repos = get_owned_repo_list(request)
owned_repos = filter(lambda r: not r.is_virtual, owned_repos)
return render_to_response('profile/set_profile.html', {
'form': form,
'server_crypto': server_crypto,
"sub_lib_enabled": sub_lib_enabled,
'force_server_crypto': settings.FORCE_SERVER_CRYPTO,
'default_repo': default_repo,
'owned_repos': owned_repos,
'is_pro': is_pro_version(),
'is_ldap_user': is_ldap_user(request.user),
}, context_instance=RequestContext(request))
@login_required
def user_profile(request, username):
if is_valid_username(username):
try:
user = User.objects.get(email=username)
except User.DoesNotExist:
user = None
else:
user = None
nickname = '' if user is None else email2nickname(user.username)
if user is not None:
profile = Profile.objects.get_profile_by_user(user.username)
intro = profile.intro if profile else ''
d_profile = DetailedProfile.objects.get_detailed_profile_by_user(
user.username)
else:
intro = _(u'Has not accepted invitation yet')
d_profile = None
return render_to_response('profile/user_profile.html', {
'user': user,
'nickname': nickname,
'intro': intro,
'd_profile': d_profile,
}, context_instance=RequestContext(request))
@login_required
def get_user_profile(request, user):
data = {
'email': user,
'user_nickname': '',
'user_intro': '',
'err_msg': '',
'new_user': ''
}
content_type = 'application/json; charset=utf-8'
try:
user_check = User.objects.get(email=user)
except User.DoesNotExist:
user_check = None
if user_check:
profile = Profile.objects.filter(user=user)
if profile:
profile = profile[0]
data['user_nickname'] = profile.nickname
data['user_intro'] = profile.intro
else:
data['user_intro'] = _(u'Has not accepted invitation yet')
if user == request.user.username or \
Contact.objects.filter(user_email=request.user.username,
contact_email=user).count() > 0:
data['new_user'] = False
else:
data['new_user'] = True
return HttpResponse(json.dumps(data), content_type=content_type)
@login_required
def delete_user_account(request):
if request.method != 'POST':
raise Http404
username = request.user.username
if username == '<EMAIL>':
messages.error(request, _(u'Demo account can not be deleted.'))
next = request.META.get('HTTP_REFERER', settings.SITE_ROOT)
return HttpResponseRedirect(next)
user = User.objects.get(email=username)
user.delete()
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.ccnet_threaded_rpc.remove_org_user(org_id, username)
return HttpResponseRedirect(settings.LOGIN_URL)
@login_required
def default_repo(request):
"""Handle post request to create default repo for user.
"""
if request.method != 'POST':
raise Http404
repo_id = request.POST.get('dst_repo', '')
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
repo = seafile_api.get_repo(repo_id)
if repo is None:
messages.error(request, _('Failed to set default library.'))
return HttpResponseRedirect(next)
if repo.encrypted:
messages.error(request, _('Can not set encrypted library as default library.'))
return HttpResponseRedirect(next)
username = request.user.username
UserOptions.objects.set_default_repo(username, repo.id)
messages.success(request, _('Successfully set "%s" as your default library.') % repo.name)
return HttpResponseRedirect(next)
<file_sep>/seahub/templates/snippets/events_body.html
{% load seahub_tags avatar_tags i18n %}
{% for e_group in event_groups %}
<h4 class="event-group-hd">{{ e_group.date }}</h4>
<ol class="event-group-bd">
{% for e in e_group.events %}
<li class="event-item">
{% avatar e.author 36 %}
<div class="txt">
{% if e.etype == "repo-update" %}
{% with repo=e.repo commit=e.commit %}
<p class="w100 ovhd">
<a href="{% url 'view_common_lib_dir' repo.id '' %}" class="updated-repo normal fright">{{ repo.name }}</a>
<span class="cmt-desc">
{{ commit.converted_cmmt_desc|translate_commit_desc_escape|safe }}
{% if commit.more_files %}
{% if repo.encrypted %}
<a class="lsch-encrypted"{% if repo.password_set %} data-passwordset="true"{% endif %} href="#" data-url="{% url 'repo_history_changes' repo.id %}?commit_id={{ commit.id }}" data-repoid="{{repo.id}}" data-reponame="{{repo.name}}" data-time="{{ commit.props.ctime|tsstr_sec }}">{% trans 'Details' %}</a>
{% else %}
<a class="lsch" href="#" data-url="{% url 'repo_history_changes' repo.id %}?commit_id={{ commit.id }}" data-time="{{ commit.props.ctime|tsstr_sec }}">{% trans 'Details' %}</a>
{% endif %}
{% endif %}
</span>
</p>
{% endwith %}
{% endif %}
{% if e.etype == "repo-create" %}
<p>{% trans "Created library" %} <a href="{% url 'view_common_lib_dir' e.repo_id '' %}" class="normal">{{ e.repo_name }}</a></p>
{% endif %}
{% if e.etype == "repo-delete" %}
<p>{% blocktrans with library_name=e.repo_name %}Deleted library {{ library_name }}{% endblocktrans %}</p>
{% endif %}
<p><a class="normal" href="{% url 'user_profile' e.author %}">{{ e.author|email2nickname }}</a> <span class="time">{{ e.time|translate_seahub_time }}</span></p>
</div>
</li>
{% endfor %}
</ol>
{% endfor %}
<file_sep>/static/scripts/app/views/folder-share-item.js
define([
'jquery',
'underscore',
'backbone',
'common'
], function($, _, Backbone, Common) {
'use strict';
var FolderShareItemView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#folder-perm-item-tmpl').html()),
initialize: function(options) {
this.item_data = options.item_data;
this.repo_id = options.repo_id;
this.path = options.path;
this.render();
},
render: function () {
this.$el.html(this.template(this.item_data));
return this;
},
events: {
'mouseenter': 'showOpIcons',
'mouseleave': 'hideOpIcons',
'click .perm-edit-icon': 'editIconClick',
'change .perm-toggle-select': 'editPerm',
'click .delete-icon': 'del'
},
showOpIcons: function () {
this.$el.find('.op-icon').removeClass('vh');
},
hideOpIcons: function () {
this.$el.find('.op-icon').addClass('vh');
},
editIconClick: function (e) {
$(e.currentTarget).closest('td')
.find('.perm').addClass('hide').end()
.find('.perm-toggle-select').removeClass('hide');
},
editPerm: function (e) {
var _this = this;
var item_data = this.item_data;
var url = Common.getUrl({
name: 'dir_shared_items',
repo_id: this.repo_id
}) + '?p=' + encodeURIComponent(this.path);
if (item_data.for_user) {
url += '&share_type=user&username=' + encodeURIComponent(item_data.user);
} else {
url += '&share_type=group&group_id=' + encodeURIComponent(item_data.group_id);
}
var perm = $(e.currentTarget).val();
$.ajax({
url: url,
dataType: 'json',
method: 'POST',
beforeSend: Common.prepareCSRFToken,
data: {
'permission': perm
},
success: function () {
item_data.perm = perm;
_this.render();
},
error: function(xhr) {
var err_msg;
if (xhr.responseText) {
err_msg = gettext("Edit failed");
} else {
err_msg = gettext("Failed. Please check the network.");
}
if (item_data.for_user) {
$('#dir-user-share .error').html(err_msg).removeClass('hide');
} else {
$('#dir-group-group .error').html(err_msg).removeClass('hide');
}
}
});
},
del: function () {
var _this = this;
var item_data = this.item_data;
var url = Common.getUrl({
name: 'dir_shared_items',
repo_id: this.repo_id
}) + '?p=' + encodeURIComponent(this.path);
if (item_data.for_user) {
url += '&share_type=user&username=' + encodeURIComponent(item_data.user);
} else {
url += '&share_type=group&group_id=' + encodeURIComponent(item_data.group_id);
}
$.ajax({
url: url,
dataType: 'json',
method: 'DELETE',
beforeSend: Common.prepareCSRFToken,
success: function () {
_this.remove();
},
error: function (xhr) {
var err_msg;
if (xhr.responseText) {
err_msg = gettext("Delete failed");
} else {
err_msg = gettext("Failed. Please check the network.");
}
if (item_data.for_user) {
$('#dir-user-share .error').html(err_msg).removeClass('hide');
} else {
$('#dir-group-group .error').html(err_msg).removeClass('hide');
}
}
});
}
});
return FolderShareItemView;
});
<file_sep>/seahub/utils/devices.py
import logging
import datetime
from seaserv import seafile_api
from seahub.api2.models import TokenV2, DESKTOP_PLATFORMS
logger = logging.getLogger(__name__)
__all__ = [
'get_user_devices',
'do_unlink_device',
]
def _last_sync_time(repos):
latest_sync_time = max([r['sync_time'] for r in repos])
return datetime.datetime.fromtimestamp(latest_sync_time)
def get_user_devices(username):
devices = TokenV2.objects.get_user_devices(username)
peer_repos_map = get_user_synced_repo_infos(username)
for device in devices:
if device['platform'] in DESKTOP_PLATFORMS:
peer_id = device['device_id']
repos = peer_repos_map.get(peer_id, [])
device['synced_repos'] = repos
if repos:
device['last_accessed'] = max(device['last_accessed'],
_last_sync_time(repos))
return devices
def get_user_synced_repo_infos(username):
'''Return a (client_ccnet_peer_id, synced_repos_on_that_client) dict'''
tokens = []
try:
tokens = seafile_api.list_repo_tokens_by_email(username)
except:
return {}
def sort_by_sync_time_descending(a, b):
if isinstance(a, dict):
return cmp(b['sync_time'], a['sync_time'])
else:
return cmp(b.sync_time, a.sync_time)
tokens.sort(sort_by_sync_time_descending, reverse=True)
peer_repos_map = {}
for token in tokens:
peer_id = token.peer_id
repo_id = token.repo_id
if peer_id not in peer_repos_map:
peer_repos_map[peer_id] = {}
peer_repos_map[peer_id][repo_id] = {
'repo_id': token.repo_id,
'repo_name': token.repo_name,
'sync_time': token.sync_time
}
ret = {}
for peer_id, repos in peer_repos_map.iteritems():
ret[peer_id] = sorted(repos.values(), sort_by_sync_time_descending)
return ret
def do_unlink_device(username, platform, device_id):
if platform in DESKTOP_PLATFORMS:
# For desktop client, we also remove the sync tokens
msg = 'failed to delete_repo_tokens_by_peer_id'
try:
if seafile_api.delete_repo_tokens_by_peer_id(username, device_id) < 0:
logger.warning(msg)
raise Exception(msg)
except:
logger.exception(msg)
raise
TokenV2.objects.delete_device_token(username, platform, device_id)
<file_sep>/tests/api/test_shared_repo.py
import json
from seahub.test_utils import BaseTestCase
from constance import config
from seaserv import seafile_api, ccnet_threaded_rpc
class SharedRepoTest(BaseTestCase):
def setUp(self):
self.repo_id = self.create_repo(name='test-admin-repo', desc='',
username=self.admin.username,
passwd=None)
self.shared_repo_url = '/api2/shared-repos/%s/?share_type=public&permission=rw'
config.ENABLE_USER_CREATE_ORG_REPO = 1
def tearDown(self):
self.remove_repo(self.repo_id)
def test_admin_can_share_repo_to_public(self):
self.login_as(self.admin)
url = self.shared_repo_url % self.repo_id
resp = self.client.put(url)
self.assertEqual(200, resp.status_code)
assert "success" in resp.content
def test_user_can_share_repo_to_public(self):
self.login_as(self.user)
url = self.shared_repo_url % self.repo.id
resp = self.client.put(url)
self.assertEqual(200, resp.status_code)
assert "success" in resp.content
def test_admin_can_set_pub_repo_when_setting_disalbed(self):
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is True
config.ENABLE_USER_CREATE_ORG_REPO = False
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is False
self.login_as(self.admin)
resp = self.client.put(self.shared_repo_url % self.repo_id)
self.assertEqual(200, resp.status_code)
assert "success" in resp.content
def test_user_can_not_set_pub_repo_when_setting_disalbed(self):
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is True
config.ENABLE_USER_CREATE_ORG_REPO = False
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is False
self.login_as(self.user)
resp = self.client.put(self.shared_repo_url % self.repo.id)
self.assertEqual(403, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['error_msg'] == 'Failed to share library to public: permission denied.'
def test_admin_can_unshare_public_repo(self):
seafile_api.add_inner_pub_repo(self.repo_id, "r")
self.login_as(self.admin)
url = self.shared_repo_url % self.repo_id
resp = self.client.delete(url)
self.assertEqual(200, resp.status_code)
assert "success" in resp.content
def test_user_can_unshare_public_repo(self):
seafile_api.add_inner_pub_repo(self.repo_id, "r")
self.login_as(self.user)
url = self.shared_repo_url % self.repo_id
resp = self.client.delete(url)
self.assertEqual(403, resp.status_code)
assert 'You do not have permission to unshare library.' in resp.content
<file_sep>/static/scripts/app/views/myhome-repos.js
define([
'jquery',
'underscore',
'backbone',
'common',
'app/collections/repos',
'app/views/repo',
'app/views/add-repo',
], function($, _, Backbone, Common, RepoCollection, RepoView, AddRepoView) {
'use strict';
var ReposView = Backbone.View.extend({
el: $('#repo-tabs'),
reposHdTemplate: _.template($('#my-repos-hd-tmpl').html()),
events: {
'click .repo-create': 'createRepo',
'click #my-own-repos .by-name': 'sortByName',
'click #my-own-repos .by-time': 'sortByTime'
},
initialize: function(options) {
this.$tabs = $('#repo-tabs');
this.$table = this.$('#my-own-repos table');
this.$tableHead = $('thead', this.$table);
this.$tableBody = $('tbody', this.$table);
this.$loadingTip = $('.loading-tip', this.$tabs);
this.$emptyTip = $('#my-own-repos .empty-tips');
this.$repoCreateBtn = this.$('.repo-create');
this.repos = new RepoCollection();
this.listenTo(this.repos, 'add', this.addOne);
this.listenTo(this.repos, 'reset', this.reset);
},
addOne: function(repo, collection, options) {
var view = new RepoView({model: repo});
if (options.prepend) {
this.$tableBody.prepend(view.render().el);
} else {
this.$tableBody.append(view.render().el);
}
},
renderReposHd: function() {
this.$tableHead.html(this.reposHdTemplate());
},
reset: function() {
this.$('.error').hide();
this.$loadingTip.hide();
if (this.repos.length) {
this.$emptyTip.hide();
this.renderReposHd();
this.$tableBody.empty();
this.repos.each(this.addOne, this);
this.$table.show();
} else {
this.$table.hide();
this.$emptyTip.show();
}
if (app.pageOptions.guide_enabled) {
$('#guide-for-new').modal({appendTo: '#main', focus:false});
app.pageOptions.guide_enabled = false;
}
},
showMyRepos: function() {
this.$tabs.show();
$('#mylib-tab').parent().addClass('ui-state-active');
this.$table.hide();
var $loadingTip = this.$loadingTip;
$loadingTip.show();
var _this = this;
this.repos.fetch({
cache: false, // for IE
reset: true,
success: function (collection, response, opts) {
},
error: function (collection, response, opts) {
$loadingTip.hide();
var $error = _this.$('.error');
var err_msg;
if (response.responseText) {
if (response['status'] == 401 || response['status'] == 403) {
err_msg = gettext("Permission error");
} else {
err_msg = gettext("Error");
}
} else {
err_msg = gettext('Please check the network.');
}
$error.html(err_msg).show();
}
});
},
show: function() {
this.$repoCreateBtn.show();
this.showMyRepos();
},
hide: function() {
this.$repoCreateBtn.hide();
this.$el.hide();
this.$table.hide();
this.$emptyTip.hide();
$('#mylib-tab', this.$tabs).parent().removeClass('ui-state-active');
},
createRepo: function() {
new AddRepoView(this.repos);
},
sortByName: function() {
$('.by-time .sort-icon').hide();
var repos = this.repos;
var el = $('.by-name .sort-icon', this.$table);
repos.comparator = function(a, b) { // a, b: model
var result = Common.compareTwoWord(a.get('name'), b.get('name'));
if (el.hasClass('icon-caret-up')) {
return -result;
} else {
return result;
}
};
repos.sort();
this.$tableBody.empty();
repos.each(this.addOne, this);
el.toggleClass('icon-caret-up icon-caret-down').show();
repos.comparator = null;
},
sortByTime: function() {
$('.by-name .sort-icon').hide();
var repos = this.repos;
var el = $('.by-time .sort-icon', this.$table);
repos.comparator = function(a, b) { // a, b: model
if (el.hasClass('icon-caret-down')) {
return a.get('mtime') < b.get('mtime') ? 1 : -1;
} else {
return a.get('mtime') < b.get('mtime') ? -1 : 1;
}
};
repos.sort();
this.$tableBody.empty();
repos.each(this.addOne, this);
el.toggleClass('icon-caret-up icon-caret-down').show();
repos.comparator = null;
}
});
return ReposView;
});
<file_sep>/tests/seahub/group/views/test_group.py
import json
from django.core.urlresolvers import reverse
import requests
from seahub.group.models import PublicGroup
from seahub.share.models import FileShare
from seahub.test_utils import BaseTestCase
from tests.common.utils import randstring
class GroupAddTest(BaseTestCase):
def setUp(self):
self.login_as(self.user)
def test_can_add(self):
resp = self.client.post(reverse('group_add'), {
'group_name': 'test_group_%s' % randstring(6)
}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
assert json.loads(resp.content)['success'] is True
def test_can_add_with_blank(self):
resp = self.client.post(reverse('group_add'), {
'group_name': 'test group %s' % randstring(6)
}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
assert json.loads(resp.content)['success'] is True
def test_can_add_with_hyphen(self):
resp = self.client.post(reverse('group_add'), {
'group_name': 'test-group-%s' % randstring(6)
}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
assert json.loads(resp.content)['success'] is True
def test_can_add_with_blank_and_hyphen(self):
resp = self.client.post(reverse('group_add'), {
'group_name': 'test-group %s' % randstring(6)
}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
assert json.loads(resp.content)['success'] is True
def test_can_not_add_with_invalid_name(self):
resp = self.client.post(reverse('group_add'), {
'group_name': 'test*group(name)'
}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(400, resp.status_code)
class GroupDiscussTest(BaseTestCase):
def setUp(self):
self.login_as(self.user)
def tearDown(self):
self.remove_group()
def test_can_render(self):
resp = self.client.get(reverse('group_discuss', args=[self.group.id]))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'group/group_discuss.html')
def test_public_group_404(self):
self.pub_grp = PublicGroup(group_id=self.group.id).save()
self.client.post(
reverse('auth_login'), {'username': self.user.username,
'password': '<PASSWORD>'}
)
resp = self.client.get(reverse('group_discuss', args=[self.group.id]))
assert resp.status_code == 404
<file_sep>/tests/api/test_search_user.py
import json
from django.core.urlresolvers import reverse
from seahub.profile.models import Profile
from seahub.profile.utils import refresh_cache
from seahub.test_utils import BaseTestCase
class SearchUserTest(BaseTestCase):
def setUp(self):
self.login_as(self.user)
self.endpoint = reverse('search-user')
def test_can_search(self):
p = Profile.objects.add_or_update(self.user.email, nickname="test")
p.contact_email = '<EMAIL>'
p.save()
resp = self.client.get(self.endpoint + '?q=' + self.user.email)
json_resp = json.loads(resp.content)
self.assertEqual(200, resp.status_code)
assert json_resp['users'] is not None
assert json_resp['users'][0]['email'] == self.user.email
assert json_resp['users'][0]['avatar'] is not None
assert json_resp['users'][0]['avatar_url'] is not None
assert json_resp['users'][0]['name'] == 'test'
assert json_resp['users'][0]['contact_email'] == '<EMAIL>'
def test_can_search_by_nickname(self):
admin_email = self.admin.email
p = Profile.objects.add_or_update(admin_email, nickname="<NAME>")
p.contact_email = '<EMAIL>'
p.save()
refresh_cache(self.user.email)
resp = self.client.get(self.endpoint + '?q=' + "Carl")
json_resp = json.loads(resp.content)
self.assertEqual(200, resp.status_code)
assert json_resp['users'] is not None
assert json_resp['users'][0]['email'] == admin_email
assert json_resp['users'][0]['avatar'] is not None
assert json_resp['users'][0]['avatar_url'] is not None
assert json_resp['users'][0]['name'] == '<NAME>'
assert json_resp['users'][0]['contact_email'] == '<EMAIL>'
def test_can_search_by_nickname_insensitive(self):
admin_email = self.admin.email
p = Profile.objects.add_or_update(admin_email, nickname="<NAME>")
p.contact_email = '<EMAIL>'
p.save()
refresh_cache(admin_email)
# test lower case
resp = self.client.get(self.endpoint + '?q=' + "carl")
json_resp = json.loads(resp.content)
self.assertEqual(200, resp.status_code)
assert json_resp['users'] is not None
assert json_resp['users'][0]['email'] == admin_email
assert json_resp['users'][0]['avatar'] is not None
assert json_resp['users'][0]['avatar_url'] is not None
assert json_resp['users'][0]['name'] == '<NAME>'
assert json_resp['users'][0]['contact_email'] == '<EMAIL>'
# test upper case
resp = self.client.get(self.endpoint + '?q=' + "CARL")
json_resp = json.loads(resp.content)
self.assertEqual(200, resp.status_code)
assert json_resp['users'] is not None
assert json_resp['users'][0]['email'] == admin_email
assert json_resp['users'][0]['avatar'] is not None
assert json_resp['users'][0]['avatar_url'] is not None
assert json_resp['users'][0]['name'] == '<NAME>'
assert json_resp['users'][0]['contact_email'] == '<EMAIL>'
<file_sep>/seahub/thumbnail/urls.py
from django.conf.urls.defaults import *
from views import thumbnail_create, thumbnail_get, share_link_thumbnail_get, \
share_link_thumbnail_create
urlpatterns = patterns('',
url(r'^(?P<repo_id>[-0-9a-f]{36})/create/$', thumbnail_create, name='thumbnail_create'),
url(r'^(?P<repo_id>[-0-9a-f]{36})/(?P<size>[0-9]+)/(?P<path>.*)$', thumbnail_get, name='thumbnail_get'),
url(r'^(?P<token>[a-f0-9]{10})/create/$', share_link_thumbnail_create, name='share_link_thumbnail_create'),
url(r'^(?P<token>[a-f0-9]{10})/(?P<size>[0-9]+)/(?P<path>.*)$', share_link_thumbnail_get, name='share_link_thumbnail_get'),
)
<file_sep>/seahub/profile/models.py
import logging
from django.conf import settings
from django.db import models
from django.core.cache import cache
from django.dispatch import receiver
from seahub.base.fields import LowerCaseCharField
from seahub.profile.settings import EMAIL_ID_CACHE_PREFIX, EMAIL_ID_CACHE_TIMEOUT
from registration.signals import user_registered
# Get an instance of a logger
logger = logging.getLogger(__name__)
class ProfileManager(models.Manager):
def add_or_update(self, username, nickname, intro='', lang_code=None):
"""Add or update user profile.
"""
try:
profile = self.get(user=username)
profile.nickname = nickname
profile.intro = intro
profile.lang_code = lang_code
except Profile.DoesNotExist:
profile = self.model(user=username, nickname=nickname,
intro=intro, lang_code=lang_code)
profile.save(using=self._db)
return profile
def get_profile_by_user(self, username):
"""Get a user's profile.
"""
try:
return super(ProfileManager, self).get(user=username)
except Profile.DoesNotExist:
return None
def get_contact_email_by_user(self, username):
"""Get a user's contact email, use username(login email) if not found.
"""
p = self.get_profile_by_user(username)
if p and p.contact_email:
return p.contact_email
else:
return username
def get_username_by_login_id(self, login_id):
"""Convert a user's login id to username(login email).
"""
if not login_id:
return None
try:
return super(ProfileManager, self).get(login_id=login_id).user
except Profile.DoesNotExist:
return None
def get_user_language(self, username):
"""Get user's language from profile. Return default language code if
user has no preferred language.
Arguments:
- `self`:
- `username`:
"""
try:
profile = self.get(user=username)
if profile.lang_code is not None:
return profile.lang_code
else:
return settings.LANGUAGE_CODE
except Profile.DoesNotExist:
return settings.LANGUAGE_CODE
def delete_profile_by_user(self, username):
self.filter(user=username).delete()
class Profile(models.Model):
user = models.EmailField(unique=True)
nickname = models.CharField(max_length=64, blank=True)
intro = models.TextField(max_length=256, blank=True)
lang_code = models.TextField(max_length=50, null=True, blank=True)
# Login id can be email or anything else used to login.
login_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
# Contact email is used to receive emails.
contact_email = models.EmailField(max_length=225, db_index=True, null=True, blank=True)
institution = models.CharField(max_length=225, db_index=True, null=True, blank=True)
objects = ProfileManager()
def set_lang_code(self, lang_code):
self.lang_code = lang_code
self.save()
class DetailedProfileManager(models.Manager):
def add_detailed_profile(self, username, department, telephone):
d_profile = self.model(user=username, department=department,
telephone=telephone)
d_profile.save(using=self._db)
return d_profile
def add_or_update(self, username, department, telephone):
try:
d_profile = self.get(user=username)
d_profile.department = department
d_profile.telephone = telephone
except DetailedProfile.DoesNotExist:
d_profile = self.model(user=username, department=department,
telephone=telephone)
d_profile.save(using=self._db)
return d_profile
def get_detailed_profile_by_user(self, username):
"""Get a user's profile.
"""
ret = list(super(DetailedProfileManager, self).filter(user=username))
if len(ret) == 0:
return None
elif len(ret) == 1:
return ret[0]
else:
# XXX: got multiple records, delete them all.
super(DetailedProfileManager, self).filter(user=username).delete()
logger.warn('Remove multiple detailed profile records for user %s' % username)
return None
class DetailedProfile(models.Model):
user = LowerCaseCharField(max_length=255, db_index=True)
department = models.CharField(max_length=512)
telephone = models.CharField(max_length=100)
objects = DetailedProfileManager()
########## signal handler
@receiver(user_registered)
def clean_email_id_cache(sender, **kwargs):
from seahub.utils import normalize_cache_key
user = kwargs['user']
key = normalize_cache_key(user.email, EMAIL_ID_CACHE_PREFIX)
cache.set(key, user.id, EMAIL_ID_CACHE_TIMEOUT)
<file_sep>/tests/api/test_repos.py
#coding: UTF-8
"""
Test repos api.
"""
import pytest
import uuid
import unittest
from seaserv import seafile_api
from tests.api.apitestbase import ApiTestBase
from tests.api.urls import (
REPOS_URL, DEFAULT_REPO_URL, VIRTUAL_REPOS_URL, GET_REPO_TOKENS_URL
)
from tests.common.utils import apiurl, urljoin, randstring
from tests.common.common import USERNAME, PASSWORD, SEAFILE_BASE_URL
# TODO: all tests should be run on an encrypted repo
class ReposApiTest(ApiTestBase):
def test_get_default_repo(self):
repo = self.get(DEFAULT_REPO_URL).json()
self.assertIsNotNone(repo['exists'])
def test_create_default_repo(self):
repo = self.post(DEFAULT_REPO_URL).json()
self.assertEqual(len(repo['repo_id']), 36)
self.assertEqual(repo['exists'], True)
def test_list_repos(self):
repos = self.get(REPOS_URL).json()
# self.assertHasLen(repos, 1)
for repo in repos:
self.assertIsNotNone(repo['permission'])
self.assertIsNotNone(repo['encrypted'])
self.assertGreater(repo['mtime'], 0)
self.assertIsNotNone(repo['mtime_relative'])
self.assertIsNotNone(repo['owner'])
self.assertIsNotNone(repo['id'])
self.assertIsNotNone(repo['size'])
self.assertIsNotNone(repo['name'])
self.assertIsNotNone(repo['type'])
# self.assertIsNotNone(repo['virtual']) #allow null for pub-repo
self.assertIsNotNone(repo['desc'])
self.assertIsNotNone(repo['root'])
def test_get_repo_info(self):
with self.get_tmp_repo() as repo:
rinfo = self.get(repo.repo_url).json()
self.assertFalse(rinfo['encrypted'])
self.assertIsNotNone(rinfo['mtime'])
self.assertIsNotNone(rinfo['owner'])
self.assertIsNotNone(rinfo['id'])
self.assertIsNotNone(rinfo['size'])
self.assertIsNotNone(rinfo['name'])
self.assertIsNotNone(rinfo['root'])
self.assertIsNotNone(rinfo['desc'])
self.assertIsNotNone(rinfo['type'])
# elf.assertIsNotNone(rinfo['password_need']) # allow null here
def test_get_repo_owner(self):
with self.get_tmp_repo() as repo:
repo_owner_url = urljoin(repo.repo_url, '/owner/')
# XXX: why only admin can get the owner of a repo?
info = self.admin_get(repo_owner_url).json()
self.assertEqual(info['owner'], self.username)
def test_get_repo_history(self):
with self.get_tmp_repo() as repo:
self.create_file(repo)
self.create_dir(repo)
repo_history_url = urljoin(repo.repo_url, '/history/')
history = self.get(repo_history_url).json()
commits = history['commits']
self.assertHasLen(commits, 3)
for commit in commits:
self.assertIsNotNone(commit['rev_file_size'])
#self.assertIsNotNone(commit['rev_file_id']) #allow null
self.assertIsNotNone(commit['ctime'])
self.assertIsNotNone(commit['creator_name'])
self.assertIsNotNone(commit['creator'])
self.assertIsNotNone(commit['root_id'])
#self.assertIsNotNone(commit['rev_renamed_old_path']) #allow null
#self.assertIsNotNone(commit['parent_id']) #allow null
self.assertIsNotNone(commit['new_merge'])
self.assertIsNotNone(commit['repo_id'])
self.assertIsNotNone(commit['desc'])
self.assertIsNotNone(commit['id'])
self.assertIsNotNone(commit['conflict'])
#self.assertIsNotNone(commit['second_parent_id']) #allow null
def test_create_repo(self):
data = {'name': 'test'}
res = self.post(REPOS_URL, data=data)
repo = res.json()
repo_id = repo['repo_id']
try:
self.assertIsNotNone(repo['encrypted'])
self.assertIsNotNone(repo['enc_version'])
self.assertIsNotNone(repo['repo_id'])
self.assertIsNotNone(repo['magic'])
self.assertIsNotNone(repo['relay_id'])
self.assertIsNotNone(repo['repo_version'])
self.assertIsNotNone(repo['relay_addr'])
self.assertIsNotNone(repo['token'])
self.assertIsNotNone(repo['relay_port'])
self.assertIsNotNone(repo['random_key'])
self.assertIsNotNone(repo['email'])
self.assertIsNotNone(repo['repo_name'])
finally:
self.remove_repo(repo_id)
# Check the repo is really removed
self.get(urljoin(REPOS_URL, repo_id), expected=404)
def test_check_or_create_sub_repo(self):
# TODO: create a sub folder and use it as a sub repo
pass
def test_fetch_repo_download_info(self):
with self.get_tmp_repo() as repo:
download_info_repo_url = urljoin(repo.repo_url, '/download-info/')
info = self.get(download_info_repo_url).json()
self.assertIsNotNone(info['relay_addr'])
self.assertIsNotNone(info['token'])
self.assertIsNotNone(info['repo_id'])
self.assertIsNotNone(info['relay_port'])
self.assertIsNotNone(info['encrypted'])
self.assertIsNotNone(info['repo_name'])
self.assertIsNotNone(info['relay_id'])
self.assertIsNotNone(info['email'])
def test_list_virtual_repos(self):
# TODO: we need to create at least on virtual repo first
vrepos = self.get(VIRTUAL_REPOS_URL).json()['virtual-repos']
for repo in vrepos:
self.assertIsNotNone(repo['virtual_perm'])
#self.assertIsNotNone(repo['store_id'])
self.assertIsNotNone(repo['worktree_invalid'])
self.assertIsNotNone(repo['encrypted'])
self.assertIsNotNone(repo['origin_repo_name'])
self.assertIsNotNone(repo['last_modify'])
self.assertIsNotNone(repo['no_local_history'])
#self.assertIsNotNone(repo['head_branch'])
self.assertIsNotNone(repo['last_sync_time'])
self.assertIsNotNone(repo['id'])
self.assertIsNotNone(repo['size'])
#self.assertIsNotNone(repo['share_permission'])
self.assertIsNotNone(repo['worktree_changed'])
self.assertIsNotNone(repo['worktree_checktime'])
self.assertIsNotNone(repo['origin_path'])
self.assertEqual(repo['is_virtual'], True)
self.assertIsNotNone(repo['origin_repo_id'])
self.assertIsNotNone(repo['version'])
#self.assertIsNotNone(repo['random_key'])
self.assertIsNotNone(repo['is_original_owner'])
#self.assertIsNotNone(repo['shared_email'])
self.assertIsNotNone(repo['enc_version'])
self.assertIsNotNone(repo['head_cmmt_id'])
#self.assertIsNotNone(repo['desc'])
self.assertIsNotNone(repo['index_corrupted'])
#self.assertIsNotNone(repo['magic'])
self.assertIsNotNone(repo['name'])
#self.assertIsNotNone(repo['worktree'])
self.assertIsNotNone(repo['auto_sync'])
#self.assertIsNotNone(repo['relay_id'])
@pytest.mark.xfail
def test_generate_repo_tokens(self):
with self.get_tmp_repo() as ra:
with self.get_tmp_repo() as rb:
fake_repo_id = str(uuid.uuid4())
repo_ids = ','.join([ra.repo_id, rb.repo_id, fake_repo_id])
tokens = self.get(GET_REPO_TOKENS_URL + '?repos=%s' % repo_ids).json()
assert ra.repo_id in tokens
assert rb.repo_id in tokens
assert fake_repo_id not in tokens
for repo_id, token in tokens.iteritems():
self._get_repo_info(token, repo_id)
def test_generate_repo_tokens_reject_invalid_params(self):
self.get(GET_REPO_TOKENS_URL, expected=400)
self.get(GET_REPO_TOKENS_URL + '?repos=badxxx', expected=400)
def _get_repo_info(self, sync_token, repo_id, **kwargs):
headers = {
'Seafile-Repo-Token': sync_token
}
url = urljoin(SEAFILE_BASE_URL,
'repo/%s/permission-check/?op=upload' % repo_id)
self.get(url, use_token=False, headers=headers, **kwargs)
# @pytest.mark.xfail
def test_create_encrypted_repo(self):
"""Test create an encrypted repo with the secure keys generated on client
side.
"""
repo_id = str(uuid.uuid4())
password = <PASSWORD>)
enc_version = 2
enc_info = seafile_api.generate_magic_and_random_key(enc_version, repo_id, password)
data = {
'name': 'enc-test',
'repo_id': repo_id,
'enc_version': enc_version,
'magic': enc_info.magic,
'random_key': enc_info.random_key,
}
res = self.post(REPOS_URL, data=data)
repo = res.json()
assert repo['repo_id'] == repo_id
assert repo['encrypted']
assert repo['magic'] == enc_info.magic
assert repo['random_key'] == enc_info.random_key
# validate the password on server
set_password_url = apiurl('/api2/repos/{}/'.format(repo['repo_id']))
self.post(set_password_url, data={'password': <PASSWORD>})
# do some file operation
self.create_file(repo['repo_id'])
<file_sep>/seahub/group/templates/group/msg_js.html
{% load i18n %}
{% if request.user.is_authenticated %}{# 'reply' is enabled only after login#}
$('.msg-main, .reply').hover(
function(){
$(this).find('.op').removeClass('vh');
},
function(){
$(this).find('.op').addClass('vh');
}
);
$('.msg .op').hover(
function() {
$(this).css({'text-decoration':'underline'});
},
function() {
$(this).css({'text-decoration':'none'});
}
);
{% endif %}
$('.replies-op').hover(
function() {
$('.unfold-replies, .fold-replies', $(this)).css({'text-decoration':'underline'});
},
function() {
$('.unfold-replies, .fold-replies', $(this)).css({'text-decoration':'none'});
}
).click(function() {
var op = $(this),
uf_r = $('.unfold-replies', op),
f_r = $('.fold-replies', op),
r_list = op.parent().find('.reply-list'),
loading = $('.replies-loading-icon', op);
loading.css({'left': uf_r.outerWidth() - 7});
if (op.attr('data-rstatus') == 'hide') {
uf_r.addClass('unfold-replies-nobg');
loading.show();
$.ajax({
url: '{{SITE_ROOT}}group/reply/' + op.parents('.msg').attr('data-id') + '/',
dataType: 'json',
cache: true,
success: function(data) {
loading.hide();
uf_r.removeClass('unfold-replies-nobg');
r_list.html(data['html']);
uf_r.addClass('hide');
f_r.removeClass('hide')
op.attr('data-rstatus', 'show');
{% if request.user.is_authenticated %}
r_list.children().hover(
function() {
$(this).find('.op').removeClass('vh');
},
function(){
$(this).find('.op').addClass('vh');
}
);
r_list.find('.reply-at').hover(
function() {
$(this).css({'text-decoration':'underline'});
},
function() {
$(this).css({'text-decoration':'none'});
}
).click(replyAt);
{% endif %}
}
});
} else {
f_r.addClass('hide');
uf_r.removeClass('hide');
r_list.children(':lt(' + (parseInt(uf_r.html()) -3) + ')').each(function() {
$(this).remove();
});
op.attr('data-rstatus', 'hide');
}
});
{% if request.user.is_authenticated %}
$('.reply-input').focus(function() {
$(this).height(50);
$(this).parent().find('.reply-submit, .reply-cancel').removeClass('hide');
});
$('.reply-cancel').click(function() {
var p = $(this).parent();
p.find('.reply-submit, .reply-cancel, .error').addClass('hide');
p.find('.reply-input').val('').height(20);
});
function replyAt() {
var r = $(this).parents('.msg-op');
var r_input = r.find('.reply-input');
r_input.height(50).val('@' + $(this).attr('data') + ' ');
r.find('.reply-submit, .reply-cancel').removeClass('hide');
setCaretPos(r_input[0], r_input.val().length);
r_input.focus();
}
$('.reply-at').click(replyAt);
$('.reply-form').submit(function() {
var form = $(this),
r_input = form.find('.reply-input'),
r = $.trim(r_input.val()),
err = form.find('.error');
if (!r || r.length > 2048) {
err.removeClass('hide');
return false;
}
err.addClass('hide');
var sm = $(this).find('.reply-submit');
disable(sm);
var msg_op = form.parent(),
r_op = msg_op.find('.replies-op'),
r_status = r_op.attr('data-rstatus');
$.ajax({
type: "POST",
url: '{{SITE_ROOT}}group/reply/' + form.parents('.msg').attr('data-id') + '/?r_status=' + e(r_status),
dataType: 'json',
cache: false,
beforeSend: prepareCSRFToken,
data: { "message": r },
success: function(data) {
var r_list = msg_op.find('.reply-list'),
r_cnt = msg_op.find('.unfold-replies');
r_list.html(data['html']).removeClass('hide');
if (data['r_num'] > 3) {
r_cnt.html(r_cnt.html().replace(/\d+/, data['r_num']));
r_op.removeClass('hide');
}
enable(sm);
r_input.val('').height(20);
form.find('.reply-submit, .reply-cancel').addClass('hide');
r_list.children().hover(
function(){
$(this).find('.op').removeClass('vh');
},
function(){
$(this).find('.op').addClass('vh');
}
);
r_list.find('.reply-at').hover(
function() {
$(this).css({'text-decoration':'underline'});
},
function() {
$(this).css({'text-decoration':'none'});
}
).click(replyAt);
},
error:function(jqXHR, textStatus, errorThrown) {
if (!jqXHR.responseText) {
err.html("{% trans "Failed. Please check the network." %}").removeClass('hide');
} else {
err.html("{% trans "Failed to post reply." %}").removeClass('hide');
}
enable(sm);
}
});
return false;
});
{% endif %}
<file_sep>/seahub/utils/file_types.py
TEXT = 'Text'
IMAGE = 'Image'
GIMP = 'GIMP Document'
DOCUMENT = 'Document'
SVG = 'SVG'
PDF = 'PDF'
OPENDOCUMENT = 'OpenDocument'
MARKDOWN = 'Markdown'
VIDEO = 'Video'
AUDIO = 'Audio'
SPREADSHEET = 'SpreadSheet'
<file_sep>/eyeos/auth.py
import json
import httplib
import logging
import subprocess
from seahub.base.accounts import AuthBackend as SeahubAuthBackend
import seahub.base.accounts as accounts
logger = logging.getLogger(__name__)
class EyeosCardAuthBackend(object):
def get_user(self, username):
try:
seahubAuth = SeahubAuthBackend()
user = seahubAuth.get_user(username)
except accounts.User.DoesNotExist:
logger.debug('user does not exist')
return False
except Exception as e:
logger.debug('got exception while authenticating with EyeosCardAuthBackend')
logger.debug(e)
return False
return user
def authenticate(self, username=None, password=<PASSWORD>):
# username is the regular eyeos user, password is <PASSWORD>
# {"card":"a-user-card", "signature":"a-user-signature"}, so we need to split the
# card/signature and validate it
try:
auth = json.loads(password)
card_username = self._extract_username_from_card(auth['card'])
card_domain = self._extract_domain_from_card(auth['card'])
logger.debug('extracted username %s from card' % card_username)
if card_username != username:
logger.debug('Used username "%s" differs from username in the card "%s"' % (username, card_username))
return None
except (ValueError, KeyError) as e:
logger.debug('got exception trying to authenticate with EyeosCardAuthBackend. Skip it.')
# not json, do not use this AuthBackend
return None
if self._validate_card(card=auth['card'], signature=auth['signature']):
user = self.get_user(username + '@' + card_domain)
if user:
return user
else:
return None
else:
return None
def _extract_username_from_card(self, card):
card_object = json.loads(card)
return card_object['username']
def _extract_domain_from_card(self, card):
card_object = json.loads(card)
return card_object['domain']
def _validate_card(self, card, signature):
args = {'c': json.loads(card), 's': signature}
process = subprocess.Popen(['node', '/opt/auth/index.js', json.dumps(args)], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Uncomment these lines to activate logging
# stdout, stderr = process.communicate()
# with open("/tmp/card_validation.log", "a") as logfile:
# logfile.write("#STDOUT: " + str(stdout) + "\n#STDERR: " + str(stderr) + '\n\n')
ret_code = process.wait()
if ret_code == 0:
return True
else:
return False
<file_sep>/seahub/profile/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('seahub.profile.views',
# url(r'^list_user/$', 'list_userids', name="list_userids"),
url(r'^$', 'edit_profile', name="edit_profile"),
url(r'^(?P<user>[^/]+)/get/$', 'get_user_profile', name="get_user_profile"),
url(r'^delete/$', 'delete_user_account', name="delete_user_account"),
url(r'^default-repo/$', 'default_repo', name="default_repo"),
url(r'^(?P<username>[^/]*)/$', 'user_profile', name="user_profile"),
# url(r'^logout/$', 'logout_relay', name="logout_relay"),
)
<file_sep>/seahub/views/ajax.py
# -*- coding: utf-8 -*-
import os
import stat
import logging
import json
import posixpath
from django.core.urlresolvers import reverse
from django.http import HttpResponse, Http404, HttpResponseBadRequest
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.http import urlquote
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib import messages
from django.template.defaultfilters import filesizeformat
import seaserv
from seaserv import seafile_api, is_passwd_set, \
get_related_users_by_repo, get_related_users_by_org_repo, \
seafserv_threaded_rpc, ccnet_threaded_rpc, \
edit_repo, set_repo_history_limit
from pysearpc import SearpcError
from seahub.auth.decorators import login_required_ajax
from seahub.base.decorators import require_POST
from seahub.contacts.models import Contact
from seahub.forms import RepoNewDirentForm, RepoRenameDirentForm, \
RepoCreateForm, SharedRepoCreateForm, RepoSettingForm
from seahub.options.models import UserOptions, CryptoOptionNotSetError
from seahub.notifications.models import UserNotification
from seahub.notifications.views import add_notice_from_info
from seahub.message.models import UserMessage
from seahub.share.models import UploadLinkShare
from seahub.group.models import PublicGroup
from seahub.signals import upload_file_successful, repo_created, repo_deleted
from seahub.views import validate_owner, check_repo_access_permission, \
get_unencry_rw_repos_by_user, get_system_default_repo_id, get_diff, group_events_data, \
get_owned_repo_list, check_folder_permission, is_registered_user
from seahub.views.modules import get_enabled_mods_by_group, \
get_available_mods_by_group, enable_mod_for_group, \
disable_mod_for_group, MOD_GROUP_WIKI, MOD_PERSONAL_WIKI, \
enable_mod_for_user, disable_mod_for_user
from seahub.group.views import is_group_staff
import seahub.settings as settings
from seahub.settings import ENABLE_THUMBNAIL, THUMBNAIL_ROOT, \
THUMBNAIL_DEFAULT_SIZE, ENABLE_SUB_LIBRARY, \
ENABLE_FOLDER_PERM, SHOW_TRAFFIC, MEDIA_URL
from constance import config
from seahub.utils import check_filename_with_rename, EMPTY_SHA1, \
gen_block_get_url, TRAFFIC_STATS_ENABLED, get_user_traffic_stat,\
new_merge_with_no_conflict, get_commit_before_new_merge, \
get_repo_last_modify, gen_file_upload_url, is_org_context, \
get_org_user_events, get_user_events, get_file_type_and_ext, \
is_valid_username, send_perm_audit_msg, get_origin_repo_info, is_pro_version
from seahub.utils.repo import get_sub_repo_abbrev_origin_path
from seahub.utils.star import star_file, unstar_file, get_dir_starred_files
from seahub.base.accounts import User
from seahub.thumbnail.utils import get_thumbnail_src
from seahub.utils.file_types import IMAGE, GIMP
from seahub.base.templatetags.seahub_tags import translate_seahub_time, \
file_icon_filter, email2nickname, tsstr_sec
from seahub.avatar.templatetags.group_avatar_tags import grp_avatar
# Get an instance of a logger
logger = logging.getLogger(__name__)
########## Seafile API Wrapper
def get_repo(repo_id):
return seafile_api.get_repo(repo_id)
def get_commit(repo_id, repo_version, commit_id):
return seaserv.get_commit(repo_id, repo_version, commit_id)
def get_group(gid):
return seaserv.get_group(gid)
def is_group_user(gid, username):
return seaserv.is_group_user(gid, username)
########## repo related
@login_required_ajax
def get_dirents(request, repo_id):
"""
Get dirents in a dir for file tree
"""
content_type = 'application/json; charset=utf-8'
# permission checking
user_perm = check_repo_access_permission(repo_id, request.user)
if user_perm is None:
err_msg = _(u"You don't have permission to access the library.")
return HttpResponse(json.dumps({"err_msg": err_msg}), status=403,
content_type=content_type)
path = request.GET.get('path', '')
dir_only = request.GET.get('dir_only', False)
all_dir = request.GET.get('all_dir', False)
if not path:
err_msg = _(u"No path.")
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
# get dirents for every path element
if all_dir:
all_dirents = []
path_eles = path.split('/')[:-1]
for i, x in enumerate(path_eles):
ele_path = '/'.join(path_eles[:i+1]) + '/'
try:
ele_path_dirents = seafile_api.list_dir_by_path(repo_id, ele_path.encode('utf-8'))
except SearpcError, e:
ele_path_dirents = []
ds = []
for d in ele_path_dirents:
if stat.S_ISDIR(d.mode):
ds.append(d.obj_name)
ds.sort(lambda x, y : cmp(x.lower(), y.lower()))
all_dirents.append(ds)
return HttpResponse(json.dumps(all_dirents), content_type=content_type)
# get dirents in path
try:
dirents = seafile_api.list_dir_by_path(repo_id, path.encode('utf-8'))
except SearpcError, e:
return HttpResponse(json.dumps({"error": e.msg}), status=500,
content_type=content_type)
d_list = []
f_list = []
for dirent in dirents:
if stat.S_ISDIR(dirent.mode):
dirent.has_subdir = False
if dir_only:
dirent_path = posixpath.join(path, dirent.obj_name)
try:
dirent_dirents = seafile_api.list_dir_by_path(repo_id, dirent_path.encode('utf-8'))
except SearpcError, e:
dirent_dirents = []
for dirent_dirent in dirent_dirents:
if stat.S_ISDIR(dirent_dirent.props.mode):
dirent.has_subdir = True
break
subdir = {
'name': dirent.obj_name,
'id': dirent.obj_id,
'type': 'dir',
'has_subdir': dirent.has_subdir, # to decide node 'state' ('closed' or not) in jstree
}
d_list.append(subdir)
else:
if not dir_only:
f = {
'id': dirent.obj_id,
'name': dirent.obj_name,
'type': 'file',
}
f_list.append(f)
d_list.sort(lambda x, y : cmp(x['name'].lower(), y['name'].lower()))
f_list.sort(lambda x, y : cmp(x['name'].lower(), y['name'].lower()))
return HttpResponse(json.dumps(d_list + f_list), content_type=content_type)
@login_required_ajax
def get_unenc_group_repos(request, group_id):
'''
Get unenc repos in a group.
'''
content_type = 'application/json; charset=utf-8'
group_id_int = int(group_id)
group = get_group(group_id_int)
if not group:
err_msg = _(u"The group doesn't exist")
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
joined = is_group_user(group_id_int, request.user.username)
if not joined and not request.user.is_staff:
err_msg = _(u"Permission denied")
return HttpResponse(json.dumps({"error": err_msg}), status=403,
content_type=content_type)
repo_list = []
if is_org_context(request):
org_id = request.user.org.org_id
repos = seafile_api.get_org_group_repos(org_id, group_id_int)
for repo in repos:
if not repo.encrypted:
repo_list.append({"name": repo.repo_name, "id": repo.repo_id})
else:
repos = seafile_api.get_group_repo_list(group_id_int)
for repo in repos:
if not repo.encrypted:
repo_list.append({"name": repo.name, "id": repo.id})
repo_list.sort(lambda x, y : cmp(x['name'].lower(), y['name'].lower()))
return HttpResponse(json.dumps(repo_list), content_type=content_type)
@login_required_ajax
def get_my_unenc_repos(request):
"""Get my owned and unencrypted repos.
"""
content_type = 'application/json; charset=utf-8'
repos = get_owned_repo_list(request)
repo_list = []
for repo in repos:
if repo.encrypted or repo.is_virtual:
continue
repo_list.append({"name": repo.name, "id": repo.id})
repo_list.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))
return HttpResponse(json.dumps(repo_list), content_type=content_type)
@login_required_ajax
def unenc_rw_repos(request):
"""Get a user's unencrypt repos that he/she can read-write.
Arguments:
- `request`:
"""
content_type = 'application/json; charset=utf-8'
acc_repos = get_unencry_rw_repos_by_user(request)
repo_list = []
acc_repos = filter(lambda r: not r.is_virtual, acc_repos)
for repo in acc_repos:
repo_list.append({"name": repo.name, "id": repo.id})
repo_list.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))
return HttpResponse(json.dumps(repo_list), content_type=content_type)
@login_required_ajax
def list_lib_dir(request, repo_id):
'''
New ajax API for list library directory
'''
content_type = 'application/json; charset=utf-8'
result = {}
repo = get_repo(repo_id)
if not repo:
err_msg = _(u'Library does not exist.')
return HttpResponse(json.dumps({'error': err_msg}),
status=400, content_type=content_type)
username = request.user.username
path = request.GET.get('p', '/')
if path[-1] != '/':
path = path + '/'
# perm for current dir
user_perm = check_folder_permission(request, repo.id, path)
if user_perm is None:
err_msg = _(u'Permission denied.')
return HttpResponse(json.dumps({'error': err_msg}),
status=403, content_type=content_type)
if repo.encrypted \
and not seafile_api.is_password_set(repo.id, username):
err_msg = _(u'Library is encrypted.')
return HttpResponse(json.dumps({'error': err_msg, 'lib_need_decrypt': True}),
status=403, content_type=content_type)
head_commit = get_commit(repo.id, repo.version, repo.head_cmmt_id)
if not head_commit:
err_msg = _(u'Error: no head commit id')
return HttpResponse(json.dumps({'error': err_msg}),
status=500, content_type=content_type)
offset = int(request.GET.get('start', 0))
limit = 100
dir_list = []
file_list = []
dirent_more = False
try:
dir_id = seafile_api.get_dir_id_by_path(repo.id, path)
except SearpcError as e:
logger.error(e)
err_msg = 'Internal Server Error'
return HttpResponse(json.dumps({'error': err_msg}),
status=500, content_type=content_type)
if not dir_id:
err_msg = 'Folder not found.'
return HttpResponse(json.dumps({'error': err_msg}),
status=404, content_type=content_type)
dirs = seafserv_threaded_rpc.list_dir_with_perm(repo_id, path, dir_id, username, offset, limit)
starred_files = get_dir_starred_files(username, repo_id, path)
for dirent in dirs:
dirent.last_modified = dirent.mtime
if stat.S_ISDIR(dirent.mode):
dpath = posixpath.join(path, dirent.obj_name)
if dpath[-1] != '/':
dpath += '/'
dir_list.append(dirent)
else:
if repo.version == 0:
file_size = seafile_api.get_file_size(repo.store_id, repo.version, dirent.obj_id)
else:
file_size = dirent.size
dirent.file_size = file_size if file_size else 0
dirent.starred = False
fpath = posixpath.join(path, dirent.obj_name)
if fpath in starred_files:
dirent.starred = True
file_list.append(dirent)
more_start = None
if limit == len(dirs):
dirent_more = True
more_start = offset + 100
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
result["is_repo_owner"] = True if repo_owner == username else False
result["is_virtual"] = repo.is_virtual
result["repo_name"] = repo.name
result["user_perm"] = user_perm
result["encrypted"] = repo.encrypted
result["dirent_more"] = dirent_more
result["more_start"] = more_start
dirent_list = []
for d in dir_list:
d_ = {}
d_['is_dir'] = True
d_['obj_name'] = d.obj_name
d_['last_modified'] = d.last_modified
d_['last_update'] = translate_seahub_time(d.last_modified)
d_['p_dpath'] = posixpath.join(path, d.obj_name)
d_['perm'] = d.permission # perm for sub dir in current dir
dirent_list.append(d_)
size = THUMBNAIL_DEFAULT_SIZE
for f in file_list:
f_ = {}
f_['is_file'] = True
f_['file_icon'] = file_icon_filter(f.obj_name)
f_['obj_name'] = f.obj_name
f_['last_modified'] = f.last_modified
f_['last_update'] = translate_seahub_time(f.last_modified)
f_['starred'] = f.starred
f_['file_size'] = filesizeformat(f.file_size)
f_['obj_id'] = f.obj_id
f_['perm'] = f.permission # perm for file in current dir
file_type, file_ext = get_file_type_and_ext(f.obj_name)
if file_type == GIMP or file_type == IMAGE:
f_['is_gimp_editable'] = True
if file_type == IMAGE:
f_['is_img'] = True
if not repo.encrypted and ENABLE_THUMBNAIL and \
os.path.exists(os.path.join(THUMBNAIL_ROOT, str(size), f.obj_id)):
file_path = posixpath.join(path, f.obj_name)
src = get_thumbnail_src(repo_id, size, file_path)
f_['encoded_thumbnail_src'] = urlquote(src)
if is_pro_version():
f_['is_locked'] = True if f.is_locked else False
f_['lock_owner'] = f.lock_owner
f_['lock_owner_name'] = email2nickname(f.lock_owner)
if username == f.lock_owner:
f_['locked_by_me'] = True
else:
f_['locked_by_me'] = False
dirent_list.append(f_)
result["dirent_list"] = dirent_list
return HttpResponse(json.dumps(result), content_type=content_type)
def new_dirent_common(func):
"""Decorator for common logic in creating directory and file.
"""
def _decorated(request, repo_id, *args, **kwargs):
if request.method != 'POST':
raise Http404
result = {}
content_type = 'application/json; charset=utf-8'
repo = get_repo(repo_id)
if not repo:
result['error'] = _(u'Library does not exist.')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# arguments checking
parent_dir = request.GET.get('parent_dir', None)
if not parent_dir:
result['error'] = _('Argument missing')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# permission checking
username = request.user.username
if check_folder_permission(request, repo.id, parent_dir) != 'rw':
result['error'] = _('Permission denied')
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
# form validation
form = RepoNewDirentForm(request.POST)
if form.is_valid():
dirent_name = form.cleaned_data["dirent_name"]
else:
result['error'] = str(form.errors.values()[0])
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# rename duplicate name
dirent_name = check_filename_with_rename(repo.id, parent_dir,
dirent_name)
return func(repo.id, parent_dir, dirent_name, username)
return _decorated
@login_required_ajax
@new_dirent_common
def new_dir(repo_id, parent_dir, dirent_name, username):
"""
Create a new dir with ajax.
"""
result = {}
content_type = 'application/json; charset=utf-8'
# create new dirent
try:
seafile_api.post_dir(repo_id, parent_dir, dirent_name, username)
except SearpcError, e:
result['error'] = str(e)
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
return HttpResponse(json.dumps({'success': True, 'name': dirent_name}),
content_type=content_type)
@login_required_ajax
@new_dirent_common
def new_file(repo_id, parent_dir, dirent_name, username):
"""
Create a new file with ajax.
"""
result = {}
content_type = 'application/json; charset=utf-8'
# create new dirent
try:
seafile_api.post_empty_file(repo_id, parent_dir, dirent_name, username)
except SearpcError, e:
result['error'] = str(e)
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
return HttpResponse(json.dumps({'success': True, 'name': dirent_name}),
content_type=content_type)
@login_required_ajax
def rename_dirent(request, repo_id):
"""
Rename a file/dir in a repo, with ajax
"""
if request.method != 'POST':
raise Http404
result = {}
username = request.user.username
content_type = 'application/json; charset=utf-8'
repo = get_repo(repo_id)
if not repo:
result['error'] = _(u'Library does not exist.')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# argument checking
parent_dir = request.GET.get('parent_dir', None)
if not parent_dir:
result['error'] = _('Argument missing')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# form validation
form = RepoRenameDirentForm(request.POST)
if form.is_valid():
oldname = form.cleaned_data["oldname"]
newname = form.cleaned_data["newname"]
else:
result['error'] = str(form.errors.values()[0])
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
full_path = posixpath.join(parent_dir, oldname)
if seafile_api.get_dir_id_by_path(repo.id, full_path) is not None:
# when dirent is a dir, check current dir perm
if check_folder_permission(request, repo.id, full_path) != 'rw':
err_msg = _('Permission denied')
return HttpResponse(json.dumps({'error': err_msg}), status=403,
content_type=content_type)
if seafile_api.get_file_id_by_path(repo.id, full_path) is not None:
# when dirent is a file, check parent dir perm
if check_folder_permission(request, repo.id, parent_dir) != 'rw':
err_msg = _('Permission denied')
return HttpResponse(json.dumps({'error': err_msg}), status=403,
content_type=content_type)
if newname == oldname:
return HttpResponse(json.dumps({'success': True}),
content_type=content_type)
# rename duplicate name
newname = check_filename_with_rename(repo_id, parent_dir, newname)
# rename file/dir
try:
seafile_api.rename_file(repo_id, parent_dir, oldname, newname, username)
except SearpcError, e:
result['error'] = str(e)
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
return HttpResponse(json.dumps({'success': True, 'newname': newname}),
content_type=content_type)
@login_required_ajax
@require_POST
def delete_dirent(request, repo_id):
"""
Delete a file/dir with ajax.
"""
content_type = 'application/json; charset=utf-8'
repo = get_repo(repo_id)
if not repo:
err_msg = _(u'Library does not exist.')
return HttpResponse(json.dumps({'error': err_msg}),
status=400, content_type=content_type)
# argument checking
parent_dir = request.GET.get("parent_dir", None)
dirent_name = request.GET.get("name", None)
if not (parent_dir and dirent_name):
err_msg = _(u'Argument missing.')
return HttpResponse(json.dumps({'error': err_msg}),
status=400, content_type=content_type)
full_path = posixpath.join(parent_dir, dirent_name)
username = request.user.username
if seafile_api.get_dir_id_by_path(repo.id, full_path) is not None:
# when dirent is a dir, check current dir perm
if check_folder_permission(request, repo.id, full_path) != 'rw':
err_msg = _('Permission denied')
return HttpResponse(json.dumps({'error': err_msg}), status=403,
content_type=content_type)
if seafile_api.get_file_id_by_path(repo.id, full_path) is not None:
# when dirent is a file, check parent dir perm
if check_folder_permission(request, repo.id, parent_dir) != 'rw':
err_msg = _('Permission denied')
return HttpResponse(json.dumps({'error': err_msg}), status=403,
content_type=content_type)
# delete file/dir
try:
seafile_api.del_file(repo_id, parent_dir, dirent_name, username)
return HttpResponse(json.dumps({'success': True}),
content_type=content_type)
except SearpcError, e:
logger.error(e)
err_msg = _(u'Internal error. Failed to delete %s.') % escape(dirent_name)
return HttpResponse(json.dumps({'error': err_msg}),
status=500, content_type=content_type)
@login_required_ajax
@require_POST
def delete_dirents(request, repo_id):
"""
Delete multi files/dirs with ajax.
"""
content_type = 'application/json; charset=utf-8'
repo = get_repo(repo_id)
if not repo:
err_msg = _(u'Library does not exist.')
return HttpResponse(json.dumps({'error': err_msg}),
status=400, content_type=content_type)
# argument checking
parent_dir = request.GET.get("parent_dir")
dirents_names = request.POST.getlist('dirents_names')
if not (parent_dir and dirents_names):
err_msg = _(u'Argument missing.')
return HttpResponse(json.dumps({'error': err_msg}),
status=400, content_type=content_type)
# permission checking
username = request.user.username
deleted = []
undeleted = []
for dirent_name in dirents_names:
full_path = posixpath.join(parent_dir, dirent_name)
if check_folder_permission(request, repo.id, full_path) != 'rw':
undeleted.append(dirent_name)
continue
try:
seafile_api.del_file(repo_id, parent_dir, dirent_name, username)
deleted.append(dirent_name)
except SearpcError, e:
logger.error(e)
undeleted.append(dirent_name)
return HttpResponse(json.dumps({'deleted': deleted, 'undeleted': undeleted}),
content_type=content_type)
def copy_move_common():
"""Decorator for common logic in copying/moving dir/file.
"""
def _method_wrapper(view_method):
def _arguments_wrapper(request, repo_id, *args, **kwargs):
if request.method != 'POST':
raise Http404
result = {}
content_type = 'application/json; charset=utf-8'
repo = get_repo(repo_id)
if not repo:
result['error'] = _(u'Library does not exist.')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# arguments validation
path = request.GET.get('path')
obj_name = request.GET.get('obj_name')
dst_repo_id = request.POST.get('dst_repo')
dst_path = request.POST.get('dst_path')
if not (path and obj_name and dst_repo_id and dst_path):
result['error'] = _('Argument missing')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# check file path
if len(dst_path + obj_name) > settings.MAX_PATH:
result['error'] = _('Destination path is too long.')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# return error when dst is the same as src
if repo_id == dst_repo_id and path == dst_path:
result['error'] = _('Invalid destination path')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# check whether user has write permission to dest repo
if check_folder_permission(request, dst_repo_id, dst_path) != 'rw':
result['error'] = _('Permission denied')
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
# Leave src folder/file permission checking to corresponding
# views.
# For 'move', check has read-write perm to src folder;
# For 'cp', check has read perm to src folder.
return view_method(request, repo_id, path, dst_repo_id, dst_path,
obj_name)
return _arguments_wrapper
return _method_wrapper
@login_required_ajax
@copy_move_common()
def mv_file(request, src_repo_id, src_path, dst_repo_id, dst_path, obj_name):
result = {}
content_type = 'application/json; charset=utf-8'
username = request.user.username
# check parent dir perm
if check_folder_permission(request, src_repo_id, src_path) != 'rw':
result['error'] = _('Permission denied')
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
new_obj_name = check_filename_with_rename(dst_repo_id, dst_path, obj_name)
try:
res = seafile_api.move_file(src_repo_id, src_path, obj_name,
dst_repo_id, dst_path, new_obj_name,
username, need_progress=1)
except SearpcError as e:
logger.error(e)
res = None
# res can be None or an object
if not res:
result['error'] = _(u'Internal server error')
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
result['success'] = True
msg = _(u'Successfully moved %(name)s') % {"name": escape(obj_name)}
result['msg'] = msg
if res.background:
result['task_id'] = res.task_id
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
@copy_move_common()
def cp_file(request, src_repo_id, src_path, dst_repo_id, dst_path, obj_name):
result = {}
content_type = 'application/json; charset=utf-8'
username = request.user.username
# check parent dir perm
if not check_folder_permission(request, src_repo_id, src_path):
result['error'] = _('Permission denied')
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
new_obj_name = check_filename_with_rename(dst_repo_id, dst_path, obj_name)
try:
res = seafile_api.copy_file(src_repo_id, src_path, obj_name,
dst_repo_id, dst_path, new_obj_name,
username, need_progress=1)
except SearpcError as e:
res = None
if not res:
result['error'] = _(u'Internal server error')
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
result['success'] = True
msg = _(u'Successfully copied %(name)s') % {"name": escape(obj_name)}
result['msg'] = msg
if res.background:
result['task_id'] = res.task_id
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
@copy_move_common()
def mv_dir(request, src_repo_id, src_path, dst_repo_id, dst_path, obj_name):
result = {}
content_type = 'application/json; charset=utf-8'
username = request.user.username
src_dir = posixpath.join(src_path, obj_name)
if dst_path.startswith(src_dir + '/'):
error_msg = _(u'Can not move directory %(src)s to its subdirectory %(des)s') \
% {'src': escape(src_dir), 'des': escape(dst_path)}
result['error'] = error_msg
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
# check dir perm
if check_folder_permission(request, src_repo_id, src_dir) != 'rw':
result['error'] = _('Permission denied')
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
new_obj_name = check_filename_with_rename(dst_repo_id, dst_path, obj_name)
try:
res = seafile_api.move_file(src_repo_id, src_path, obj_name,
dst_repo_id, dst_path, new_obj_name,
username, need_progress=1)
except SearpcError, e:
res = None
# res can be None or an object
if not res:
result['error'] = _(u'Internal server error')
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
result['success'] = True
msg = _(u'Successfully moved %(name)s') % {"name": escape(obj_name)}
result['msg'] = msg
if res.background:
result['task_id'] = res.task_id
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
@copy_move_common()
def cp_dir(request, src_repo_id, src_path, dst_repo_id, dst_path, obj_name):
result = {}
content_type = 'application/json; charset=utf-8'
username = request.user.username
# check src dir perm
if not check_folder_permission(request, src_repo_id, src_path):
result['error'] = _('Permission denied')
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
src_dir = posixpath.join(src_path, obj_name)
if dst_path.startswith(src_dir):
error_msg = _(u'Can not copy directory %(src)s to its subdirectory %(des)s') \
% {'src': escape(src_dir), 'des': escape(dst_path)}
result['error'] = error_msg
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
new_obj_name = check_filename_with_rename(dst_repo_id, dst_path, obj_name)
try:
res = seafile_api.copy_file(src_repo_id, src_path, obj_name,
dst_repo_id, dst_path, new_obj_name,
username, need_progress=1)
except SearpcError, e:
res = None
# res can be None or an object
if not res:
result['error'] = _(u'Internal server error')
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
result['success'] = True
msg = _(u'Successfully copied %(name)s') % {"name": escape(obj_name)}
result['msg'] = msg
if res.background:
result['task_id'] = res.task_id
return HttpResponse(json.dumps(result), content_type=content_type)
def dirents_copy_move_common():
"""
Decorator for common logic in copying/moving dirs/files in batch.
"""
def _method_wrapper(view_method):
def _arguments_wrapper(request, repo_id, *args, **kwargs):
if request.method != 'POST':
raise Http404
result = {}
content_type = 'application/json; charset=utf-8'
repo = get_repo(repo_id)
if not repo:
result['error'] = _(u'Library does not exist.')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# arguments validation
parent_dir = request.GET.get('parent_dir')
obj_file_names = request.POST.getlist('file_names')
obj_dir_names = request.POST.getlist('dir_names')
dst_repo_id = request.POST.get('dst_repo')
dst_path = request.POST.get('dst_path')
if not (parent_dir and dst_repo_id and dst_path) and \
not (obj_file_names or obj_dir_names):
result['error'] = _('Argument missing')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# check file path
for obj_name in obj_file_names + obj_dir_names:
if len(dst_path+obj_name) > settings.MAX_PATH:
result['error'] = _('Destination path is too long for %s.') % escape(obj_name)
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# when dst is the same as src
if repo_id == dst_repo_id and parent_dir == dst_path:
result['error'] = _('Invalid destination path')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# check whether user has write permission to dest repo
if check_folder_permission(request, dst_repo_id, dst_path) != 'rw':
result['error'] = _('Permission denied')
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
# Leave src folder/file permission checking to corresponding
# views, only need to check folder permission when perform 'move'
# operation, 1), if move file, check parent dir perm, 2), if move
# folder, check that folder perm.
return view_method(request, repo_id, parent_dir, dst_repo_id,
dst_path, obj_file_names, obj_dir_names)
return _arguments_wrapper
return _method_wrapper
@login_required_ajax
@dirents_copy_move_common()
def mv_dirents(request, src_repo_id, src_path, dst_repo_id, dst_path,
obj_file_names, obj_dir_names):
result = {}
content_type = 'application/json; charset=utf-8'
username = request.user.username
failed = []
allowed_files = []
allowed_dirs = []
# check parent dir perm for files
if check_folder_permission(request, src_repo_id, src_path) != 'rw':
allowed_files = []
failed += obj_file_names
else:
allowed_files = obj_file_names
for obj_name in obj_dir_names:
src_dir = posixpath.join(src_path, obj_name)
if dst_path.startswith(src_dir + '/'):
error_msg = _(u'Can not move directory %(src)s to its subdirectory %(des)s') \
% {'src': escape(src_dir), 'des': escape(dst_path)}
result['error'] = error_msg
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
# check every folder perm
if check_folder_permission(request, src_repo_id, src_dir) != 'rw':
failed.append(obj_name)
else:
allowed_dirs.append(obj_name)
success = []
url = None
for obj_name in allowed_files + allowed_dirs:
new_obj_name = check_filename_with_rename(dst_repo_id, dst_path, obj_name)
try:
res = seafile_api.move_file(src_repo_id, src_path, obj_name,
dst_repo_id, dst_path, new_obj_name, username, need_progress=1)
except SearpcError as e:
logger.error(e)
res = None
if not res:
failed.append(obj_name)
else:
success.append(obj_name)
if len(success) > 0:
url = reverse("view_common_lib_dir", args=[dst_repo_id, urlquote(dst_path).strip('/')])
result = {'success': success, 'failed': failed, 'url': url}
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
@dirents_copy_move_common()
def cp_dirents(request, src_repo_id, src_path, dst_repo_id, dst_path, obj_file_names, obj_dir_names):
result = {}
content_type = 'application/json; charset=utf-8'
username = request.user.username
if check_folder_permission(request, src_repo_id, src_path) is None:
error_msg = _(u'You do not have permission to copy files/folders in this directory')
result['error'] = error_msg
return HttpResponse(json.dumps(result), status=403, content_type=content_type)
for obj_name in obj_dir_names:
src_dir = posixpath.join(src_path, obj_name)
if dst_path.startswith(src_dir):
error_msg = _(u'Can not copy directory %(src)s to its subdirectory %(des)s') \
% {'src': escape(src_dir), 'des': escape(dst_path)}
result['error'] = error_msg
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
failed = []
success = []
url = None
for obj_name in obj_file_names + obj_dir_names:
new_obj_name = check_filename_with_rename(dst_repo_id, dst_path, obj_name)
try:
res = seafile_api.copy_file(src_repo_id, src_path, obj_name,
dst_repo_id, dst_path, new_obj_name, username, need_progress=1)
except SearpcError as e:
logger.error(e)
res = None
if not res:
failed.append(obj_name)
else:
success.append(obj_name)
if len(success) > 0:
url = reverse("view_common_lib_dir", args=[dst_repo_id, urlquote(dst_path).strip('/')])
result = {'success': success, 'failed': failed, 'url': url}
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
def get_cp_progress(request):
'''
Fetch progress of file/dir mv/cp.
'''
content_type = 'application/json; charset=utf-8'
result = {}
task_id = request.GET.get('task_id')
if not task_id:
result['error'] = _(u'Argument missing')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
res = seafile_api.get_copy_task(task_id)
# res can be None
if not res:
result['error'] = _(u'Error')
return HttpResponse(json.dumps(result), status=500, content_type=content_type)
result['done'] = res.done
result['total'] = res.total
result['canceled'] = res.canceled
result['failed'] = res.failed
result['successful'] = res.successful
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
def cancel_cp(request):
'''
cancel file/dir mv/cp.
'''
content_type = 'application/json; charset=utf-8'
result = {}
task_id = request.GET.get('task_id')
if not task_id:
result['error'] = _('Argument missing')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
res = seafile_api.cancel_copy_task(task_id) # returns 0 or -1
if res == 0:
result['success'] = True
return HttpResponse(json.dumps(result), content_type=content_type)
else:
result['error'] = _('Cancel failed')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
@login_required_ajax
def repo_star_file(request, repo_id):
content_type = 'application/json; charset=utf-8'
user_perm = check_repo_access_permission(repo_id, request.user)
if user_perm is None:
err_msg = _(u'Permission denied.')
return HttpResponse(json.dumps({'error': err_msg}),
status=403, content_type=content_type)
path = request.GET.get('file', '')
if not path:
return HttpResponse(json.dumps({'error': _(u'Invalid arguments')}),
status=400, content_type=content_type)
is_dir = False
star_file(request.user.username, repo_id, path, is_dir)
return HttpResponse(json.dumps({'success':True}), content_type=content_type)
@login_required_ajax
def repo_unstar_file(request, repo_id):
content_type = 'application/json; charset=utf-8'
user_perm = check_repo_access_permission(repo_id, request.user)
if user_perm is None:
err_msg = _(u'Permission denied.')
return HttpResponse(json.dumps({'error': err_msg}),
status=403, content_type=content_type)
path = request.GET.get('file', '')
if not path:
return HttpResponse(json.dumps({'error': _(u'Invalid arguments')}),
status=400, content_type=content_type)
unstar_file(request.user.username, repo_id, path)
return HttpResponse(json.dumps({'success':True}), content_type=content_type)
########## contacts related
@login_required_ajax
def get_contacts(request):
content_type = 'application/json; charset=utf-8'
username = request.user.username
contacts = Contact.objects.get_contacts_by_user(username)
contact_list = []
from seahub.avatar.templatetags.avatar_tags import avatar
for c in contacts:
try:
user = User.objects.get(email=c.contact_email)
if user.is_active:
contact_list.append({
"email": c.contact_email,
"avatar": avatar(c.contact_email, 32),
"name": email2nickname(c.contact_email),
})
except User.DoesNotExist:
continue
return HttpResponse(json.dumps({"contacts":contact_list}), content_type=content_type)
@login_required_ajax
def get_current_commit(request, repo_id):
content_type = 'application/json; charset=utf-8'
repo = get_repo(repo_id)
if not repo:
err_msg = _(u'Library does not exist.')
return HttpResponse(json.dumps({'error': err_msg}),
status=400, content_type=content_type)
username = request.user.username
user_perm = check_repo_access_permission(repo.id, request.user)
if user_perm is None:
err_msg = _(u'Permission denied.')
return HttpResponse(json.dumps({'error': err_msg}),
status=403, content_type=content_type)
try:
server_crypto = UserOptions.objects.is_server_crypto(username)
except CryptoOptionNotSetError:
# Assume server_crypto is ``False`` if this option is not set.
server_crypto = False
if repo.encrypted and \
(repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \
and not seafile_api.is_password_set(repo.id, username):
err_msg = _(u'Library is encrypted.')
return HttpResponse(json.dumps({'error': err_msg}),
status=403, content_type=content_type)
head_commit = get_commit(repo.id, repo.version, repo.head_cmmt_id)
if not head_commit:
err_msg = _(u'Error: no head commit id')
return HttpResponse(json.dumps({'error': err_msg}),
status=500, content_type=content_type)
if new_merge_with_no_conflict(head_commit):
info_commit = get_commit_before_new_merge(head_commit)
else:
info_commit = head_commit
ctx = {
'repo': repo,
'info_commit': info_commit
}
html = render_to_string('snippets/current_commit.html', ctx,
context_instance=RequestContext(request))
return HttpResponse(json.dumps({'html': html}),
content_type=content_type)
@login_required_ajax
def sub_repo(request, repo_id):
'''
check if a dir has a corresponding sub_repo
if it does not have, create one
'''
username = request.user.username
content_type = 'application/json; charset=utf-8'
result = {}
if not request.user.permissions.can_add_repo():
result['error'] = _(u"You do not have permission to create library")
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
origin_repo = seafile_api.get_repo(repo_id)
if origin_repo is None:
result['error'] = _('Repo not found.')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# perm check, only repo owner can create sub repo
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(origin_repo.id)
else:
repo_owner = seafile_api.get_repo_owner(origin_repo.id)
is_repo_owner = True if username == repo_owner else False
if not is_repo_owner:
result['error'] = _(u"You do not have permission to create library")
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
path = request.GET.get('p')
if not path:
result['error'] = _('Argument missing')
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
name = os.path.basename(path)
# check if the sub-lib exist
try:
if is_org_context(request):
org_id = request.user.org.org_id
sub_repo = seaserv.seafserv_threaded_rpc.get_org_virtual_repo(
org_id, repo_id, path, username)
else:
sub_repo = seafile_api.get_virtual_repo(repo_id, path, username)
except SearpcError as e:
logger.error(e)
result['error'] = _('Failed to create sub library, please try again later.')
return HttpResponse(json.dumps(result), status=500, content_type=content_type)
if sub_repo:
result['sub_repo_id'] = sub_repo.id
else:
# create a sub-lib
try:
# use name as 'repo_name' & 'repo_desc' for sub_repo
if is_org_context(request):
org_id = request.user.org.org_id
sub_repo_id = seaserv.seafserv_threaded_rpc.create_org_virtual_repo(
org_id, repo_id, path, name, name, username)
else:
sub_repo_id = seafile_api.create_virtual_repo(repo_id, path,
name, name,
username)
result['sub_repo_id'] = sub_repo_id
result['name'] = name
result['abbrev_origin_path'] = get_sub_repo_abbrev_origin_path(
origin_repo.name, path)
except SearpcError as e:
logger.error(e)
result['error'] = _('Failed to create sub library, please try again later.')
return HttpResponse(json.dumps(result), status=500, content_type=content_type)
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
def download_enc_file(request, repo_id, file_id):
content_type = 'application/json; charset=utf-8'
result = {}
op = 'downloadblks'
blklist = []
if file_id == EMPTY_SHA1:
result = { 'blklist':blklist, 'url':None, }
return HttpResponse(json.dumps(result), content_type=content_type)
try:
blks = seafile_api.list_file_by_file_id(repo_id, file_id)
except SearpcError, e:
result['error'] = _(u'Failed to get file block list')
return HttpResponse(json.dumps(result), content_type=content_type)
blklist = blks.split('\n')
blklist = [i for i in blklist if len(i) == 40]
token = seafile_api.get_fileserver_access_token(repo_id, file_id,
op, request.user.username)
url = gen_block_get_url(token, None)
result = {
'blklist':blklist,
'url':url,
}
return HttpResponse(json.dumps(result), content_type=content_type)
def upload_file_done(request):
"""Send a message when a file is uploaded.
Arguments:
- `request`:
"""
ct = 'application/json; charset=utf-8'
result = {}
filename = request.GET.get('fn', '')
if not filename:
result['error'] = _('Argument missing')
return HttpResponse(json.dumps(result), status=400, content_type=ct)
repo_id = request.GET.get('repo_id', '')
if not repo_id:
result['error'] = _('Argument missing')
return HttpResponse(json.dumps(result), status=400, content_type=ct)
path = request.GET.get('p', '')
if not path:
result['error'] = _('Argument missing')
return HttpResponse(json.dumps(result), status=400, content_type=ct)
# a few checkings
if not seafile_api.get_repo(repo_id):
result['error'] = _('Wrong repo id')
return HttpResponse(json.dumps(result), status=400, content_type=ct)
owner = seafile_api.get_repo_owner(repo_id)
if not owner: # this is an org repo, get org repo owner
owner = seafile_api.get_org_repo_owner(repo_id)
file_path = path.rstrip('/') + '/' + filename
if seafile_api.get_file_id_by_path(repo_id, file_path) is None:
result['error'] = _('File does not exist')
return HttpResponse(json.dumps(result), status=400, content_type=ct)
# send singal
upload_file_successful.send(sender=None,
repo_id=repo_id,
file_path=file_path,
owner=owner)
return HttpResponse(json.dumps({'success': True}), content_type=ct)
@login_required_ajax
def unseen_notices_count(request):
"""Count user's unseen notices.
Arguments:
- `request`:
"""
content_type = 'application/json; charset=utf-8'
username = request.user.username
count = UserNotification.objects.count_unseen_user_notifications(username)
result = {}
result['count'] = count
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
def get_popup_notices(request):
"""Get user's notifications.
If unseen notices > 5, return all unseen notices.
If unseen notices = 0, return last 5 notices.
Otherwise return all unseen notices, plus some seen notices to make the
sum equal to 5.
Arguments:
- `request`:
"""
content_type = 'application/json; charset=utf-8'
username = request.user.username
result_notices = []
unseen_notices = []
seen_notices = []
list_num = 5
unseen_num = UserNotification.objects.count_unseen_user_notifications(username)
if unseen_num == 0:
seen_notices = UserNotification.objects.get_user_notifications(
username)[:list_num]
elif unseen_num > list_num:
unseen_notices = UserNotification.objects.get_user_notifications(
username, seen=False)
else:
unseen_notices = UserNotification.objects.get_user_notifications(
username, seen=False)
seen_notices = UserNotification.objects.get_user_notifications(
username, seen=True)[:list_num - unseen_num]
result_notices += unseen_notices
result_notices += seen_notices
# Add 'msg_from' or 'default_avatar_url' to notice.
result_notices = add_notice_from_info(result_notices)
ctx_notices = {"notices": result_notices}
notice_html = render_to_string(
'snippets/notice_html.html', ctx_notices,
context_instance=RequestContext(request))
return HttpResponse(json.dumps({
"notice_html": notice_html,
}), content_type=content_type)
@login_required_ajax
@require_POST
def set_notices_seen(request):
"""Set user's notices seen:
Arguments:
- `request`:
"""
content_type = 'application/json; charset=utf-8'
username = request.user.username
unseen_notices = UserNotification.objects.get_user_notifications(username,
seen=False)
for notice in unseen_notices:
notice.seen = True
notice.save()
# mark related user msg as read
if notice.is_user_message():
d = notice.user_message_detail_to_dict()
msg_from = d.get('msg_from')
UserMessage.objects.update_unread_messages(msg_from, username)
return HttpResponse(json.dumps({'success': True}), content_type=content_type)
@login_required_ajax
@require_POST
def set_notice_seen_by_id(request):
"""
Arguments:
- `request`:
"""
content_type = 'application/json; charset=utf-8'
notice_id = request.GET.get('notice_id')
try:
notice = UserNotification.objects.get(id=notice_id)
except UserNotification.DoesNotExist as e:
logger.error(e)
return HttpResponse(json.dumps({
'error': _(u'Failed')
}), status=400, content_type=content_type)
if not notice.seen:
notice.seen = True
notice.save()
return HttpResponse(json.dumps({'success': True}), content_type=content_type)
@login_required_ajax
@require_POST
def repo_remove(request, repo_id):
ct = 'application/json; charset=utf-8'
result = {}
repo = get_repo(repo_id)
username = request.user.username
if is_org_context(request):
# Remove repo in org context, only (repo owner/org staff) can perform
# this operation.
org_id = request.user.org.org_id
is_org_staff = request.user.org.is_staff
org_repo_owner = seafile_api.get_org_repo_owner(repo_id)
if is_org_staff or org_repo_owner == username:
# Must get related useres before remove the repo
usernames = get_related_users_by_org_repo(org_id, repo_id)
seafile_api.remove_repo(repo_id)
if repo: # send delete signal only repo is valid
repo_deleted.send(sender=None,
org_id=org_id,
usernames=usernames,
repo_owner=username,
repo_id=repo_id,
repo_name=repo.name)
result['success'] = True
return HttpResponse(json.dumps(result), content_type=ct)
else:
result['error'] = _(u'Permission denied.')
return HttpResponse(json.dumps(result), status=403, content_type=ct)
else:
# Remove repo in personal context, only (repo owner) can perform this
# operation.
if validate_owner(request, repo_id):
usernames = get_related_users_by_repo(repo_id)
seafile_api.remove_repo(repo_id)
if repo: # send delete signal only repo is valid
repo_deleted.send(sender=None,
org_id=-1,
usernames=usernames,
repo_owner=username,
repo_id=repo_id,
repo_name=repo.name)
result['success'] = True
return HttpResponse(json.dumps(result), content_type=ct)
else:
result['error'] = _(u'Permission denied.')
return HttpResponse(json.dumps(result), status=403, content_type=ct)
@login_required_ajax
def space_and_traffic(request):
content_type = 'application/json; charset=utf-8'
username = request.user.username
# space & quota calculation
org = ccnet_threaded_rpc.get_orgs_by_user(username)
if not org:
space_quota = seafile_api.get_user_quota(username)
space_usage = seafile_api.get_user_self_usage(username)
else:
org_id = org[0].org_id
space_quota = seafserv_threaded_rpc.get_org_user_quota(org_id,
username)
space_usage = seafserv_threaded_rpc.get_org_user_quota_usage(
org_id, username)
rates = {}
if space_quota > 0:
rates['space_usage'] = str(float(space_usage) / space_quota * 100) + '%'
else: # no space quota set in config
rates['space_usage'] = '0%'
# traffic calculation
traffic_stat = 0
if TRAFFIC_STATS_ENABLED:
# User's network traffic stat in this month
try:
stat = get_user_traffic_stat(username)
except Exception as e:
logger.error(e)
stat = None
if stat:
traffic_stat = stat['file_view'] + stat['file_download'] + stat['dir_download']
# payment url, TODO: need to remove from here.
payment_url = ''
ENABLE_PAYMENT = getattr(settings, 'ENABLE_PAYMENT', False)
if ENABLE_PAYMENT:
if is_org_context(request):
if request.user.org and bool(request.user.org.is_staff) is True:
# payment for org admin
payment_url = reverse('org_plan')
else:
# no payment for org members
ENABLE_PAYMENT = False
else:
# payment for personal account
payment_url = reverse('plan')
ctx = {
"org": org,
"space_quota": space_quota,
"space_usage": space_usage,
"rates": rates,
"SHOW_TRAFFIC": SHOW_TRAFFIC,
"TRAFFIC_STATS_ENABLED": TRAFFIC_STATS_ENABLED,
"traffic_stat": traffic_stat,
"ENABLE_PAYMENT": ENABLE_PAYMENT,
"payment_url": payment_url,
}
html = render_to_string('snippets/space_and_traffic.html', ctx,
context_instance=RequestContext(request))
return HttpResponse(json.dumps({"html": html}), content_type=content_type)
def get_share_in_repo_list(request, start, limit):
"""List share in repos.
"""
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
repo_list = seafile_api.get_org_share_in_repo_list(org_id, username,
-1, -1)
else:
repo_list = seafile_api.get_share_in_repo_list(username, -1, -1)
for repo in repo_list:
repo.user_perm = seafile_api.check_repo_access_permission(repo.repo_id,
username)
return repo_list
def get_groups_by_user(request):
"""List user groups.
"""
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
return seaserv.get_org_groups_by_user(org_id, username)
else:
return seaserv.get_personal_groups_by_user(username)
def get_group_repos(request, groups):
"""Get repos shared to groups.
"""
username = request.user.username
group_repos = []
if is_org_context(request):
org_id = request.user.org.org_id
# For each group I joined...
for grp in groups:
# Get group repos, and for each group repos...
for r_id in seafile_api.get_org_group_repoids(org_id, grp.id):
# No need to list my own repo
repo_owner = seafile_api.get_org_repo_owner(r_id)
if repo_owner == username:
continue
# Convert repo properties due to the different collumns in Repo
# and SharedRepo
r = get_repo(r_id)
if not r:
continue
r.repo_id = r.id
r.repo_name = r.name
r.repo_desc = r.desc
r.last_modified = get_repo_last_modify(r)
r.share_type = 'group'
r.user = repo_owner
r.user_perm = seafile_api.check_repo_access_permission(
r_id, username)
r.group = grp
group_repos.append(r)
else:
# For each group I joined...
for grp in groups:
# Get group repos, and for each group repos...
for r_id in seafile_api.get_group_repoids(grp.id):
# No need to list my own repo
repo_owner = seafile_api.get_repo_owner(r_id)
if repo_owner == username:
continue
# Convert repo properties due to the different collumns in Repo
# and SharedRepo
r = get_repo(r_id)
if not r:
continue
r.repo_id = r.id
r.repo_name = r.name
r.repo_desc = r.desc
r.last_modified = get_repo_last_modify(r)
r.share_type = 'group'
r.user = repo_owner
r.user_perm = seafile_api.check_repo_access_permission(
r_id, username)
r.group = grp
group_repos.append(r)
return group_repos
def get_file_uploaded_bytes(request, repo_id):
"""
For resumable fileupload
"""
content_type = 'application/json; charset=utf-8'
parent_dir = request.GET.get('parent_dir')
file_name = request.GET.get('file_name')
if not parent_dir or not file_name:
err_msg = _(u'Argument missing')
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
repo = get_repo(repo_id)
if not repo:
err_msg = _(u'Library does not exist')
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
file_path = os.path.join(parent_dir, file_name)
uploadedBytes = seafile_api.get_upload_tmp_file_offset(repo_id, file_path)
return HttpResponse(json.dumps({"uploadedBytes": uploadedBytes}),
content_type=content_type)
@login_required_ajax
def get_file_op_url(request, repo_id):
"""Get file upload/update url for AJAX.
"""
content_type = 'application/json; charset=utf-8'
op_type = request.GET.get('op_type') # value can be 'upload', 'update', 'upload-blks', 'update-blks'
path = request.GET.get('path')
if not (op_type and path):
err_msg = _(u'Argument missing')
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
repo = get_repo(repo_id)
if not repo:
err_msg = _(u'Library does not exist')
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
# permission checking
if check_folder_permission(request, repo.id, path) != 'rw':
err_msg = _(u'Permission denied')
return HttpResponse(json.dumps({"error": err_msg}), status=403,
content_type=content_type)
username = request.user.username
if op_type == 'upload':
if request.user.is_staff and get_system_default_repo_id() == repo.id:
# Set username to 'system' to let fileserver release permission
# check.
username = 'system'
if op_type.startswith('update'):
token = seafile_api.get_fileserver_access_token(repo_id, 'dummy',
op_type, username)
else:
token = seafile_api.get_fileserver_access_token(repo_id, 'dummy',
op_type, username,
use_onetime=False)
url = gen_file_upload_url(token, op_type + '-aj', request.GET.get('hostname'))
return HttpResponse(json.dumps({"url": url}), content_type=content_type)
def get_file_upload_url_ul(request, token):
"""Get file upload url in dir upload link.
Arguments:
- `request`:
- `token`:
"""
if not request.is_ajax():
raise Http404
content_type = 'application/json; charset=utf-8'
uls = UploadLinkShare.objects.get_valid_upload_link_by_token(token)
if uls is None:
return HttpResponse(json.dumps({"error": _("Bad upload link token.")}),
status=400, content_type=content_type)
repo_id = uls.repo_id
r = request.GET.get('r', '')
if repo_id != r: # perm check
return HttpResponse(json.dumps({"error": _("Bad repo id in upload link.")}),
status=403, content_type=content_type)
acc_token = seafile_api.get_fileserver_access_token(repo_id, 'dummy',
'upload', '',
use_onetime=False)
url = gen_file_upload_url(acc_token, 'upload-aj', request.GET.get('hostname'))
return HttpResponse(json.dumps({"url": url}), content_type=content_type)
@login_required_ajax
def repo_history_changes(request, repo_id):
changes = {}
content_type = 'application/json; charset=utf-8'
repo = get_repo(repo_id)
if not repo:
err_msg = _(u'Library does not exist.')
return HttpResponse(json.dumps({'error': err_msg}),
status=400, content_type=content_type)
# perm check
if check_repo_access_permission(repo.id, request.user) is None:
if request.user.is_staff is True:
pass # Allow system staff to check repo changes
else:
err_msg = _(u"Permission denied")
return HttpResponse(json.dumps({"error": err_msg}), status=403,
content_type=content_type)
username = request.user.username
try:
server_crypto = UserOptions.objects.is_server_crypto(username)
except CryptoOptionNotSetError:
# Assume server_crypto is ``False`` if this option is not set.
server_crypto = False
if repo.encrypted and \
(repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \
and not is_passwd_set(repo_id, username):
err_msg = _(u'Library is encrypted.')
return HttpResponse(json.dumps({'error': err_msg}),
status=403, content_type=content_type)
commit_id = request.GET.get('commit_id', '')
if not commit_id:
err_msg = _(u'Argument missing')
return HttpResponse(json.dumps({'error': err_msg}),
status=400, content_type=content_type)
changes = get_diff(repo_id, '', commit_id)
c = get_commit(repo.id, repo.version, commit_id)
if c.parent_id is None:
# A commit is a first commit only if it's parent id is None.
changes['cmt_desc'] = repo.desc
elif c.second_parent_id is None:
# Normal commit only has one parent.
if c.desc.startswith('Changed library'):
changes['cmt_desc'] = _('Changed library name or description')
else:
# A commit is a merge only if it has two parents.
changes['cmt_desc'] = _('No conflict in the merge.')
changes['date_time'] = tsstr_sec(c.ctime)
return HttpResponse(json.dumps(changes), content_type=content_type)
def _create_repo_common(request, repo_name, repo_desc, encryption,
uuid, magic_str, encrypted_file_key):
"""Common logic for creating repo.
Returns:
newly created repo id. Or ``None`` if error raised.
"""
username = request.user.username
try:
if not encryption:
if is_org_context(request):
org_id = request.user.org.org_id
repo_id = seafile_api.create_org_repo(repo_name, repo_desc,
username, None, org_id)
else:
repo_id = seafile_api.create_repo(repo_name, repo_desc,
username, None)
else:
if is_org_context(request):
org_id = request.user.org.org_id
repo_id = seafile_api.create_org_enc_repo(
uuid, repo_name, repo_desc, username, magic_str,
encrypted_file_key, enc_version=2, org_id=org_id)
else:
repo_id = seafile_api.create_enc_repo(
uuid, repo_name, repo_desc, username,
magic_str, encrypted_file_key, enc_version=2)
except SearpcError as e:
logger.error(e)
repo_id = None
return repo_id
@login_required_ajax
def public_repo_create(request):
'''
Handle ajax post to create public repo.
'''
if request.method != 'POST':
return Http404
result = {}
content_type = 'application/json; charset=utf-8'
if not request.user.permissions.can_add_repo():
result['error'] = _(u"You do not have permission to create library")
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
form = SharedRepoCreateForm(request.POST)
if not form.is_valid():
result['error'] = str(form.errors.values()[0])
return HttpResponseBadRequest(json.dumps(result),
content_type=content_type)
repo_name = form.cleaned_data['repo_name']
repo_desc = form.cleaned_data['repo_desc']
permission = form.cleaned_data['permission']
encryption = int(form.cleaned_data['encryption'])
uuid = form.cleaned_data['uuid']
magic_str = form.cleaned_data['magic_str']
encrypted_file_key = form.cleaned_data['encrypted_file_key']
repo_id = _create_repo_common(request, repo_name, repo_desc, encryption,
uuid, magic_str, encrypted_file_key)
if repo_id is None:
result['error'] = _(u'Internal Server Error')
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
org_id = -1
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.set_org_inner_pub_repo(
org_id, repo_id, permission)
else:
seafile_api.add_inner_pub_repo(repo_id, permission)
username = request.user.username
repo_created.send(sender=None,
org_id=org_id,
creator=username,
repo_id=repo_id,
repo_name=repo_name)
result['success'] = True
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
def events(request):
events_count = 15
username = request.user.username
start = int(request.GET.get('start'))
if is_org_context(request):
org_id = request.user.org.org_id
events, start = get_org_user_events(org_id, username, start, events_count)
else:
events, start = get_user_events(username, start, events_count)
events_more = True if len(events) == events_count else False
event_groups = group_events_data(events)
ctx = {'event_groups': event_groups}
html = render_to_string("snippets/events_body.html", ctx)
return HttpResponse(json.dumps({'html': html,
'events_more': events_more,
'new_start': start}),
content_type='application/json; charset=utf-8')
@login_required_ajax
def ajax_repo_change_basic_info(request, repo_id):
"""Handle post request to change library basic info.
"""
if request.method != 'POST':
raise Http404
content_type = 'application/json; charset=utf-8'
username = request.user.username
repo = seafile_api.get_repo(repo_id)
if not repo:
raise Http404
# no settings for virtual repo
if ENABLE_SUB_LIBRARY and repo.is_virtual:
raise Http404
# check permission
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
is_owner = True if username == repo_owner else False
if not is_owner:
raise Http404
form = RepoSettingForm(request.POST)
if not form.is_valid():
return HttpResponse(json.dumps({
'error': str(form.errors.values()[0])
}), status=400, content_type=content_type)
repo_name = form.cleaned_data['repo_name']
days = form.cleaned_data['days']
# Edit library info (name, descryption).
if repo.name != repo_name:
if not edit_repo(repo_id, repo_name, '', username): # set desc as ''
err_msg = _(u'Failed to edit library information.')
return HttpResponse(json.dumps({'error': err_msg}),
status=500, content_type=content_type)
# set library history
if days is not None and config.ENABLE_REPO_HISTORY_SETTING:
res = set_repo_history_limit(repo_id, days)
if res != 0:
return HttpResponse(json.dumps({
'error': _(u'Failed to save settings on server')
}), status=400, content_type=content_type)
messages.success(request, _(u'Settings saved.'))
return HttpResponse(json.dumps({'success': True}),
content_type=content_type)
@login_required_ajax
def ajax_repo_transfer_owner(request, repo_id):
"""Handle post request to transfer library owner.
"""
if request.method != 'POST':
raise Http404
content_type = 'application/json; charset=utf-8'
username = request.user.username
repo = seafile_api.get_repo(repo_id)
if not repo:
raise Http404
# check permission
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
is_owner = True if username == repo_owner else False
if not is_owner:
raise Http404
# check POST arg
repo_owner = request.POST.get('repo_owner', '').lower()
if not is_valid_username(repo_owner):
return HttpResponse(json.dumps({
'error': _('Username %s is not valid.') % repo_owner,
}), status=400, content_type=content_type)
try:
User.objects.get(email=repo_owner)
except User.DoesNotExist:
return HttpResponse(json.dumps({
'error': _('User %s is not found.') % repo_owner,
}), status=400, content_type=content_type)
if is_org_context(request):
org_id = request.user.org.org_id
if not seaserv.ccnet_threaded_rpc.org_user_exists(org_id, repo_owner):
return HttpResponse(json.dumps({
'error': _('User %s is not in current organization.') %
repo_owner,}), status=400, content_type=content_type)
if repo_owner and repo_owner != username:
if is_org_context(request):
org_id = request.user.org.org_id
seafile_api.set_org_repo_owner(org_id, repo_id, repo_owner)
else:
if ccnet_threaded_rpc.get_orgs_by_user(repo_owner):
return HttpResponse(json.dumps({
'error': _('Can not transfer library to organization user %s.') % repo_owner,
}), status=400, content_type=content_type)
else:
seafile_api.set_repo_owner(repo_id, repo_owner)
return HttpResponse(json.dumps({'success': True}), content_type=content_type)
@login_required_ajax
def ajax_repo_change_passwd(request, repo_id):
"""Handle ajax post request to change library password.
"""
if request.method != 'POST':
raise Http404
content_type = 'application/json; charset=utf-8'
username = request.user.username
repo = seafile_api.get_repo(repo_id)
if not repo:
raise Http404
# check permission
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
is_owner = True if username == repo_owner else False
if not is_owner:
return HttpResponse(json.dumps({
'error': _('Faied to change password, you are not owner.')}),
status=400, content_type=content_type)
old_passwd = request.POST.get('old_passwd', '')
new_passwd = request.POST.get('new_passwd', '')
try:
seafile_api.change_repo_passwd(repo_id, old_passwd, new_passwd, username)
except SearpcError, e:
return HttpResponse(json.dumps({
'error': e.msg,
}), status=400, content_type=content_type)
messages.success(request, _(u'Successfully updated the password of Library %(repo_name)s.') %
{'repo_name': escape(repo.name)})
return HttpResponse(json.dumps({'success': True}),
content_type=content_type)
@login_required_ajax
def get_folder_perm_by_path(request, repo_id):
"""
Get user/group folder permission by path
"""
result = {}
content_type = 'application/json; charset=utf-8'
if not (is_pro_version() and ENABLE_FOLDER_PERM):
return HttpResponse(json.dumps({"error": True}),
status=403, content_type=content_type)
path = request.GET.get('path', None)
if not path:
return HttpResponse(json.dumps({"error": _('Argument missing')}),
status=400, content_type=content_type)
user_perms = seafile_api.list_folder_user_perm_by_repo(repo_id)
group_perms = seafile_api.list_folder_group_perm_by_repo(repo_id)
user_perms.reverse()
group_perms.reverse()
user_result_perms = []
for user_perm in user_perms:
if path == user_perm.path:
user_result_perm = {
"perm": user_perm.permission,
"user": user_perm.user,
"user_name": email2nickname(user_perm.user),
}
user_result_perms.append(user_result_perm)
group_result_perms = []
for group_perm in group_perms:
if path == group_perm.path:
group_result_perm = {
"perm": group_perm.permission,
"group_id": group_perm.group_id,
"group_name": get_group(group_perm.group_id).group_name,
}
group_result_perms.append(group_result_perm)
result['user_perms'] = user_result_perms
result['group_perms'] = group_result_perms
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
def set_user_folder_perm(request, repo_id):
"""
Add or modify or delete folder permission to a user
"""
if request.method != 'POST':
raise Http404
content_type = 'application/json; charset=utf-8'
if not (is_pro_version() and ENABLE_FOLDER_PERM):
return HttpResponse(json.dumps({"error": _(u"Permission denied")}),
status=403, content_type=content_type)
user = request.POST.get('user', None)
path = request.POST.get('path', None)
perm = request.POST.get('perm', None)
op_type = request.POST.get('type', None)
username = request.user.username
## check params
if not user or not path or not perm or \
op_type != 'add' and op_type != 'modify' and op_type != 'delete':
return HttpResponse(json.dumps({"error": _('Argument missing')}),
status=400, content_type=content_type)
if not seafile_api.get_repo(repo_id):
return HttpResponse(json.dumps({"error": _('Library does not exist')}),
status=400, content_type=content_type)
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo_id)
else:
repo_owner = seafile_api.get_repo_owner(repo_id)
if username != repo_owner:
return HttpResponse(json.dumps({"error": _('Permission denied')}),
status=403, content_type=content_type)
if perm is not None:
if perm != 'r' and perm != 'rw':
return HttpResponse(json.dumps({
"error": _('Invalid folder permission, should be "rw" or "r"')
}), status=400, content_type=content_type)
if not path.startswith('/'):
return HttpResponse(json.dumps({"error": _('Path should start with "/"')}),
status=400, content_type=content_type)
if path != '/' and path.endswith('/'):
return HttpResponse(json.dumps({"error": _('Path should not end with "/"')}),
status=400, content_type=content_type)
if seafile_api.get_dir_id_by_path(repo_id, path) is None:
return HttpResponse(json.dumps({"error": _('Invalid path')}),
status=400, content_type=content_type)
## add perm for user(s)
if op_type == 'add':
return add_user_folder_perm(request, repo_id, user, path, perm)
if not is_registered_user(user):
return HttpResponse(json.dumps({"error": _('Invalid user, should be registered')}),
status=400, content_type=content_type)
user_folder_perm = seafile_api.get_folder_user_perm(repo_id, path, user)
if op_type == 'modify':
if user_folder_perm and user_folder_perm != perm:
try:
seafile_api.set_folder_user_perm(repo_id, path, perm, user)
send_perm_audit_msg('modify-repo-perm', username, user, repo_id, path, perm)
except SearpcError as e:
logger.error(e)
return HttpResponse(json.dumps({"error": _('Operation failed')}),
status=500, content_type=content_type)
else:
return HttpResponse(json.dumps({"error": _('Wrong folder permission')}),
status=400, content_type=content_type)
if op_type == 'delete':
if user_folder_perm:
try:
seafile_api.rm_folder_user_perm(repo_id, path, user)
send_perm_audit_msg('delete-repo-perm', username, user, repo_id, path, perm)
except SearpcError as e:
logger.error(e)
return HttpResponse(json.dumps({"error": _('Operation failed')}),
status=500, content_type=content_type)
else:
return HttpResponse(json.dumps({"error": _('Please add folder permission first')}),
status=400, content_type=content_type)
return HttpResponse(json.dumps({'success': True}), content_type=content_type)
def add_user_folder_perm(request, repo_id, users, path, perm):
"""
Add folder permission for user(s)
"""
content_type = 'application/json; charset=utf-8'
emails = users.split(',')
success, failed = [], []
username = request.user.username
for user in [e.strip() for e in emails if e.strip()]:
if not is_valid_username(user):
failed.append(user)
continue
if not is_registered_user(user):
failed.append(user)
continue
user_folder_perm = seafile_api.get_folder_user_perm(repo_id, path, user)
if user_folder_perm:
# Already add this folder permission
continue
try:
seafile_api.add_folder_user_perm(repo_id, path, perm, user)
send_perm_audit_msg('add-repo-perm', username, user, repo_id, path, perm)
success.append({
'user': user,
'user_name': email2nickname(user)
})
except SearpcError as e:
logger.error(e)
failed.append(user)
if len(success) > 0:
data = json.dumps({"success": success, "failed": failed})
return HttpResponse(data, content_type=content_type)
else:
data = json.dumps({
"error": _("Please check the email(s) you entered and the contacts you selected")
})
return HttpResponse(data, status=400, content_type=content_type)
@login_required_ajax
def set_group_folder_perm(request, repo_id):
"""
Add or modify or delete folder permission to a group
"""
if request.method != 'POST':
raise Http404
content_type = 'application/json; charset=utf-8'
if not (is_pro_version() and ENABLE_FOLDER_PERM):
return HttpResponse(json.dumps({"error": _(u"Permission denied")}),
status=403, content_type=content_type)
group_id = request.POST.get('group_id', None)
path = request.POST.get('path', None)
perm = request.POST.get('perm', None)
op_type = request.POST.get('type', None)
username = request.user.username
if not group_id or not path or not perm or \
op_type != 'add' and op_type != 'modify' and op_type != 'delete':
return HttpResponse(json.dumps({"error": _('Argument missing')}),
status=400, content_type=content_type)
## check params
if not seafile_api.get_repo(repo_id):
return HttpResponse(json.dumps({"error": _('Library does not exist')}),
status=400, content_type=content_type)
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo_id)
else:
repo_owner = seafile_api.get_repo_owner(repo_id)
if username != repo_owner:
return HttpResponse(json.dumps({"error": _('Permission denied')}),
status=403, content_type=content_type)
if perm is not None:
if perm != 'r' and perm != 'rw':
return HttpResponse(json.dumps({
"error": _('Invalid folder permission, should be "rw" or "r"')
}), status=400, content_type=content_type)
if not path.startswith('/'):
return HttpResponse(json.dumps({"error": _('Path should start with "/"')}),
status=400, content_type=content_type)
if path != '/' and path.endswith('/'):
return HttpResponse(json.dumps({"error": _('Path should not end with "/"')}),
status=400, content_type=content_type)
if seafile_api.get_dir_id_by_path(repo_id, path) is None:
return HttpResponse(json.dumps({"error": _('Invalid path')}),
status=400, content_type=content_type)
## add perm for group(s)
if op_type == 'add':
return add_group_folder_perm(request, repo_id, group_id, path, perm)
group_id = int(group_id)
if not seaserv.get_group(group_id):
return HttpResponse(json.dumps({"error": _('Invalid group')}),
status=400, content_type=content_type)
group_folder_perm = seafile_api.get_folder_group_perm(repo_id, path, group_id)
if op_type == 'modify':
if group_folder_perm and group_folder_perm != perm:
try:
seafile_api.set_folder_group_perm(repo_id, path, perm, group_id)
send_perm_audit_msg('modify-repo-perm', username, group_id, repo_id, path, perm)
except SearpcError as e:
logger.error(e)
return HttpResponse(json.dumps({"error": _('Operation failed')}),
status=500, content_type=content_type)
else:
return HttpResponse(json.dumps({"error": _('Wrong folder permission')}),
status=400, content_type=content_type)
if op_type == 'delete':
if group_folder_perm:
try:
seafile_api.rm_folder_group_perm(repo_id, path, group_id)
send_perm_audit_msg('delete-repo-perm', username, group_id, repo_id, path, perm)
except SearpcError as e:
logger.error(e)
return HttpResponse(json.dumps({"error": _('Operation failed')}),
status=500, content_type=content_type)
else:
return HttpResponse(json.dumps({"error": _('Please add folder permission first')}),
status=400, content_type=content_type)
return HttpResponse(json.dumps({'success': True}), content_type=content_type)
def add_group_folder_perm(request, repo_id, group_ids, path, perm):
"""
Add folder permission for group(s)
"""
content_type = 'application/json; charset=utf-8'
group_id_list = group_ids.split(',') # 'user'
success, failed = [], []
username = request.user.username
for group_id in group_id_list:
group_id = int(group_id)
if not seaserv.get_group(group_id):
failed.append(group_id)
group_folder_perm = seafile_api.get_folder_group_perm(repo_id, path, group_id)
if group_folder_perm:
#Already add this folder permission
continue
try:
seafile_api.add_folder_group_perm(repo_id, path, perm, group_id)
send_perm_audit_msg('add-repo-perm', username, group_id, repo_id, path, perm)
success.append({
'group_id': group_id,
"group_name": get_group(group_id).group_name,
})
except SearpcError as e:
logger.error(e)
failed.append(group_id)
if len(success) > 0:
data = json.dumps({"success": success, "failed": failed})
return HttpResponse(data, content_type=content_type)
else:
data = json.dumps({"error": _("Failed")})
return HttpResponse(data, status=400, content_type=content_type)
@login_required_ajax
def get_group_basic_info(request, group_id):
'''
Get group basic info for group side nav
'''
content_type = 'application/json; charset=utf-8'
result = {}
group_id_int = int(group_id) # Checked by URL Conf
group = get_group(group_id_int)
if not group:
result["error"] = _('Group does not exist.')
return HttpResponse(json.dumps(result),
status=400, content_type=content_type)
group.is_staff = is_group_staff(group, request.user)
if PublicGroup.objects.filter(group_id=group.id):
group.is_pub = True
else:
group.is_pub = False
mods_available = get_available_mods_by_group(group.id)
mods_enabled = get_enabled_mods_by_group(group.id)
return HttpResponse(json.dumps({
"id": group.id,
"name": group.group_name,
"avatar": grp_avatar(group.id, 32),
"is_staff": group.is_staff,
"is_pub": group.is_pub,
"mods_available": mods_available,
"mods_enabled": mods_enabled,
}), content_type=content_type)
@login_required_ajax
def toggle_group_modules(request, group_id):
content_type = 'application/json; charset=utf-8'
result = {}
group_id_int = int(group_id) # Checked by URL Conf
group = get_group(group_id_int)
if not group:
result["error"] = _('Group does not exist.')
return HttpResponse(json.dumps(result),
status=400, content_type=content_type)
group.is_staff = is_group_staff(group, request.user)
if not group.is_staff:
result["error"] = _('Permission denied.')
return HttpResponse(json.dumps(result),
status=403, content_type=content_type)
group_wiki = request.POST.get('group_wiki', '')
if group_wiki == 'true':
enable_mod_for_group(group.id, MOD_GROUP_WIKI)
else:
disable_mod_for_group(group.id, MOD_GROUP_WIKI)
return HttpResponse(json.dumps({ "success": True }),
content_type=content_type)
@login_required_ajax
def toggle_personal_modules(request):
content_type = 'application/json; charset=utf-8'
result = {}
if not request.user.permissions.can_add_repo:
result["error"] = _('Permission denied.')
return HttpResponse(json.dumps(result),
status=403, content_type=content_type)
username = request.user.username
personal_wiki = request.POST.get('personal_wiki', '')
if personal_wiki == 'true':
enable_mod_for_user(username, MOD_PERSONAL_WIKI)
else:
disable_mod_for_user(username, MOD_PERSONAL_WIKI)
return HttpResponse(json.dumps({ "success": True }),
content_type=content_type)
@login_required_ajax
@require_POST
def ajax_unset_inner_pub_repo(request, repo_id):
"""
Unshare repos in organization.
"""
content_type = 'application/json; charset=utf-8'
result = {}
repo = get_repo(repo_id)
if not repo:
result["error"] = _('Library does not exist.')
return HttpResponse(json.dumps(result),
status=400, content_type=content_type)
perm = request.POST.get('permission', None)
if perm is None:
result["error"] = _(u'Argument missing')
return HttpResponse(json.dumps(result),
status=400, content_type=content_type)
# permission check
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
repo_owner = seafile_api.get_org_repo_owner(repo.id)
is_repo_owner = True if repo_owner == username else False
if not (request.user.org.is_staff or is_repo_owner):
result["error"] = _('Permission denied.')
return HttpResponse(json.dumps(result),
status=403, content_type=content_type)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
is_repo_owner = True if repo_owner == username else False
if not (request.user.is_staff or is_repo_owner):
result["error"] = _('Permission denied.')
return HttpResponse(json.dumps(result),
status=403, content_type=content_type)
try:
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.unset_org_inner_pub_repo(org_id,
repo.id)
else:
seaserv.unset_inner_pub_repo(repo.id)
origin_repo_id, origin_path = get_origin_repo_info(repo.id)
if origin_repo_id is not None:
perm_repo_id = origin_repo_id
perm_path = origin_path
else:
perm_repo_id = repo.id
perm_path = '/'
send_perm_audit_msg('delete-repo-perm', username, 'all', \
perm_repo_id, perm_path, perm)
return HttpResponse(json.dumps({"success": True}), content_type=content_type)
except SearpcError:
return HttpResponse(json.dumps({"error": _('Internal server error')}),
status=500, content_type=content_type)
@login_required_ajax
def ajax_repo_dir_recycle_more(request, repo_id):
"""
List 'more' repo/dir trash.
"""
result = {}
content_type = 'application/json; charset=utf-8'
repo = seafile_api.get_repo(repo_id)
if not repo:
err_msg = 'Library %s not found.' % repo_id
return HttpResponse(json.dumps({'error': err_msg}),
status=404, content_type=content_type)
path = request.GET.get('path', '/')
path = '/' if path == '' else path
if check_folder_permission(request, repo_id, path) != 'rw':
err_msg = 'Permission denied.'
return HttpResponse(json.dumps({'error': err_msg}),
status=403, content_type=content_type)
scan_stat = request.GET.get('scan_stat', None)
try:
deleted_entries = seafile_api.get_deleted(repo_id, 0, path, scan_stat)
except SearpcError as e:
logger.error(e)
result['error'] = 'Internal server error'
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
new_scan_stat = deleted_entries[-1].scan_stat
trash_more = True if new_scan_stat is not None else False
more_entries_html = ''
# since there will always have one 'deleted_entry' to tell scan_stat,
# so if len of deleted_entries = 1, means have not get any trash dir/file
# if len of deleted_entries > 1,
# means have get trash dir/file from current scanned commits
if len(deleted_entries) > 1:
deleted_entries = deleted_entries[0:-1]
for dirent in deleted_entries:
if stat.S_ISDIR(dirent.mode):
dirent.is_dir = True
else:
dirent.is_dir = False
# Entries sort by deletion time in descending order.
deleted_entries.sort(lambda x, y : cmp(y.delete_time,
x.delete_time))
ctx = {
'show_recycle_root': True,
'repo': repo,
'dir_entries': deleted_entries,
'dir_path': path,
'MEDIA_URL': MEDIA_URL
}
more_entries_html = render_to_string("snippets/repo_dir_trash_tr.html", ctx)
result = {
'html': more_entries_html,
'trash_more': trash_more,
'new_scan_stat': new_scan_stat,
}
return HttpResponse(json.dumps(result), content_type=content_type)
<file_sep>/seahub/notifications/management/commands/send_notices.py
# encoding: utf-8
import datetime
import logging
import json
import os
import re
from django.utils.http import urlquote
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from django.utils.html import escape
from django.utils import translation
from django.utils.translation import ugettext as _
import seaserv
from seaserv import seafile_api
from seahub.base.models import CommandsLastCheck
from seahub.notifications.models import UserNotification
from seahub.utils import send_html_email, get_service_url, \
get_site_scheme_and_netloc
import seahub.settings as settings
from seahub.avatar.templatetags.avatar_tags import avatar
from seahub.avatar.util import get_default_avatar_url
from seahub.base.templatetags.seahub_tags import email2nickname
from seahub.profile.models import Profile
# Get an instance of a logger
logger = logging.getLogger(__name__)
subject = _('New notice on %s') % settings.SITE_NAME
class Command(BaseCommand):
help = 'Send Email notifications to user if he/she has an unread notices every period of seconds .'
label = "notifications_send_notices"
def handle(self, *args, **options):
logger.debug('Start sending user notices...')
self.do_action()
logger.debug('Finish sending user notices.\n')
def get_avatar(self, username, default_size=32):
img_tag = avatar(username, default_size)
pattern = r'src="(.*)"'
repl = r'src="%s\1"' % get_site_scheme_and_netloc()
return re.sub(pattern, repl, img_tag)
def get_avatar_src(self, username, default_size=32):
avatar_img = self.get_avatar(username, default_size)
m = re.search('<img src="(.*?)".*', avatar_img)
if m:
return m.group(1)
else:
return ''
def get_default_avatar(self, default_size=32):
# user default avatar
img_tag = """<img src="%s" width="%s" height="%s" class="avatar" alt="" />""" % \
(get_default_avatar_url(), default_size, default_size)
pattern = r'src="(.*)"'
repl = r'src="%s\1"' % get_site_scheme_and_netloc()
return re.sub(pattern, repl, img_tag)
def get_default_avatar_src(self, default_size=32):
avatar_img = self.get_default_avatar(default_size)
m = re.search('<img src="(.*?)".*', avatar_img)
if m:
return m.group(1)
else:
return ''
def format_priv_file_share_msg(self, notice):
d = json.loads(notice.detail)
priv_share_token = d['priv_share_token']
notice.priv_shared_file_url = reverse('view_priv_shared_file',
args=[priv_share_token])
notice.notice_from = escape(email2nickname(d['share_from']))
notice.priv_shared_file_name = d['file_name']
notice.avatar_src = self.get_avatar_src(d['share_from'])
return notice
def format_user_message(self, notice):
d = notice.user_message_detail_to_dict()
msg_from = d['msg_from']
message = d.get('message')
notice.notice_from = escape(email2nickname(msg_from))
notice.avatar_src = self.get_avatar_src(msg_from)
notice.user_msg_url = reverse('user_msg_list', args=[msg_from])
notice.user_msg = message
return notice
def format_group_message(self, notice):
d = notice.group_message_detail_to_dict()
group_id = d['group_id']
message = d['message']
group = seaserv.get_group(int(group_id))
if group is None:
notice.delete()
notice.group_url = reverse('group_discuss', args=[group.id])
notice.notice_from = escape(email2nickname(d['msg_from']))
notice.group_name = group.group_name
notice.avatar_src = self.get_avatar_src(d['msg_from'])
notice.grp_msg = message
return notice
def format_grpmsg_reply(self, notice):
d = notice.grpmsg_reply_detail_to_dict()
message = d.get('reply_msg')
grpmsg_topic = d.get('grpmsg_topic')
notice.group_msg_reply_url = reverse('msg_reply_new')
notice.notice_from = escape(email2nickname(d['reply_from']))
notice.avatar_src = self.get_avatar_src(d['reply_from'])
notice.grp_reply_msg = message
notice.grpmsg_topic = grpmsg_topic
return notice
def format_repo_share_msg(self, notice):
d = json.loads(notice.detail)
repo_id = d['repo_id']
repo = seafile_api.get_repo(repo_id)
if repo is None:
notice.delete()
notice.repo_url = reverse("view_common_lib_dir", args=[repo_id, '/'])
notice.notice_from = escape(email2nickname(d['share_from']))
notice.repo_name = repo.name
notice.avatar_src = self.get_avatar_src(d['share_from'])
return notice
def format_file_uploaded_msg(self, notice):
d = json.loads(notice.detail)
file_name = d['file_name']
repo_id = d['repo_id']
uploaded_to = d['uploaded_to'].rstrip('/')
file_path = uploaded_to + '/' + file_name
file_link = reverse('view_lib_file', args=[repo_id, urlquote(file_path)])
folder_link = reverse('view_common_lib_dir', args=[repo_id, urlquote(uploaded_to).strip('/')])
folder_name = os.path.basename(uploaded_to)
notice.file_link = file_link
notice.file_name = file_name
notice.folder_link = folder_link
notice.folder_name = folder_name
notice.avatar_src = self.get_default_avatar_src()
return notice
def format_group_join_request(self, notice):
d = json.loads(notice.detail)
username = d['username']
group_id = d['group_id']
join_request_msg = d['join_request_msg']
group = seaserv.get_group(group_id)
if group is None:
notice.delete()
notice.grpjoin_user_profile_url = reverse('user_profile',
args=[username])
notice.grpjoin_group_url = reverse('group_members', args=[group_id])
notice.notice_from = username
notice.grpjoin_group_name = group.group_name
notice.grpjoin_request_msg = join_request_msg
notice.avatar_src = self.get_avatar_src(username)
return notice
def format_add_user_to_group(self, notice):
d = json.loads(notice.detail)
group_staff = d['group_staff']
group_id = d['group_id']
group = seaserv.get_group(group_id)
if group is None:
notice.delete()
notice.notice_from = group_staff
notice.avatar_src = self.get_avatar_src(group_staff)
notice.group_staff_profile_url = reverse('user_profile',
args=[group_staff])
notice.group_url = reverse('view_group', args=[group_id])
notice.group_name = group.group_name
return notice
def get_user_language(self, username):
return Profile.objects.get_user_language(username)
def do_action(self):
now = datetime.datetime.now()
try:
cmd_last_check = CommandsLastCheck.objects.get(command_type=self.label)
logger.debug('Last check time is %s' % cmd_last_check.last_check)
unseen_notices = UserNotification.objects.get_all_notifications(
seen=False, time_since=cmd_last_check.last_check)
logger.debug('Update last check time to %s' % now)
cmd_last_check.last_check = now
cmd_last_check.save()
except CommandsLastCheck.DoesNotExist:
logger.debug('No last check time found, get all unread notices.')
unseen_notices = UserNotification.objects.get_all_notifications(
seen=False)
logger.debug('Create new last check time: %s' % now)
CommandsLastCheck(command_type=self.label, last_check=now).save()
email_ctx = {}
for notice in unseen_notices:
if notice.to_user in email_ctx:
email_ctx[notice.to_user] += 1
else:
email_ctx[notice.to_user] = 1
for to_user, count in email_ctx.items():
# save current language
cur_language = translation.get_language()
# get and active user language
user_language = self.get_user_language(to_user)
translation.activate(user_language)
logger.debug('Set language code to %s for user: %s' % (user_language, to_user))
self.stdout.write('[%s] Set language code to %s' % (
str(datetime.datetime.now()), user_language))
notices = []
for notice in unseen_notices:
logger.info('Processing unseen notice: [%s]' % (notice))
if notice.to_user != to_user:
continue
if notice.is_priv_file_share_msg():
notice = self.format_priv_file_share_msg(notice)
elif notice.is_user_message():
notice = self.format_user_message(notice)
elif notice.is_group_msg():
notice = self.format_group_message(notice)
elif notice.is_grpmsg_reply():
notice = self.format_grpmsg_reply(notice)
elif notice.is_repo_share_msg():
notice = self.format_repo_share_msg(notice)
elif notice.is_file_uploaded_msg():
notice = self.format_file_uploaded_msg(notice)
elif notice.is_group_join_request():
notice = self.format_group_join_request(notice)
elif notice.is_add_user_to_group():
notice = self.format_add_user_to_group(notice)
notices.append(notice)
if not notices:
continue
contact_email = Profile.objects.get_contact_email_by_user(to_user)
to_user = contact_email # use contact email if any
c = {
'to_user': to_user,
'notice_count': count,
'notices': notices,
}
try:
send_html_email(_('New notice on %s') % settings.SITE_NAME,
'notifications/notice_email.html', c,
None, [to_user])
logger.info('Successfully sent email to %s' % to_user)
self.stdout.write('[%s] Successfully sent email to %s' % (str(datetime.datetime.now()), to_user))
except Exception as e:
logger.error('Failed to send email to %s, error detail: %s' % (to_user, e))
self.stderr.write('[%s] Failed to send email to %s, error detail: %s' % (str(datetime.datetime.now()), to_user, e))
# restore current language
translation.activate(cur_language)
<file_sep>/tests/seahub/share/views/test_list_priv_shared_folders.py
# -*- coding: utf-8 -*-
import os
from django.utils.http import urlquote
from django.core.urlresolvers import reverse
from seaserv import seafile_api
from seahub.test_utils import BaseTestCase
class ListPrivSharedFoldersTest(BaseTestCase):
def tearDown(self):
self.remove_repo()
def test_can_list_priv_shared_folders(self):
repo_id = self.repo.id
username = self.user.username
parent_dir = '/'
dirname = '<img onerror=alert(1) src=a>_"_Ω_%2F_W_#_12_这'
full_dir_path = os.path.join(parent_dir, dirname)
# create folder
self.create_folder(repo_id=repo_id,
parent_dir=parent_dir,
dirname=dirname,
username=username)
sub_repo_id = seafile_api.create_virtual_repo(repo_id, full_dir_path, dirname, dirname, username)
seafile_api.share_repo(sub_repo_id, username, self.admin.username, 'rw')
self.login_as(self.user)
resp = self.client.get(reverse('list_priv_shared_folders'))
self.assertEqual(200, resp.status_code)
href = reverse("view_common_lib_dir", args=[repo_id, urlquote(full_dir_path).strip('/')])
self.assertRegexpMatches(resp.content, href)
<file_sep>/seahub/base/accounts.py
# encoding: utf-8
from django import forms
from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site
from seahub.auth.models import get_hexdigest
from seahub.auth import login
from registration import signals
#from registration.forms import RegistrationForm
import seaserv
from seaserv import ccnet_threaded_rpc, unset_repo_passwd, is_passwd_set, \
seafile_api
from seahub.profile.models import Profile, DetailedProfile
from seahub.utils import is_valid_username, is_user_password_strong, \
clear_token
try:
from seahub.settings import CLOUD_MODE
except ImportError:
CLOUD_MODE = False
try:
from seahub.settings import MULTI_TENANCY
except ImportError:
MULTI_TENANCY = False
from constance import config
UNUSABLE_PASSWORD = '!' # This will never be a valid hash
class UserManager(object):
def create_user(self, email, password=<PASSWORD>, is_staff=False, is_active=False):
"""
Creates and saves a User with given username and password.
"""
# Lowercasing email address to avoid confusion.
email = email.lower()
user = User(email=email)
user.is_staff = is_staff
user.is_active = is_active
user.set_password(<PASSWORD>)
user.save()
return self.get(email=email)
def update_role(self, email, role):
"""
If user has a role, update it; or create a role for user.
"""
ccnet_threaded_rpc.update_role_emailuser(email, role)
return self.get(email=email)
def create_superuser(self, email, password):
u = self.create_user(email, password, is_staff=True, is_active=True)
return u
def get_superusers(self):
"""Return a list of admins.
"""
emailusers = ccnet_threaded_rpc.get_superusers()
user_list = []
for e in emailusers:
user = User(e.email)
user.id = e.id
user.is_staff = e.is_staff
user.is_active = e.is_active
user.ctime = e.ctime
user_list.append(user)
return user_list
def get(self, email=None, id=None):
if not email and not id:
raise User.DoesNotExist, 'User matching query does not exits.'
if email:
emailuser = ccnet_threaded_rpc.get_emailuser(email)
if id:
emailuser = ccnet_threaded_rpc.get_emailuser_by_id(id)
if not emailuser:
raise User.DoesNotExist, 'User matching query does not exits.'
user = User(emailuser.email)
user.id = emailuser.id
user.enc_password = <PASSWORD>
user.is_staff = emailuser.is_staff
user.is_active = emailuser.is_active
user.ctime = emailuser.ctime
user.org = emailuser.org
user.source = emailuser.source
user.role = emailuser.role
return user
class UserPermissions(object):
def __init__(self, user):
self.user = user
def can_add_repo(self):
return True
def can_add_group(self):
return True
def can_generate_shared_link(self):
return True
def can_use_global_address_book(self):
return True
def can_view_org(self):
if MULTI_TENANCY:
return True if self.user.org is not None else False
return False if CLOUD_MODE else True
class User(object):
is_staff = False
is_active = False
is_superuser = False
groups = []
org = None
objects = UserManager()
class DoesNotExist(Exception):
pass
def __init__(self, email):
self.username = email
self.email = email
self.permissions = UserPermissions(self)
def __unicode__(self):
return self.username
def is_anonymous(self):
"""
Always returns False. This is a way of comparing User objects to
anonymous users.
"""
return False
def is_authenticated(self):
"""
Always return True. This is a way to tell if the user has been
authenticated in templates.
"""
return True
def save(self):
emailuser = ccnet_threaded_rpc.get_emailuser(self.username)
if emailuser:
if not hasattr(self, 'password'):
self.set_unusable_password()
if emailuser.source == "DB":
source = "DB"
else:
source = "LDAP"
result_code = ccnet_threaded_rpc.update_emailuser(source,
emailuser.id,
self.password,
int(self.is_staff),
int(self.is_active))
else:
result_code = ccnet_threaded_rpc.add_emailuser(self.username,
self.password,
int(self.is_staff),
int(self.is_active))
# -1 stands for failed; 0 stands for success
return result_code
def delete(self):
"""
When delete user, we should also delete group relationships.
"""
if self.source == "DB":
source = "DB"
else:
source = "LDAP"
owned_repos = []
orgs = ccnet_threaded_rpc.get_orgs_by_user(self.username)
if orgs:
for org in orgs:
owned_repos += seafile_api.get_org_owned_repo_list(org.org_id,
self.username)
else:
owned_repos += seafile_api.get_owned_repo_list(self.username)
for r in owned_repos:
seafile_api.remove_repo(r.id)
clear_token(self.username)
ccnet_threaded_rpc.remove_emailuser(source, self.username)
Profile.objects.delete_profile_by_user(self.username)
def get_and_delete_messages(self):
messages = []
return messages
def set_password(self, raw_password):
if raw_password is None:
self.set_unusable_password()
else:
self.password = '%s' % raw_password
def check_password(self, raw_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
"""
# Backwards-compatibility check. Older passwords won't include the
# algorithm or salt.
# if '$' not in self.password:
# is_correct = (self.password == \
# get_hexdigest('sha1', '', raw_password))
# return is_correct
return (ccnet_threaded_rpc.validate_emailuser(self.username, raw_password) == 0)
def set_unusable_password(self):
# Sets a value that will never be a valid hash
self.password = <PASSWORD>
def email_user(self, subject, message, from_email=None):
"Sends an e-mail to this User."
from django.core.mail import send_mail
send_mail(subject, message, from_email, [self.email])
def remove_repo_passwds(self):
"""
Remove all repo decryption passwords stored on server.
"""
from seahub.utils import get_user_repos
owned_repos, shared_repos, groups_repos, public_repos = get_user_repos(self.email)
def has_repo(repos, repo):
for r in repos:
if repo.id == r.id:
return True
return False
passwd_setted_repos = []
for r in owned_repos + shared_repos + groups_repos + public_repos:
if not has_repo(passwd_setted_repos, r) and r.encrypted and \
is_passwd_set(r.id, self.email):
passwd_setted_repos.append(r)
for r in passwd_setted_repos:
unset_repo_passwd(r.id, self.email)
def remove_org_repo_passwds(self, org_id):
"""
Remove all org repo decryption passwords stored on server.
"""
from seahub.utils import get_user_repos
owned_repos, shared_repos, groups_repos, public_repos = get_user_repos(self.email, org_id=org_id)
def has_repo(repos, repo):
for r in repos:
if repo.id == r.id:
return True
return False
passwd_setted_repos = []
for r in owned_repos + shared_repos + groups_repos + public_repos:
if not has_repo(passwd_setted_repos, r) and r.encrypted and \
is_passwd_set(r.id, self.email):
passwd_setted_repos.append(r)
for r in passwd_setted_repos:
unset_repo_passwd(r.id, self.email)
class AuthBackend(object):
def get_user_with_import(self, username):
emailuser = seaserv.get_emailuser_with_import(username)
if not emailuser:
raise User.DoesNotExist, 'User matching query does not exits.'
user = User(emailuser.email)
user.id = emailuser.id
user.enc_password = <PASSWORD>
user.is_staff = emailuser.is_staff
user.is_active = emailuser.is_active
user.ctime = emailuser.ctime
user.org = emailuser.org
user.source = emailuser.source
user.role = emailuser.role
return user
def get_user(self, username):
try:
user = self.get_user_with_import(username)
except User.DoesNotExist:
user = None
return user
def authenticate(self, username=None, password=None):
user = self.get_user(username)
if not user:
return None
if user.check_password(password):
return user
########## Register related
class RegistrationBackend(object):
"""
A registration backend which follows a simple workflow:
1. User signs up, inactive account is created.
2. Email is sent to user with activation link.
3. User clicks activation link, account is now active.
Using this backend requires that
* ``registration`` be listed in the ``INSTALLED_APPS`` setting
(since this backend makes use of models defined in this
application).
* The setting ``ACCOUNT_ACTIVATION_DAYS`` be supplied, specifying
(as an integer) the number of days from registration during
which a user may activate their account (after that period
expires, activation will be disallowed).
* The creation of the templates
``registration/activation_email_subject.txt`` and
``registration/activation_email.txt``, which will be used for
the activation email. See the notes for this backends
``register`` method for details regarding these templates.
Additionally, registration can be temporarily closed by adding the
setting ``REGISTRATION_OPEN`` and setting it to
``False``. Omitting this setting, or setting it to ``True``, will
be interpreted as meaning that registration is currently open and
permitted.
Internally, this is accomplished via storing an activation key in
an instance of ``registration.models.RegistrationProfile``. See
that model and its custom manager for full documentation of its
fields and supported operations.
"""
def register(self, request, **kwargs):
"""
Given a username, email address and password, register a new
user account, which will initially be inactive.
Along with the new ``User`` object, a new
``registration.models.RegistrationProfile`` will be created,
tied to that ``User``, containing the activation key which
will be used for this account.
An email will be sent to the supplied email address; this
email should contain an activation link. The email will be
rendered using two templates. See the documentation for
``RegistrationProfile.send_activation_email()`` for
information about these templates and the contexts provided to
them.
After the ``User`` and ``RegistrationProfile`` are created and
the activation email is sent, the signal
``registration.signals.user_registered`` will be sent, with
the new ``User`` as the keyword argument ``user`` and the
class of this backend as the sender.
"""
email, password = kwargs['email'], kwargs['<PASSWORD>']
username = email
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
from registration.models import RegistrationProfile
if config.ACTIVATE_AFTER_REGISTRATION is True:
# since user will be activated after registration,
# so we will not use email sending, just create acitvated user
new_user = RegistrationProfile.objects.create_active_user(username, email,
password, site,
send_email=False)
# login the user
new_user.backend=settings.AUTHENTICATION_BACKENDS[0]
login(request, new_user)
else:
# create inactive user, user can be activated by admin, or through activated email
new_user = RegistrationProfile.objects.create_inactive_user(username, email,
password, site,
send_email=config.REGISTRATION_SEND_MAIL)
# userid = kwargs['userid']
# if userid:
# ccnet_threaded_rpc.add_binding(new_user.username, userid)
if settings.REQUIRE_DETAIL_ON_REGISTRATION:
name = kwargs.get('name', '')
department = kwargs.get('department', '')
telephone = kwargs.get('telephone', '')
note = kwargs.get('note', '')
Profile.objects.add_or_update(new_user.username, name, note)
DetailedProfile.objects.add_detailed_profile(new_user.username,
department,
telephone)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user
def activate(self, request, activation_key):
"""
Given an an activation key, look up and activate the user
account corresponding to that key (if possible).
After successful activation, the signal
``registration.signals.user_activated`` will be sent, with the
newly activated ``User`` as the keyword argument ``user`` and
the class of this backend as the sender.
"""
from registration.models import RegistrationProfile
activated = RegistrationProfile.objects.activate_user(activation_key)
if activated:
signals.user_activated.send(sender=self.__class__,
user=activated,
request=request)
# login the user
activated.backend=settings.AUTHENTICATION_BACKENDS[0]
login(request, activated)
return activated
def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:
* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.
* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.
"""
return getattr(settings, 'REGISTRATION_OPEN', True)
def get_form_class(self, request):
"""
Return the default form class used for user registration.
"""
return RegistrationForm
def post_registration_redirect(self, request, user):
"""
Return the name of the URL to redirect to after successful
user registration.
"""
return ('registration_complete', (), {})
def post_activation_redirect(self, request, user):
"""
Return the name of the URL to redirect to after successful
account activation.
"""
return ('myhome', (), {})
class RegistrationForm(forms.Form):
"""
Form for registering a new user account.
Validates that the requested email is not already in use, and
requires the password to be entered twice to catch typos.
"""
attrs_dict = { 'class': 'input' }
email = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=75)),
label=_("Email address"))
userid = forms.RegexField(regex=r'^\w+$',
max_length=40,
required=False,
widget=forms.TextInput(),
label=_("Username"),
error_messages={ 'invalid': _("This value must be of length 40") })
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_("Password"))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_("Password (again)"))
def clean_email(self):
email = self.cleaned_data['email']
if not is_valid_username(email):
raise forms.ValidationError(_("Enter a valid email address."))
emailuser = ccnet_threaded_rpc.get_emailuser(email)
if not emailuser:
return self.cleaned_data['email']
else:
raise forms.ValidationError(_("A user with this email already"))
def clean_userid(self):
if self.cleaned_data['userid'] and len(self.cleaned_data['userid']) != 40:
raise forms.ValidationError(_("Invalid user id."))
return self.cleaned_data['userid']
def clean_password1(self):
if '<PASSWORD>' in self.cleaned_data:
pwd = self.cleaned_data['<PASSWORD>']
if config.USER_STRONG_PASSWORD_REQUIRED is True:
if is_user_password_strong(pwd) is True:
return pwd
else:
raise forms.ValidationError(
_(("%(pwd_len)s characters or more, include "
"%(num_types)s types or more of these: "
"letters(case sensitive), numbers, and symbols")) %
{'pwd_len': config.USER_PASSWORD_MIN_LENGTH,
'num_types': config.USER_PASSWORD_STRENGTH_LEVEL})
else:
return pwd
def clean_password2(self):
"""
Verifiy that the values entered into the two password fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.
"""
if '<PASSWORD>' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two password fields didn't match."))
return self.cleaned_data
class DetailedRegistrationForm(RegistrationForm):
attrs_dict = { 'class': 'input' }
try:
from seahub.settings import REGISTRATION_DETAILS_MAP
except:
REGISTRATION_DETAILS_MAP = None
if REGISTRATION_DETAILS_MAP:
name_required = REGISTRATION_DETAILS_MAP.get('name', False)
dept_required = REGISTRATION_DETAILS_MAP.get('department', False)
tele_required = REGISTRATION_DETAILS_MAP.get('telephone', False)
note_required = REGISTRATION_DETAILS_MAP.get('note', False)
else:
# Backward compatible
name_required = dept_required = tele_required = note_required = True
name = forms.CharField(widget=forms.TextInput(
attrs=dict(attrs_dict, maxlength=64)), label=_("name"),
required=name_required)
department = forms.CharField(widget=forms.TextInput(
attrs=dict(attrs_dict, maxlength=512)), label=_("department"),
required=dept_required)
telephone = forms.CharField(widget=forms.TextInput(
attrs=dict(attrs_dict, maxlength=100)), label=_("telephone"),
required=tele_required)
note = forms.CharField(widget=forms.TextInput(
attrs=dict(attrs_dict, maxlength=100)), label=_("note"),
required=note_required)
<file_sep>/fabfile/locale.py
"""
Tools for i18n.
"""
from fabric.api import local, task
from fabric.colors import red, green
@task
def make(default=True):
"""Update source language.
"""
local('django-admin.py makemessages -l en -e py,html -i "thirdpart*" -i "docs*"')
# some version of makemessages will produce "%%" in the string, replace that
# to "%".
_inplace_change('locale/en/LC_MESSAGES/django.po', '%%s', '%s')
_inplace_change('locale/en/LC_MESSAGES/django.po', '%%(', '%(')
local('django-admin.py makemessages -l en -d djangojs -i "thirdpart" -i "node_modules" -i "media" -i "static/scripts/dist" -i "static/scripts/lib" -i "tests" -i "tools" -i "tagging" -i "static/scripts/i18n" --verbosity 2')
@task
def push():
"""Push source file to Transifex.
"""
local('tx push -s')
@task
def pull():
"""Update local po files with Transifex.
"""
local('tx pull')
@task()
def compile():
"""Compile po files.
"""
local('django-admin.py compilemessages')
########## utility functions
def _inplace_change(filename, old_string, new_string):
s = open(filename).read()
if old_string in s:
print(green('Changing "{old_string}" to "{new_string}" in "{filename}"'.format(**locals())))
s = s.replace(old_string, new_string)
f = open(filename, 'w')
f.write(s)
f.flush()
f.close()
def _debug(msg):
print(red('Running: {msg}'.format(**locals())))
<file_sep>/seahub/api2/urls.py
from django.conf.urls.defaults import *
from .views import *
from .views_misc import ServerInfoView
from .views_auth import LogoutDeviceView, ClientLoginTokenView
from .endpoints.dir_shared_items import DirSharedItemsEndpoint
from .endpoints.account import Account
from .endpoints.shared_upload_links import SharedUploadLinksView
from .endpoints.be_shared_repo import BeSharedReposView
urlpatterns = patterns('',
url(r'^ping/$', Ping.as_view()),
url(r'^auth/ping/$', AuthPing.as_view()),
url(r'^auth-token/', ObtainAuthToken.as_view()),
url(r'^server-info/$', ServerInfoView.as_view()),
url(r'^logout-device/$', LogoutDeviceView.as_view()),
url(r'^client-login/$', ClientLoginTokenView.as_view()),
# RESTful API
url(r'^accounts/$', Accounts.as_view(), name="accounts"),
url(r'^accounts/(?P<email>\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/$', Account.as_view(), name="api2-account"),
url(r'^account/info/$', AccountInfo.as_view()),
url(r'^regdevice/$', RegDevice.as_view(), name="regdevice"),
url(r'^search/$', Search.as_view(), name='api_search'),
url(r'^search-user/$', SearchUser.as_view(), name='search-user'),
url(r'^repos/$', Repos.as_view(), name="api2-repos"),
url(r'^repos/public/$', PubRepos.as_view(), name="api2-pub-repos"),
url(r'^repos/(?P<repo_id>[-0-9a-f]{36})/$', Repo.as_view(), name="api2-repo"),
url(r'^repos/(?P<repo_id>[-0-9a-f]{36})/history/$', RepoHistory.as_view()),
url(r'^repos/(?P<repo_id>[-0-9a-f]{36})/download-info/$', DownloadRepo.as_view()),
url(r'^repos/(?P<repo_id>[-0-9a-f]{36})/owner/$', RepoOwner.as_view()),
url(r'^repos/(?P<repo_id>[-0-9a-f]{36})/public/$', RepoPublic.as_view()),
url(r'^repos/(?P<repo_id>[-0-9a-f]{36})/upload-link/$', UploadLinkView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9a-f]{36})/update-link/$', UpdateLinkView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9a-f]{36})/upload-blks-link/$', UploadBlksLinkView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9a-f]{36})/update-blks-link/$', UpdateBlksLinkView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/file/$', FileView.as_view(), name='FileView'),
url(r'^repos/(?P<repo_id>[-0-9a-f]{36})/files/(?P<file_id>[0-9a-f]{40})/blks/(?P<block_id>[0-9a-f]{40})/download-link/$', FileBlockDownloadLinkView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/file/detail/$', FileDetailView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/file/history/$', FileHistory.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/file/revision/$', FileRevision.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/file/revert/$', FileRevert.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/file/shared-link/$', FileSharedLinkView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/dir/$', DirView.as_view(), name='DirView'),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/dir/sub_repo/$', DirSubRepoView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/dir/share/$', DirShareView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/dir/shared_items/$', DirSharedItemsEndpoint.as_view(), name="api2-dir-shared-items"),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/dir/download/$', DirDownloadView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/thumbnail/$', ThumbnailView.as_view(), name='api2-thumbnail'),
url(r'^starredfiles/', StarredFileView.as_view(), name='starredfiles'),
url(r'^shared-repos/$', SharedRepos.as_view(), name='sharedrepos'),
url(r'^shared-repos/(?P<repo_id>[-0-9-a-f]{36})/$', SharedRepo.as_view(), name='sharedrepo'),
url(r'^beshared-repos/$', BeShared.as_view(), name='beshared'),
url(r'^beshared-repos/(?P<repo_id>[-0-9-a-f]{36})/$', BeSharedReposView.as_view(), name='beshared-repos'),
url(r'^default-repo/$', DefaultRepoView.as_view(), name='api2-defaultrepo'),
url(r'^shared-links/$', SharedLinksView.as_view()),
url(r'^shared-upload-links/$', SharedUploadLinksView.as_view()),
url(r'^shared-files/$', SharedFilesView.as_view()),
url(r'^virtual-repos/$', VirtualRepos.as_view()),
url(r'^repo-tokens/$', RepoTokensView.as_view()),
url(r'^organization/$', OrganizationView.as_view()),
url(r'^s/f/(?P<token>[a-f0-9]{10})/$', PrivateSharedFileView.as_view()),
url(r'^s/f/(?P<token>[a-f0-9]{10})/detail/$', PrivateSharedFileDetailView.as_view()),
url(r'^f/(?P<token>[a-f0-9]{10})/$', SharedFileView.as_view()),
url(r'^f/(?P<token>[a-f0-9]{10})/detail/$', SharedFileDetailView.as_view()),
url(r'^d/(?P<token>[a-f0-9]{10})/dir/$', SharedDirView.as_view()),
url(r'^groupandcontacts/$', GroupAndContacts.as_view()),
url(r'^events/$', EventsView.as_view()),
url(r'^repo_history_changes/(?P<repo_id>[-0-9a-f]{36})/$', RepoHistoryChange.as_view()),
url(r'^unseen_messages/$', UnseenMessagesCountView.as_view()),
url(r'^group/msgs/(?P<group_id>\d+)/$', GroupMsgsView.as_view()),
url(r'^group/(?P<group_id>\d+)/msg/(?P<msg_id>\d+)/$', GroupMsgView.as_view()),
url(r'^user/msgs/(?P<id_or_email>[^/]+)/$', UserMsgsView.as_view()),
url(r'^new_replies/$', NewRepliesView.as_view()),
url(r'^avatars/user/(?P<user>\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/resized/(?P<size>[0-9]+)/$', UserAvatarView.as_view()),
url(r'^avatars/group/(?P<group_id>\d+)/resized/(?P<size>[0-9]+)/$', GroupAvatarView.as_view()),
url(r'^groups/$', Groups.as_view()),
url(r'^groups/(?P<group_id>\d+)/$', Groups.as_view()),
url(r'^groups/(?P<group_id>\d+)/members/$', GroupMembers.as_view()),
url(r'^groups/(?P<group_id>\d+)/changes/$', GroupChanges.as_view(), name="api2-group-changes"),
url(r'^groups/(?P<group_id>\d+)/repos/$', GroupRepos.as_view(), name="api2-grouprepos"),
url(r'^groups/(?P<group_id>\d+)/repos/(?P<repo_id>[-0-9a-f]{36})/$', GroupRepo.as_view(), name="api2-grouprepo"),
url(r'^html/events/$', EventsHtml.as_view()),
url(r'^html/more_events/$', AjaxEvents.as_view(), name="more_events"),
url(r'^html/repo_history_changes/(?P<repo_id>[-0-9a-f]{36})/$', RepoHistoryChangeHtml.as_view(), name='api_repo_history_changes'),
url(r'^html/discussions/(?P<group_id>\d+)/$', DiscussionsHtml.as_view(), name="api_discussions"),
url(r'^html/discussion/(?P<msg_id>\d+)/$', DiscussionHtml.as_view(), name="api_discussion"),
url(r'^html/more_discussions/(?P<group_id>\d+)/$', AjaxDiscussions.as_view(), name="more_discussions"),
url(r'^html/newreply/$', NewReplyHtml.as_view()),
url(r'^html/usermsgs/(?P<id_or_email>[^/]+)/$', UserMsgsHtml.as_view()),
url(r'^html/more_usermsgs/(?P<id_or_email>[^/]+)/$', AjaxUserMsgs.as_view(), name="api_more_usermsgs"),
# Folowing is only for debug, will be removed
#url(r'^html/newreply2/$', api_new_replies),
#url(r'^html/events2/$', activity2),
#url(r'^html/more_events/$', events2, name="more_events"),
#url(r'^html/repo_history_changes/(?P<repo_id>[-0-9a-f]{36})/$', api_repo_history_changes, name='api_repo_history_changes'),
#url(r'^html/discussions2/(?P<group_id>\d+)/$', discussions2, name="api_discussions2"),
#url(r'^html/discussion/(?P<msg_id>\d+)/$', discussion2, name="api_discussion2"),
#url(r'^html/more_discussions/(?P<group_id>\d+)/$', more_discussions2, name="more_discussions"),
#url(r'^html/usermsgs2/(?P<id_or_email>[^/]+)/$', api_usermsgs),
#url(r'^html/more_usermsgs/(?P<id_or_email>[^/]+)/$', api_more_usermsgs, name="api_more_usermsgs"),
# Deprecated
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/fileops/delete/$', OpDeleteView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/fileops/copy/$', OpCopyView.as_view()),
url(r'^repos/(?P<repo_id>[-0-9-a-f]{36})/fileops/move/$', OpMoveView.as_view()),
)
# serve office converter static files
from seahub.utils import HAS_OFFICE_CONVERTER
if HAS_OFFICE_CONVERTER:
from seahub.utils import OFFICE_HTML_DIR
urlpatterns += patterns('',
url(r'^office-convert/static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': OFFICE_HTML_DIR}, name='api_office_convert_static'),
)
urlpatterns += patterns('',
url(r'^office-convert/status/$', OfficeConvertQueryStatus.as_view()),
)
urlpatterns += patterns('',
url(r'^office-convert/generate/repos/(?P<repo_id>[-0-9-a-f]{36})/$', OfficeGenerateView.as_view()),
)
from seahub import settings
if getattr(settings, 'ENABLE_OFFICE_WEB_APP', False):
urlpatterns += patterns('',
(r'^wopi/', include('seahub_extra.wopi.urls')),
)
<file_sep>/tests/seahub/views/test_list_lib_dir.py
import json
import os
from django.core.urlresolvers import reverse
from seahub.test_utils import BaseTestCase
class ListLibDirTest(BaseTestCase):
def setUp(self):
self.login_as(self.user)
self.endpoint = reverse('list_lib_dir', args=[self.repo.id])
self.folder_name = os.path.basename(self.folder)
def tearDown(self):
self.remove_repo()
def test_can_list(self):
resp = self.client.get(self.endpoint, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert len(json_resp) == 8
assert self.folder_name == json_resp['dirent_list'][0]['obj_name']
assert self.repo.name == json_resp['repo_name']
<file_sep>/seahub/options/urls.py
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns("",
url(r'^save/$', save_options, name='options_save'),
url(r'^enable_sub_lib/$', sub_lib_enable_set, name='sub_lib_enable_set'),
)
<file_sep>/seahub/templates/file_access.html
{% extends base_template %}
{% load seahub_tags avatar_tags i18n %}
{% load url from future %}
{% block sub_title %}{% trans "Access Log" %} - {% endblock %}
{% block main_panel %}
<h2 class="file-access-hd"><span class="op-target">{{ filename }}</span> {% trans "Access Log" %}</h2>
<div class="file-audit-list-topbar">
<p class="path">
{% trans 'Current Path:' %}
{% for name, link in zipped %}
{% if not forloop.last %}
<a href="{% url 'view_common_lib_dir' repo.id link|urlencode|strip_slash %}">{{ name }}</a> /
{% else %}
<a href="{% url 'view_lib_file' repo.id path|urlencode %}" target="_blank" >{{ name }}</a>
{% endif %}
{% endfor %}
</p>
</div>
{% if events %}
<table class='file-audit-list'>
<tr>
<th width="25%" class="user">{% trans "User" %}</th>
<th width="20%">{% trans "Type" %}</th>
<th width="30%">{% trans "IP" %} / {% trans "Device Name" %}</th>
<th width="25%">{% trans "Date" %}</th>
</tr>
{% for e in events %}
<tr>
<td class="user">
{% avatar e.user 16 %}
{% if e.user %}
<a href="{% url 'user_profile' e.user %}">{{ e.user }}</a>
{% else %}
<span>{% trans "Anonymous User" %}</span>
{% endif %}
</td>
<td><span>{{ e.event_type }}</span></td>
<td>
{% if e.show_device %}
{{ e.ip }} / {{ e.show_device }}
{% else %}
{{ e.ip }}
{% endif %}
</td>
<td>{{ e.time|date:"Y-m-d G:i:s" }}</td>
</tr>
{% endfor %}
</table>
<div id="paginator">
{% if current_page != 1 %}
<a href="?page={{ prev_page }}&per_page={{ per_page }}{{ extra_href }}">{% trans "Previous" %}</a>
{% endif %}
{% if page_next %}
<a href="?page={{ next_page }}&per_page={{ per_page }}{{ extra_href }}">{% trans "Next" %}</a>
{% endif %}
{% if current_page != 1 or page_next %}
|
{% endif %}
<span>{% trans "Per page: " %}</span>
{% if per_page == 25 %}
<span> 25 </span>
{% else %}
<a href="?per_page=25{{ extra_href }}" class="per-page">25</a>
{% endif %}
{% if per_page == 50 %}
<span> 50 </span>
{% else %}
<a href="?per_page=50{{ extra_href }}" class="per-page">50</a>
{% endif %}
{% if per_page == 100 %}
<span> 100 </span>
{% else %}
<a href="?per_page=100{{ extra_href }}" class="per-page">100</a>
{% endif %}
</div>
{% else %}
<div class="empty-tips">
<h2 class="alc">{% trans "This file has (apparently) not been accessed yet" %}</h2>
</div>
{% endif %}
{% endblock %}
<file_sep>/static/scripts/app/views/dirent.js
define([
'jquery',
'underscore',
'backbone',
'common',
'file-tree',
'app/views/share',
'app/views/folder-perm'
], function($, _, Backbone, Common, FileTree, ShareView, FolderPermView) {
'use strict';
app = app || {};
app.globalState = app.globalState || {};
var DirentView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#dirent-tmpl').html()),
renameTemplate: _.template($("#rename-form-template").html()),
mvcpTemplate: _.template($("#mvcp-form-template").html()),
mvProgressTemplate: _.template($("#mv-progress-popup-template").html()),
initialize: function(options) {
this.dirView = options.dirView;
this.dir = this.dirView.dir;
this.listenTo(this.model, "change", this.render);
this.listenTo(this.model, 'remove', this.remove); // for multi dirents: delete, mv
},
render: function() {
var dir = this.dir;
var dirent_path = Common.pathJoin([dir.path, this.model.get('obj_name')]);
var is_pro = app.pageOptions.is_pro;
var file_audit_enabled = app.pageOptions.file_audit_enabled;
this.$el.html(this.template({
dirent: this.model.attributes,
dirent_path: dirent_path,
encoded_path: Common.encodePath(dirent_path),
category: dir.category,
repo_id: dir.repo_id,
is_repo_owner: dir.is_repo_owner,
can_generate_shared_link: app.pageOptions.can_generate_shared_link,
is_pro: is_pro,
file_audit_enabled: file_audit_enabled,
// sync_problem: true when the filename contains forbidden characters in some filesystem
sync_problem: Common.isFilenameProblematicForSyncing(this.model.attributes.obj_name),
repo_encrypted: dir.encrypted
}));
this.$('.file-locked-icon').attr('title', gettext("locked by {placeholder}").replace('{placeholder}', this.model.get('lock_owner_name')));
return this;
},
events: {
'mouseenter': 'highlight',
'mouseleave': 'rmHighlight',
'click .select': 'select',
'click .file-star': 'starFile',
'click .dir-link': 'visitDir',
'click .more-op-icon': 'togglePopup',
'click .edit': 'edit',
'click .share': 'share',
'click .delete': 'del', // 'delete' is a preserve word
'click .rename': 'rename',
'click .mv': 'mvcp',
'click .cp': 'mvcp',
'click .set-folder-permission': 'setFolderPerm',
'click .lock-file': 'lockFile',
'click .unlock-file': 'unlockFile'
},
highlight: function() {
if (!$('.hidden-op:visible').length && !$('#rename-form').length) {
this.$el.addClass('hl').find('.repo-file-op').removeClass('vh');
}
},
rmHighlight: function() {
if (!$('.hidden-op:visible').length && !$('#rename-form').length) {
this.$el.removeClass('hl').find('.repo-file-op').addClass('vh');
}
},
select: function () {
var checkbox = this.$('.checkbox');
checkbox.toggleClass('checkbox-checked');
if (checkbox.hasClass('checkbox-checked')) {
this.model.set({'selected':true}, {silent:true}); // do not trigger the 'change' event.
} else {
this.model.set({'selected':false}, {silent:true});
}
var dirView = this.dirView;
var $dirents_op = dirView.$('#multi-dirents-op');
var toggle_all_checkbox = dirView.$('th .checkbox');
var checked_num = dirView.$('tr:gt(0) .checkbox-checked').length;
if (checked_num > 0) {
$dirents_op.css({'display':'inline'});
} else {
$dirents_op.hide();
}
if (checked_num == dirView.$('tr:gt(0)').length) {
toggle_all_checkbox.addClass('checkbox-checked');
} else {
toggle_all_checkbox.removeClass('checkbox-checked');
}
},
starFile: function() {
var _this = this;
var dir = this.dirView.dir;
var starred = this.model.get('starred');
var options = { repo_id: dir.repo_id };
options.name = starred ? 'unstar_file' : 'star_file';
var filePath = Common.pathJoin([dir.path, this.model.get('obj_name')]);
var url = Common.getUrl(options) + '?file=' + encodeURIComponent(filePath);
$.ajax({
url: url,
dataType: 'json',
cache: false,
success: function () {
if (starred) {
_this.model.set({'starred':false});
} else {
_this.model.set({'starred':true});
}
},
error: function (xhr) {
Common.ajaxErrorHandler(xhr);
}
});
},
visitDir: function () { // todo
// show 'loading'
this.$('.dirent-icon img').attr({
'src': app.config.mediaUrl + 'img/loading-icon.gif',
'alt':''
});
// empty all models
this.dirView.dir.reset();
// update url & dirents
var dir_url = this.$('.dir-link').attr("href");
app.router.navigate(dir_url, {trigger: true}); // offer an url fragment
return false;
},
togglePopup: function () {
var icon = this.$('.more-op-icon'),
popup = this.$('.hidden-op');
if (popup.hasClass('hide')) { // the popup is not shown
popup.css({'left': icon.position().left});
if (icon.offset().top + popup.height() <= $('#main').offset().top + $('#main').height()) {
// below the icon
popup.css('top', icon.position().top + icon.height() + 3);
} else {
popup.css('bottom', icon.parent().outerHeight() - icon.position().top + 3);
}
popup.removeClass('hide');
} else {
popup.addClass('hide');
}
},
edit: function() {
var desktopBus = window.parent.DesktopBus;
var self = this;
Common.getExportedLibraryName(this.dir.repo_id, function(err, libraryName) {
if (desktopBus && !err) {
var event = {
name: 'eyeosCloud.fileOpened',
//path: this.dir.repo_name + this.dir.path + '/' + this.model.get('obj_name')
path: Common.pathJoin([libraryName, self.dir.path, self.model.get('obj_name')])
};
console.log("sending event to desktop", event);
desktopBus.dispatch(event.name, event);
} else {
console.error('No desktopBus present in parent iframe');
}
});
return false;
},
share: function() {
var dir = this.dir,
obj_name = this.model.get('obj_name'),
dirent_path = Common.pathJoin([dir.path, obj_name]);
var options = {
'is_repo_owner': dir.is_repo_owner,
'is_virtual': dir.is_virtual,
'user_perm': this.model.get('perm'),
'repo_id': dir.repo_id,
'repo_encrypted': false,
'is_dir': this.model.get('is_dir') ? true : false,
'dirent_path': dirent_path,
'obj_name': obj_name
};
new ShareView(options);
return false;
},
del: function() {
var dirent_name = this.model.get('obj_name');
var dir = this.dir;
var options = {
repo_id: dir.repo_id,
name: this.model.get('is_dir') ? 'del_dir' : 'del_file'
};
var model = this.model;
$.ajax({
url: Common.getUrl(options) + '?parent_dir=' + encodeURIComponent(dir.path)
+ '&name=' + encodeURIComponent(dirent_name),
type: 'POST',
dataType: 'json',
beforeSend: Common.prepareCSRFToken,
success: function(data) {
dir.remove(model);
var msg = gettext("Successfully deleted %(name)s")
.replace('%(name)s', Common.HTMLescape(dirent_name));
Common.feedback(msg, 'success');
},
error: function(xhr) {
Common.ajaxErrorHandler(xhr);
}
});
return false;
},
rename: function() {
var is_dir = this.model.get('is_dir');
var dirent_name = this.model.get('obj_name');
var form = $(this.renameTemplate({
dirent_name: dirent_name
}));
var $name = this.$('.dirent-name'),
$op = this.$('.dirent-op'),
$td = $name.closest('td');
$td.attr('colspan', 2).css({
'width': $name.width() + $op.outerWidth(),
'height': $name.height()
}).append(form);
$op.hide();
$name.hide();
this.$('.hidden-op').addClass('hide');
var cancelRename = function() {
form.remove();
$op.show();
$name.show();
$td.attr('colspan', 1).css({
'width': $name.width()
});
return false; // stop bubbling (to 'doc click to hide .hidden-op')
};
$('.cancel', form).click(cancelRename);
var form_id = form.attr('id');
var _this = this;
var dir = this.dirView.dir;
form.submit(function() {
var new_name = $.trim($('[name="newname"]', form).val());
if (!new_name) {
return false;
}
if (new_name == dirent_name) {
cancelRename();
return false;
}
// make sure it does not have invalid windows chars
if (Common.isFilenameProblematicForSyncing(new_name)) {
Common.feedback(gettext("The following characters are not supported: Angular brackets \\ / : ? * \" |"), 'error');
return false;
}
var post_data = {
'oldname': dirent_name,
'newname': new_name
};
var post_url = Common.getUrl({
name: is_dir ? 'rename_dir' : 'rename_file',
repo_id: dir.repo_id
}) + '?parent_dir=' + encodeURIComponent(dir.path);
var after_op_success = function (data) {
var renamed_dirent_data = {
'obj_name': data['newname'],
'last_modified': new Date().getTime()/1000,
'last_update': gettext("Just now")
};
if (!is_dir) {
$.extend(renamed_dirent_data, {
'starred': false
});
}
$.modal.close();
_this.model.set(renamed_dirent_data); // it will trigger 'change' event
};
var after_op_error = function(xhr) {
var err_msg;
if (xhr.responseText) {
err_msg = $.parseJSON(xhr.responseText).error;
} else {
err_msg = gettext("Failed. Please check the network.");
}
Common.feedback(err_msg, 'error');
Common.enableButton(submit_btn);
};
var submit_btn = $('[type="submit"]', form);
Common.disableButton(submit_btn);
$.ajax({
url: post_url,
type: 'POST',
dataType: 'json',
beforeSend: Common.prepareCSRFToken,
data: post_data,
success: after_op_success,
error: after_op_error
});
return false;
});
return false;
},
mvcp: function(event) {
var dir = this.dir;
var el = event.target || event.srcElement,
op_type = $(el).hasClass('mv') ? 'mv' : 'cp',
obj_name = this.model.get('obj_name'),
obj_type = this.model.get('is_dir') ? 'dir' : 'file';
var title = op_type == 'mv' ? gettext("Move {placeholder} to:") : gettext("Copy {placeholder} to:");
title = title.replace('{placeholder}', '<span class="op-target ellipsis ellipsis-op-target" title="' + Common.HTMLescape(obj_name) + '">' + Common.HTMLescape(obj_name) + '</span>');
var show_cur_repo = true;
if (this.model.get('perm') == 'r') {
show_cur_repo = false;
}
var form = $(this.mvcpTemplate({
form_title: title,
op_type: op_type,
obj_type: obj_type,
obj_name: obj_name,
show_cur_repo: show_cur_repo,
show_other_repos: !dir.encrypted
}));
form.modal({appendTo:'#main', autoResize:true, focus:false});
$('#simplemodal-container').css({'width':'auto', 'height':'auto'});
if (show_cur_repo) {
FileTree.renderTreeForPath({
repo_name: dir.repo_name,
repo_id: dir.repo_id,
path: dir.path
});
}
if (!dir.encrypted) {
FileTree.prepareOtherReposTree({cur_repo_id: dir.repo_id});
}
var dirent = this.$el;
var _this = this;
form.submit(function() {
var form = $(this),
form_id = form.attr('id'),
path = dir.path,
repo_id = dir.repo_id;
var dst_repo = $('[name="dst_repo"]', form).val(),
dst_path = $('[name="dst_path"]', form).val(),
op = $('[name="op"]', form).val(),
obj_name = $('[name="obj_name"]', form).val(),
obj_type = $('[name="obj_type"]', form).val();
if (!$.trim(dst_repo) || !$.trim(dst_path)) {
$('.error', form).removeClass('hide');
return false;
}
if (dst_repo == repo_id && (dst_path == path || (obj_type == 'dir' && dst_path == path + obj_name + '/'))) {
$('.error', form).html(gettext("Invalid destination path")).removeClass('hide');
return false;
}
var options = { repo_id: repo_id };
if (obj_type == 'dir') {
options.name = op == 'mv' ? 'mv_dir' : 'cp_dir';
} else {
options.name = op == 'mv' ? 'mv_file' : 'cp_file';
}
var post_url = Common.getUrl(options) + '?path=' + encodeURIComponent(path) + '&obj_name=' + encodeURIComponent(obj_name);
var post_data = {
'dst_repo': dst_repo,
'dst_path': dst_path
};
var after_op_success = function(data) {
$.modal.close();
var msg = data['msg'];
if (!data['task_id']) { // no progress
if (op == 'mv') {
dirent.remove();
}
Common.feedback(msg, 'success');
} else {
var mv_progress_popup = $(_this.mvProgressTemplate());
var details = $('#mv-details', mv_progress_popup),
cancel_btn = $('#cancel-mv', mv_progress_popup),
other_info = $('#mv-other-info', mv_progress_popup);
cancel_btn.removeClass('hide');
setTimeout(function () {
mv_progress_popup.modal({containerCss: {
width: 300,
height: 150,
paddingTop: 50
}, focus:false});
var det_text = op == 'mv' ? gettext("Moving %(name)s") : gettext("Copying %(name)s");
details.html(det_text.replace('%(name)s', Common.HTMLescape(obj_name))).removeClass('vh');
$('#mv-progress').progressbar();
req_progress();
}, 100);
var req_progress = function () {
$.ajax({
url: Common.getUrl({name: 'get_cp_progress'}) + '?task_id=' + encodeURIComponent(data['task_id']),
dataType: 'json',
success: function(data) {
var bar = $('.ui-progressbar-value', $('#mv-progress'));
if (!data['failed'] && !data['canceled'] && !data['successful']) {
if (data['done'] == data['total']) {
bar.css('width', '100%'); // 'done' and 'total' can be both 0
details.addClass('vh');
cancel_btn.addClass('hide');
other_info.html(gettext("Saving...")).removeClass('hide');
} else {
bar.css('width', parseInt(data['done']/data['total']*100, 10) + '%');
}
bar.show();
setTimeout(req_progress, 1000);
} else if (data['successful']) {
$.modal.close();
if (op == 'mv') {
dirent.remove();
}
Common.feedback(msg, 'success');
} else { // failed or canceled
details.addClass('vh');
var other_msg = data['failed'] ? gettext("Failed.") : gettext("Canceled.");
other_info.html(other_msg).removeClass('hide');
cancel_btn.addClass('hide');
setTimeout(function () { $.modal.close(); }, 1000);
}
},
error: function(xhr, textStatus, errorThrown) {
var error;
if (xhr.responseText) {
error = $.parseJSON(xhr.responseText).error;
} else {
error = gettext("Failed. Please check the network.");
}
details.addClass('vh')
other_info.html(error).removeClass('hide');
cancel_btn.addClass('hide');
setTimeout(function () { $.modal.close(); }, 1000);
}
});
};
cancel_btn.click(function() {
Common.disableButton(cancel_btn);
$.ajax({
url: Common.getUrl({name: 'cancel_cp'}) + '?task_id=' + encodeURIComponent(data['task_id']),
dataType: 'json',
success: function(data) {
details.addClass('vh')
other_info.html(gettext("Canceled.")).removeClass('hide');
cancel_btn.addClass('hide');
setTimeout(function () {$.modal.close();}, 1000);
},
error: function(xhr, textStatus, errorThrown) {
var error;
if (xhr.responseText) {
error = $.parseJSON(xhr.responseText).error;
} else {
error = gettext("Failed. Please check the network.");
}
other_info.html(error).removeClass('hide');
Common.enableButton(cancel_btn);
}
});
});
}
}
Common.ajaxPost({
'form': form,
'post_url': post_url,
'post_data': post_data,
'after_op_success': after_op_success,
'form_id': form_id
});
return false;
});
return false;
},
setFolderPerm: function() {
var options = {
'obj_name': this.model.get('obj_name'),
'dir_path': this.dir.path,
'repo_id': this.dir.repo_id
};
new FolderPermView(options);
return false;
},
lockOrUnlockFile: function(params) {
var dir = this.dir,
filepath = Common.pathJoin([dir.path, this.model.get('obj_name')]),
callback = params.after_success;
$.ajax({
url: Common.getUrl({name: 'lock_or_unlock_file', repo_id: dir.repo_id}),
type: 'PUT',
dataType: 'json',
data: {
'operation': params.op,
'p': filepath
},
cache: false,
beforeSend: Common.prepareCSRFToken,
success: function() {
callback();
},
error: function (xhr) {
Common.ajaxErrorHandler(xhr);
}
});
},
lockFile: function() {
var _this = this;
this.lockOrUnlockFile({
'op': 'lock',
'after_success': function() {
_this.model.set({
'is_locked': true,
'locked_by_me': true,
'lock_owner_name': app.pageOptions.name
});
_this.$el.removeClass('hl');
}
});
return false;
},
unlockFile: function() {
var _this = this;
this.lockOrUnlockFile({
'op': 'unlock',
'after_success': function() {
_this.model.set({
'is_locked': false
});
_this.$el.removeClass('hl');
}
});
return false;
}
});
return DirentView;
});
<file_sep>/seahub/api2/permissions.py
"""
Provides a set of pluggable permission policies.
"""
from rest_framework.permissions import BasePermission
from seaserv import check_permission, is_repo_owner
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class IsRepoWritable(BasePermission):
"""
Allows access only for user who has write permission to the repo.
"""
def has_permission(self, request, view, obj=None):
if request.method in SAFE_METHODS:
return True
repo_id = view.kwargs.get('repo_id', '')
user = request.user.username if request.user else ''
if user and check_permission(repo_id, user) == 'rw':
return True
return False
class IsRepoAccessible(BasePermission):
"""
Check whether user has Read or Write permission to a repo.
"""
def has_permission(self, request, view, obj=None):
repo_id = view.kwargs.get('repo_id', '')
user = request.user.username if request.user else ''
return True if check_permission(repo_id, user) else False
class IsRepoOwner(BasePermission):
"""
Check whether user is the owner of a repo.
"""
def has_permission(self, request, view, obj=None):
repo_id = view.kwargs.get('repo_id', '')
user = request.user.username if request.user else ''
return True if is_repo_owner(user, repo_id) else False
<file_sep>/seahub/views/__init__.py
# encoding: utf-8
import hashlib
import os
import stat
import json
import mimetypes
import urllib2
import logging
from math import ceil
import posixpath
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.http import HttpResponse, HttpResponseBadRequest, Http404, \
HttpResponseRedirect
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.utils import timezone
from django.utils.http import urlquote
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.views.decorators.http import condition
import seaserv
from seaserv import get_repo, get_commits, is_valid_filename, \
seafserv_threaded_rpc, seafserv_rpc, is_repo_owner, check_permission, \
is_passwd_set, get_file_size, get_group, get_session_info, get_commit, \
MAX_DOWNLOAD_DIR_SIZE, send_message, ccnet_threaded_rpc, \
get_personal_groups_by_user, seafile_api
from pysearpc import SearpcError
from seahub.avatar.util import get_avatar_file_storage
from seahub.auth.decorators import login_required, login_required_ajax
from seahub.auth import login as auth_login
from seahub.auth import get_backends
from seahub.base.accounts import User
from seahub.base.decorators import user_mods_check, require_POST
from seahub.base.models import UserStarredFiles, ClientLoginToken
from seahub.contacts.models import Contact
from seahub.options.models import UserOptions, CryptoOptionNotSetError
from seahub.profile.models import Profile
from seahub.share.models import FileShare, PrivateFileDirShare, \
UploadLinkShare
from seahub.forms import RepoPassowrdForm
from seahub.utils import render_permission_error, render_error, list_to_string, \
get_fileserver_root, gen_shared_upload_link, is_org_context, \
gen_dir_share_link, gen_file_share_link, get_repo_last_modify, \
calculate_repos_last_modify, get_file_type_and_ext, get_user_repos, \
EMPTY_SHA1, normalize_file_path, gen_file_upload_url, \
get_file_revision_id_size, get_ccnet_server_addr_port, \
gen_file_get_url, string2list, MAX_INT, IS_EMAIL_CONFIGURED, \
EVENTS_ENABLED, get_user_events, get_org_user_events, show_delete_days, \
TRAFFIC_STATS_ENABLED, get_user_traffic_stat, new_merge_with_no_conflict, \
user_traffic_over_limit, send_perm_audit_msg, get_origin_repo_info, \
get_max_upload_file_size, is_pro_version, FILE_AUDIT_ENABLED, \
is_org_repo_creation_allowed
from seahub.utils.paginator import get_page_range
from seahub.utils.star import get_dir_starred_files
from seahub.utils.timeutils import utc_to_local
from seahub.views.modules import MOD_PERSONAL_WIKI, enable_mod_for_user, \
disable_mod_for_user
from seahub.utils.devices import get_user_devices, do_unlink_device
import seahub.settings as settings
from seahub.settings import FILE_PREVIEW_MAX_SIZE, INIT_PASSWD, USE_PDFJS, \
FILE_ENCODING_LIST, FILE_ENCODING_TRY_LIST, AVATAR_FILE_STORAGE, \
SEND_EMAIL_ON_ADDING_SYSTEM_MEMBER, SEND_EMAIL_ON_RESETTING_USER_PASSWD, \
ENABLE_SUB_LIBRARY, ENABLE_FOLDER_PERM
from constance import config
# Get an instance of a logger
logger = logging.getLogger(__name__)
def validate_owner(request, repo_id):
"""
Check whether user in the request owns the repo.
"""
ret = is_repo_owner(request.user.username, repo_id)
return True if ret else False
def is_registered_user(email):
"""
Check whether user is registerd.
"""
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
user = None
return True if user else False
_default_repo_id = None
def get_system_default_repo_id():
global _default_repo_id
if not _default_repo_id:
try:
_default_repo_id = seaserv.seafserv_threaded_rpc.get_system_default_repo_id()
except SearpcError as e:
logger.error(e)
return _default_repo_id
def check_folder_permission(request, repo_id, path):
"""Check repo/folder access permission of a user, always return 'rw'
when repo is system repo and user is admin.
Arguments:
- `request`:
- `repo_id`:
- `path`:
"""
username = request.user.username
if request.user.is_staff and get_system_default_repo_id() == repo_id:
return 'rw'
return seafile_api.check_permission_by_path(repo_id, path, username)
def check_file_permission(request, repo_id, path):
"""Check file access permission of a user, always return 'rw'
when repo is system repo and user is admin.
Arguments:
- `request`:
- `repo_id`:
- `path`:
"""
username = request.user.username
if get_system_default_repo_id() == repo_id and request.user.is_staff:
return 'rw'
return seafile_api.check_permission_by_path(repo_id, path, username)
def check_file_lock(repo_id, file_path, username):
""" check if file is locked to current user
according to returned value of seafile_api.check_file_lock:
0: not locked
1: locked by other
2: locked by me
-1: error
return (is_locked, locked_by_me)
"""
try:
return_value = seafile_api.check_file_lock(repo_id,
file_path.lstrip('/'), username)
except SearpcError as e:
logger.error(e)
return (None, None)
if return_value == 0:
return (False, False)
elif return_value == 1:
return (True , False)
elif return_value == 2:
return (True, True)
else:
return (None, None)
def check_repo_access_permission(repo_id, user):
"""Check repo access permission of a user, always return 'rw' when repo is
system repo and user is admin.
Arguments:
- `repo_id`:
- `user`:
"""
if user.is_staff and get_system_default_repo_id() == repo_id:
return 'rw'
else:
return seafile_api.check_repo_access_permission(repo_id, user.username)
def get_file_access_permission(repo_id, path, username):
"""Check user has permission to view the file.
1. check whether this file is private shared.
2. if failed, check whether the parent of this directory is private shared.
"""
pfs = PrivateFileDirShare.objects.get_private_share_in_file(username,
repo_id, path)
if pfs is None:
dirs = PrivateFileDirShare.objects.list_private_share_in_dirs_by_user_and_repo(username, repo_id)
for e in dirs:
if path.startswith(e.path):
return e.permission
return None
else:
return pfs.permission
def gen_path_link(path, repo_name):
"""
Generate navigate paths and links in repo page.
"""
if path and path[-1] != '/':
path += '/'
paths = []
links = []
if path and path != '/':
paths = path[1:-1].split('/')
i = 1
for name in paths:
link = '/' + '/'.join(paths[:i])
i = i + 1
links.append(link)
if repo_name:
paths.insert(0, repo_name)
links.insert(0, '/')
zipped = zip(paths, links)
return zipped
def get_file_download_link(repo_id, obj_id, path):
"""Generate file download link.
Arguments:
- `repo_id`:
- `obj_id`:
- `filename`:
"""
return reverse('download_file', args=[repo_id, obj_id]) + '?p=' + \
urlquote(path)
def get_repo_dirents(request, repo, commit, path, offset=-1, limit=-1):
"""List repo dirents based on commit id and path. Use ``offset`` and
``limit`` to do paginating.
Returns: A tupple of (file_list, dir_list, dirent_more)
TODO: Some unrelated parts(file sharing, stars, modified info, etc) need
to be pulled out to multiple functions.
"""
dir_list = []
file_list = []
dirent_more = False
if commit.root_id == EMPTY_SHA1:
return ([], [], False) if limit == -1 else ([], [], False)
else:
try:
dirs = seafile_api.list_dir_by_commit_and_path(commit.repo_id,
commit.id, path,
offset, limit)
if not dirs:
return ([], [], False)
except SearpcError as e:
logger.error(e)
return ([], [], False)
if limit != -1 and limit == len(dirs):
dirent_more = True
username = request.user.username
starred_files = get_dir_starred_files(username, repo.id, path)
fileshares = FileShare.objects.filter(repo_id=repo.id).filter(username=username)
uploadlinks = UploadLinkShare.objects.filter(repo_id=repo.id).filter(username=username)
view_dir_base = reverse("view_common_lib_dir", args=[repo.id, '/'])
dl_dir_base = reverse('repo_download_dir', args=[repo.id])
file_history_base = reverse('file_revisions', args=[repo.id])
for dirent in dirs:
dirent.last_modified = dirent.mtime
dirent.sharelink = ''
dirent.uploadlink = ''
if stat.S_ISDIR(dirent.props.mode):
dpath = posixpath.join(path, dirent.obj_name)
if dpath[-1] != '/':
dpath += '/'
for share in fileshares:
if dpath == share.path:
dirent.sharelink = gen_dir_share_link(share.token)
dirent.sharetoken = share.token
break
for link in uploadlinks:
if dpath == link.path:
dirent.uploadlink = gen_shared_upload_link(link.token)
dirent.uploadtoken = link.token
break
p_dpath = posixpath.join(path, dirent.obj_name)
dirent.view_link = view_dir_base + '?p=' + urlquote(p_dpath)
dirent.dl_link = dl_dir_base + '?p=' + urlquote(p_dpath)
dir_list.append(dirent)
else:
file_list.append(dirent)
if repo.version == 0:
dirent.file_size = get_file_size(repo.store_id, repo.version, dirent.obj_id)
else:
dirent.file_size = dirent.size
dirent.starred = False
fpath = posixpath.join(path, dirent.obj_name)
p_fpath = posixpath.join(path, dirent.obj_name)
dirent.view_link = reverse('view_lib_file', args=[repo.id, urlquote(p_fpath)])
dirent.dl_link = get_file_download_link(repo.id, dirent.obj_id,
p_fpath)
dirent.history_link = file_history_base + '?p=' + urlquote(p_fpath)
if fpath in starred_files:
dirent.starred = True
for share in fileshares:
if fpath == share.path:
dirent.sharelink = gen_file_share_link(share.token)
dirent.sharetoken = share.token
break
return (file_list, dir_list, dirent_more)
def get_unencry_rw_repos_by_user(request):
"""Get all unencrypted repos the user can read and write.
"""
username = request.user.username
def has_repo(repos, repo):
for r in repos:
if repo.id == r.id:
return True
return False
org_id = request.user.org.org_id if is_org_context(request) else None
owned_repos, shared_repos, groups_repos, public_repos = get_user_repos(
username, org_id=org_id)
accessible_repos = []
for r in owned_repos:
if not has_repo(accessible_repos, r) and not r.encrypted:
accessible_repos.append(r)
for r in shared_repos + groups_repos + public_repos:
if not has_repo(accessible_repos, r) and not r.encrypted:
if seafile_api.check_repo_access_permission(r.id, username) == 'rw':
accessible_repos.append(r)
return accessible_repos
def render_recycle_root(request, repo_id):
repo = get_repo(repo_id)
if not repo:
raise Http404
scan_stat = request.GET.get('scan_stat', None)
try:
deleted_entries = seafile_api.get_deleted(repo_id, 0, '/', scan_stat)
except SearpcError as e:
logger.error(e)
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
return HttpResponseRedirect(next)
if not deleted_entries:
new_scan_stat = None
else:
new_scan_stat = deleted_entries[-1].scan_stat
trash_more = True if new_scan_stat is not None else False
deleted_entries = deleted_entries[0:-1]
for dirent in deleted_entries:
if stat.S_ISDIR(dirent.mode):
dirent.is_dir = True
else:
dirent.is_dir = False
# Entries sort by deletion time in descending order.
deleted_entries.sort(lambda x, y : cmp(y.delete_time,
x.delete_time))
username = request.user.username
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
is_repo_owner = True if repo_owner == username else False
enable_clean = False
if is_repo_owner:
enable_clean = True
return render_to_response('repo_dir_recycle_view.html', {
'show_recycle_root': True,
'repo': repo,
'repo_dir_name': repo.name,
'dir_entries': deleted_entries,
'scan_stat': new_scan_stat,
'trash_more': trash_more,
'enable_clean': enable_clean,
}, context_instance=RequestContext(request))
def render_recycle_dir(request, repo_id, commit_id):
basedir = request.GET.get('base', '')
path = request.GET.get('p', '')
if not basedir or not path:
return render_recycle_root(request, repo_id)
if basedir[0] != '/':
basedir = '/' + basedir
if path[-1] != '/':
path += '/'
repo = get_repo(repo_id)
if not repo:
raise Http404
try:
commit = seafserv_threaded_rpc.get_commit(repo.id, repo.version, commit_id)
except SearpcError as e:
logger.error(e)
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
return HttpResponseRedirect(next)
if not commit:
raise Http404
zipped = gen_path_link(path, '')
dir_entries = seafile_api.list_dir_by_commit_and_path(commit.repo_id,
commit.id, basedir+path,
-1, -1)
for dirent in dir_entries:
if stat.S_ISDIR(dirent.mode):
dirent.is_dir = True
else:
dirent.is_dir = False
return render_to_response('repo_dir_recycle_view.html', {
'show_recycle_root': False,
'repo': repo,
'repo_dir_name': repo.name,
'zipped': zipped,
'dir_entries': dir_entries,
'commit_id': commit_id,
'basedir': basedir,
'path': path,
}, context_instance=RequestContext(request))
def render_dir_recycle_root(request, repo_id, dir_path):
repo = get_repo(repo_id)
if not repo:
raise Http404
scan_stat = request.GET.get('scan_stat', None)
try:
deleted_entries = seafile_api.get_deleted(repo_id, 0, dir_path, scan_stat)
except SearpcError as e:
logger.error(e)
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
return HttpResponseRedirect(next)
if not deleted_entries:
new_scan_stat = None
else:
new_scan_stat = deleted_entries[-1].scan_stat
trash_more = True if new_scan_stat is not None else False
deleted_entries = deleted_entries[0:-1]
for dirent in deleted_entries:
if stat.S_ISDIR(dirent.mode):
dirent.is_dir = True
else:
dirent.is_dir = False
# Entries sort by deletion time in descending order.
deleted_entries.sort(lambda x, y : cmp(y.delete_time,
x.delete_time))
return render_to_response('repo_dir_recycle_view.html', {
'show_recycle_root': True,
'repo': repo,
'repo_dir_name': os.path.basename(dir_path.rstrip('/')),
'dir_entries': deleted_entries,
'scan_stat': new_scan_stat,
'trash_more': trash_more,
'dir_path': dir_path,
}, context_instance=RequestContext(request))
def render_dir_recycle_dir(request, repo_id, commit_id, dir_path):
basedir = request.GET.get('base', '')
path = request.GET.get('p', '')
if not basedir or not path:
return render_dir_recycle_root(request, repo_id, dir_path)
if basedir[0] != '/':
basedir = '/' + basedir
if path[-1] != '/':
path += '/'
repo = get_repo(repo_id)
if not repo:
raise Http404
try :
commit = seafserv_threaded_rpc.get_commit(repo.id, repo.version, commit_id)
except SearpcError as e:
logger.error(e)
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
return HttpResponseRedirect(next)
if not commit:
raise Http404
zipped = gen_path_link(path, '')
dir_entries = seafile_api.list_dir_by_commit_and_path(commit.repo_id,
commit.id, basedir+path,
-1, -1)
for dirent in dir_entries:
if stat.S_ISDIR(dirent.mode):
dirent.is_dir = True
else:
dirent.is_dir = False
return render_to_response('repo_dir_recycle_view.html', {
'show_recycle_root': False,
'repo': repo,
'repo_dir_name': os.path.basename(dir_path.rstrip('/')),
'zipped': zipped,
'dir_entries': dir_entries,
'commit_id': commit_id,
'basedir': basedir,
'path': path,
'dir_path': dir_path,
}, context_instance=RequestContext(request))
@login_required
def repo_recycle_view(request, repo_id):
if not seafile_api.get_dir_id_by_path(repo_id, '/') or \
check_folder_permission(request, repo_id, '/') != 'rw':
return render_permission_error(request, _(u'Unable to view recycle page'))
commit_id = request.GET.get('commit_id', '')
if not commit_id:
return render_recycle_root(request, repo_id)
else:
return render_recycle_dir(request, repo_id, commit_id)
@login_required
def dir_recycle_view(request, repo_id):
dir_path = request.GET.get('dir_path', '')
if not seafile_api.get_dir_id_by_path(repo_id, dir_path) or \
check_folder_permission(request, repo_id, dir_path) != 'rw':
return render_permission_error(request, _(u'Unable to view recycle page'))
commit_id = request.GET.get('commit_id', '')
if not commit_id:
return render_dir_recycle_root(request, repo_id, dir_path)
else:
return render_dir_recycle_dir(request, repo_id, commit_id, dir_path)
@login_required
def repo_online_gc(request, repo_id):
if request.method != 'POST':
raise Http404
repo = get_repo(repo_id)
if not repo:
raise Http404
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
username = request.user.username
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
is_repo_owner = True if repo_owner == username else False
if not is_repo_owner:
messages.error(request, _('Permission denied'))
return HttpResponseRedirect(next)
day = int(request.POST.get('day'))
try:
seafile_api.clean_up_repo_history(repo.id, day)
except SearpcError as e:
logger.error(e)
messages.error(request, _('Internal server error'))
return HttpResponseRedirect(next)
return HttpResponseRedirect(next)
def can_access_repo_setting(request, repo_id, username):
repo = seafile_api.get_repo(repo_id)
if not repo:
return (False, None)
# no settings for virtual repo
if ENABLE_SUB_LIBRARY and repo.is_virtual:
return (False, None)
# check permission
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo_id)
else:
repo_owner = seafile_api.get_repo_owner(repo_id)
is_owner = True if username == repo_owner else False
if not is_owner:
return (False, None)
return (True, repo)
@login_required
def repo_basic_info(request, repo_id):
"""List and change library basic info.
"""
username = request.user.username
can_access, repo = can_access_repo_setting(request, repo_id, username)
if not can_access:
raise Http404
history_limit = seaserv.get_repo_history_limit(repo.id)
full_history_checked = no_history_checked = partial_history_checked = False
if history_limit > 0:
partial_history_checked = True
elif history_limit == 0:
no_history_checked = True
else:
full_history_checked = True
full_history_enabled = no_history_enabled = partial_history_enabled = True
days_enabled = True
if not config.ENABLE_REPO_HISTORY_SETTING:
full_history_enabled = no_history_enabled = partial_history_enabled = False
days_enabled = False
if history_limit <= 0:
days_enabled = False
return render_to_response('repo_basic_info.html', {
'repo': repo,
'history_limit': history_limit if history_limit > 0 else '',
'full_history_checked': full_history_checked,
'no_history_checked': no_history_checked,
'partial_history_checked': partial_history_checked,
'full_history_enabled': full_history_enabled,
'no_history_enabled': no_history_enabled,
'partial_history_enabled': partial_history_enabled,
'days_enabled': days_enabled,
'ENABLE_FOLDER_PERM': ENABLE_FOLDER_PERM,
}, context_instance=RequestContext(request))
@login_required
def repo_transfer_owner(request, repo_id):
"""Show transfer repo owner page.
"""
username = request.user.username
can_access, repo = can_access_repo_setting(request, repo_id, username)
if not can_access:
raise Http404
return render_to_response('repo_transfer_owner.html', {
'repo': repo,
'ENABLE_FOLDER_PERM': ENABLE_FOLDER_PERM,
}, context_instance=RequestContext(request))
def repo_transfer_success(request, repo_id):
repo = get_repo(repo_id)
if not repo:
raise Http404
return render_to_response('repo_transfer_success.html', {
'repo': repo,
}, context_instance=RequestContext(request))
@login_required
def repo_change_password(request, repo_id):
"""Show change library password page.
"""
username = request.user.username
can_access, repo = can_access_repo_setting(request, repo_id, username)
if not can_access:
raise Http404
return render_to_response('repo_change_password.html', {
'repo': repo,
'repo_password_min_length': config.REPO_PASSWORD_MIN_LENGTH,
'ENABLE_FOLDER_PERM': ENABLE_FOLDER_PERM,
}, context_instance=RequestContext(request))
@login_required
def repo_shared_link(request, repo_id):
"""List and change library shared links.
"""
username = request.user.username
can_access, repo = can_access_repo_setting(request, repo_id, username)
if not can_access:
raise Http404
# download links
fileshares = FileShare.objects.filter(repo_id=repo_id)
p_fileshares = []
for fs in fileshares:
if fs.is_file_share_link():
if seafile_api.get_file_id_by_path(repo.id, fs.path) is None:
fs.delete()
continue
fs.filename = os.path.basename(fs.path)
fs.shared_link = gen_file_share_link(fs.token)
path = fs.path.rstrip('/') # Normalize file path
obj_id = seafile_api.get_file_id_by_path(repo.id, path)
fs.filesize = seafile_api.get_file_size(repo.store_id, repo.version,
obj_id)
else:
if seafile_api.get_dir_id_by_path(repo.id, fs.path) is None:
fs.delete()
continue
if fs.path != '/':
fs.filename = os.path.basename(fs.path.rstrip('/'))
else:
fs.filename = fs.path
fs.shared_link = gen_dir_share_link(fs.token)
path = fs.path
if path[-1] != '/': # Normalize dir path
path += '/'
#get dir size
dir_id = seafserv_threaded_rpc.get_dirid_by_path(
repo.id, repo.head_cmmt_id, path)
fs.filesize = seafserv_threaded_rpc.get_dir_size(repo.store_id,
repo.version, dir_id)
p_fileshares.append(fs)
# upload links
uploadlinks = UploadLinkShare.objects.filter(repo_id=repo_id)
p_uploadlinks = []
for link in uploadlinks:
if seafile_api.get_dir_id_by_path(repo.id, link.path) is None:
link.delete()
continue
if link.path != '/':
link.dir_name = os.path.basename(link.path.rstrip('/'))
else:
link.dir_name = link.path
link.shared_link = gen_shared_upload_link(link.token)
p_uploadlinks.append(link)
return render_to_response('repo_shared_link.html', {
'repo': repo,
'fileshares': p_fileshares,
'uploadlinks': p_uploadlinks,
'ENABLE_FOLDER_PERM': ENABLE_FOLDER_PERM,
}, context_instance=RequestContext(request))
@login_required
def repo_share_manage(request, repo_id):
"""Manage share of this library.
"""
username = request.user.username
can_access, repo = can_access_repo_setting(request, repo_id, username)
if not can_access:
raise Http404
# sharing management
repo_share_user = []
repo_share_group = []
if is_org_context(request):
org_id = request.user.org.org_id
repo_share_user = seafile_api.get_org_share_out_repo_list(org_id, username, -1, -1)
repo_share_group = seafserv_threaded_rpc.get_org_group_repos_by_owner(org_id, username)
else:
repo_share_user = seafile_api.get_share_out_repo_list(username, -1, -1)
repo_share_group = seaserv.get_group_repos_by_owner(username)
repo_share_user = filter(lambda i: i.repo_id == repo_id, repo_share_user)
repo_share_group = filter(lambda i: i.repo_id == repo_id, repo_share_group)
for share in repo_share_group:
share.group_name = get_group(share.group_id).group_name
return render_to_response('repo_share_manage.html', {
'repo': repo,
'repo_share_user': repo_share_user,
'repo_share_group': repo_share_group,
'ENABLE_FOLDER_PERM': ENABLE_FOLDER_PERM,
}, context_instance=RequestContext(request))
@login_required
def repo_folder_perm(request, repo_id):
"""Manage folder permmission of this library.
"""
username = request.user.username
can_access, repo = can_access_repo_setting(request, repo_id, username)
if not can_access or not ENABLE_FOLDER_PERM:
raise Http404
def not_need_delete(perm):
repo_id = perm.repo_id
path = perm.path
group_id = perm.group_id if hasattr(perm, 'group_id') else None
email = perm.user if hasattr(perm, 'user') else None
repo = get_repo(repo_id)
dir_id = seafile_api.get_dir_id_by_path(repo_id, path)
if group_id is not None:
# is a group folder perm
group = get_group(group_id)
if repo is None or dir_id is None or group is None:
seafile_api.rm_folder_group_perm(repo_id, path, group_id)
return False
if email is not None:
# is a user folder perm
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
user = None
if repo is None or dir_id is None or user is None:
seafile_api.rm_folder_user_perm(repo_id, path, email)
return False
return True
# for user folder permission
user_folder_perms = seafile_api.list_folder_user_perm_by_repo(repo_id)
user_folder_perms = filter(lambda x: not_need_delete(x), user_folder_perms)
user_folder_perms.reverse()
for folder_perm in user_folder_perms:
folder_path = folder_perm.path
folder_perm.folder_link = reverse("view_common_lib_dir", args=[repo_id, urlquote(folder_path).strip('/')])
if folder_path == '/':
folder_perm.folder_name = _(u'Root Directory')
else:
folder_perm.folder_name = os.path.basename(folder_path)
# for group folder permission
group_folder_perms = seafile_api.list_folder_group_perm_by_repo(repo_id)
group_folder_perms = filter(lambda x: not_need_delete(x), group_folder_perms)
group_folder_perms.reverse()
for folder_perm in group_folder_perms:
folder_path = folder_perm.path
folder_perm.folder_link = reverse("view_common_lib_dir", args=[repo_id, urlquote(folder_path).strip('/')])
if folder_path == '/':
folder_perm.folder_name = _(u'Root Directory')
else:
folder_perm.folder_name = os.path.basename(folder_path)
folder_perm.group_name = get_group(folder_perm.group_id).group_name
# contacts that already registered
sys_contacts = []
contacts = Contact.objects.get_contacts_by_user(username)
for contact in contacts:
try:
user = User.objects.get(email = contact.contact_email)
except User.DoesNotExist:
user = None
if user is not None:
sys_contacts.append(contact.contact_email)
return render_to_response('repo_folder_perm.html', {
'repo': repo,
'user_folder_perms': user_folder_perms,
'group_folder_perms': group_folder_perms,
'contacts': sys_contacts,
}, context_instance=RequestContext(request))
def upload_error_msg (code):
err_msg = _(u'Internal Server Error')
if (code == 0):
err_msg = _(u'Filename contains invalid character')
elif (code == 1):
err_msg = _(u'Duplicated filename')
elif (code == 2):
err_msg = _(u'File does not exist')
elif (code == 3):
err_msg = _(u'File size surpasses the limit')
elif (code == 4):
err_msg = _(u'The space of owner is used up, upload failed')
elif (code == 5):
err_msg = _(u'An error occurs during file transfer')
return err_msg
def upload_file_error(request, repo_id):
if request.method == 'GET':
repo = get_repo(repo_id)
if not repo:
raise Http404
parent_dir = request.GET.get('p')
filename = request.GET.get('fn', '')
err = request.GET.get('err')
if not parent_dir or not err:
return render_error(request, _(u'Invalid url'))
zipped = gen_path_link (parent_dir, repo.name)
code = int(err)
err_msg = upload_error_msg(code)
return render_to_response('upload_file_error.html', {
'repo': repo,
'zipped': zipped,
'filename': filename,
'err_msg': err_msg,
}, context_instance=RequestContext(request))
def update_file_error(request, repo_id):
if request.method == 'GET':
repo = get_repo(repo_id)
if not repo:
raise Http404
target_file = request.GET.get('p')
err = request.GET.get('err')
if not target_file or not err:
return render_error(request, _(u'Invalid url'))
zipped = gen_path_link (target_file, repo.name)
code = int(err)
err_msg = upload_error_msg(code)
return render_to_response('update_file_error.html', {
'repo': repo,
'zipped': zipped,
'err_msg': err_msg,
}, context_instance=RequestContext(request))
@login_required
def repo_history(request, repo_id):
"""
List library modification histories.
"""
user_perm = check_repo_access_permission(repo_id, request.user)
if not user_perm:
return render_permission_error(request, _(u'Unable to view library modification'))
repo = get_repo(repo_id)
if not repo:
raise Http404
username = request.user.username
try:
server_crypto = UserOptions.objects.is_server_crypto(username)
except CryptoOptionNotSetError:
# Assume server_crypto is ``False`` if this option is not set.
server_crypto = False
password_set = False
if repo.props.encrypted and \
(repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)):
try:
ret = seafserv_rpc.is_passwd_set(repo_id, username)
if ret == 1:
password_set = True
except SearpcError, e:
return render_error(request, e.msg)
if not password_set:
return HttpResponseRedirect(reverse("view_common_lib_dir", args=[repo_id, '/']))
try:
current_page = int(request.GET.get('page', '1'))
per_page = int(request.GET.get('per_page', '25'))
except ValueError:
current_page = 1
per_page = 25
commits_all = get_commits(repo_id, per_page * (current_page -1),
per_page + 1)
commits = commits_all[:per_page]
for c in commits:
c.show = False if new_merge_with_no_conflict(c) else True
if len(commits_all) == per_page + 1:
page_next = True
else:
page_next = False
return render_to_response('repo_history.html', {
"repo": repo,
"commits": commits,
'current_page': current_page,
'prev_page': current_page-1,
'next_page': current_page+1,
'per_page': per_page,
'page_next': page_next,
'user_perm': user_perm,
}, context_instance=RequestContext(request))
@login_required
@require_POST
def repo_revert_history(request, repo_id):
next = request.META.get('HTTP_REFERER', None)
if not next:
next = settings.SITE_ROOT
repo = get_repo(repo_id)
if not repo:
messages.error(request, _("Library does not exist"))
return HttpResponseRedirect(next)
# perm check
perm = check_repo_access_permission(repo.id, request.user)
username = request.user.username
repo_owner = seafile_api.get_repo_owner(repo.id)
if perm is None or repo_owner != username:
messages.error(request, _("Permission denied"))
return HttpResponseRedirect(next)
try:
server_crypto = UserOptions.objects.is_server_crypto(username)
except CryptoOptionNotSetError:
# Assume server_crypto is ``False`` if this option is not set.
server_crypto = False
password_set = False
if repo.props.encrypted and \
(repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)):
try:
ret = seafserv_rpc.is_passwd_set(repo_id, username)
if ret == 1:
password_set = True
except SearpcError, e:
return render_error(request, e.msg)
if not password_set:
return HttpResponseRedirect(reverse("view_common_lib_dir", args=[repo_id, '/']))
commit_id = request.GET.get('commit_id', '')
if not commit_id:
return render_error(request, _(u'Please specify history ID'))
try:
seafserv_threaded_rpc.revert_on_server(repo_id, commit_id, request.user.username)
except SearpcError, e:
if e.msg == 'Bad arguments':
return render_error(request, _(u'Invalid arguments'))
elif e.msg == 'No such repo':
return render_error(request, _(u'Library does not exist'))
elif e.msg == "Commit doesn't exist":
return render_error(request, _(u'History you specified does not exist'))
else:
return render_error(request, _(u'Unknown error'))
return HttpResponseRedirect(next)
def fpath_to_link(repo_id, path, is_dir=False):
"""Translate file path of a repo to its view link"""
if is_dir:
href = reverse("view_common_lib_dir", args=[repo_id, urllib2.quote(path.encode('utf-8')).strip('/')])
else:
if not path.startswith('/'):
p = '/' + path
href = reverse("view_lib_file", args=[repo_id, urllib2.quote(p.encode('utf-8'))])
return '<a href="%s">%s</a>' % (href, escape(path))
def get_diff(repo_id, arg1, arg2):
lists = {'new': [], 'removed': [], 'renamed': [], 'modified': [],
'newdir': [], 'deldir': []}
diff_result = seafserv_threaded_rpc.get_diff(repo_id, arg1, arg2)
if not diff_result:
return lists
for d in diff_result:
if d.status == "add":
lists['new'].append(fpath_to_link(repo_id, d.name))
elif d.status == "del":
lists['removed'].append(escape(d.name))
elif d.status == "mov":
lists['renamed'].append(escape(d.name) + " ==> " + fpath_to_link(repo_id, d.new_name))
elif d.status == "mod":
lists['modified'].append(fpath_to_link(repo_id, d.name))
elif d.status == "newdir":
lists['newdir'].append(fpath_to_link(repo_id, d.name, is_dir=True))
elif d.status == "deldir":
lists['deldir'].append(escape(d.name))
return lists
def create_default_library(request):
"""Create a default library for user.
Arguments:
- `username`:
"""
username = request.user.username
# Disable user guide no matter user permission error or creation error,
# so that the guide popup only show once.
UserOptions.objects.disable_user_guide(username)
if not request.user.permissions.can_add_repo():
return
if is_org_context(request):
org_id = request.user.org.org_id
default_repo = seafile_api.create_org_repo(name=_("My Library"),
desc=_("My Library"),
username=username,
passwd=<PASSWORD>,
org_id=org_id)
else:
default_repo = seafile_api.create_repo(name=_("My Library"),
desc=_("My Library"),
username=username,
passwd=<PASSWORD>)
sys_repo_id = get_system_default_repo_id()
if sys_repo_id is None:
return
try:
dirents = seafile_api.list_dir_by_path(sys_repo_id, '/')
for e in dirents:
obj_name = e.obj_name
seafile_api.copy_file(sys_repo_id, '/', obj_name,
default_repo, '/', obj_name, username, 0)
except SearpcError as e:
logger.error(e)
return
UserOptions.objects.set_default_repo(username, default_repo)
return default_repo
def get_owned_repo_list(request):
"""List owned repos.
"""
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
return seafile_api.get_org_owned_repo_list(org_id, username)
else:
return seafile_api.get_owned_repo_list(username)
def get_virtual_repos_by_owner(request):
"""List virtual repos.
Arguments:
- `request`:
"""
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
return seaserv.seafserv_threaded_rpc.get_org_virtual_repos_by_owner(
org_id, username)
else:
return seafile_api.get_virtual_repos_by_owner(username)
@login_required
@user_mods_check
def myhome(request):
return HttpResponseRedirect(reverse('libraries'))
@login_required
@user_mods_check
def libraries(request):
"""
New URL to replace myhome
"""
username = request.user.username
# options
if request.cloud_mode and request.user.org is None:
allow_public_share = False
else:
allow_public_share = True
sub_lib_enabled = UserOptions.objects.is_sub_lib_enabled(username)
max_upload_file_size = get_max_upload_file_size()
guide_enabled = UserOptions.objects.is_user_guide_enabled(username)
if guide_enabled:
create_default_library(request)
folder_perm_enabled = True if is_pro_version() and ENABLE_FOLDER_PERM else False
can_add_pub_repo = True if is_org_repo_creation_allowed(request) else False
return render_to_response('libraries.html', {
"allow_public_share": allow_public_share,
"guide_enabled": guide_enabled,
"sub_lib_enabled": sub_lib_enabled,
'enable_upload_folder': settings.ENABLE_UPLOAD_FOLDER,
'enable_resumable_fileupload': settings.ENABLE_RESUMABLE_FILEUPLOAD,
'enable_thumbnail': settings.ENABLE_THUMBNAIL,
'enable_encrypted_library': config.ENABLE_ENCRYPTED_LIBRARY,
'max_upload_file_size': max_upload_file_size,
'folder_perm_enabled': folder_perm_enabled,
'is_pro': True if is_pro_version() else False,
'file_audit_enabled': FILE_AUDIT_ENABLED,
'can_add_pub_repo': can_add_pub_repo,
}, context_instance=RequestContext(request))
@login_required
@user_mods_check
def starred(request):
"""List starred files.
Arguments:
- `request`:
"""
username = request.user.username
starred_files = UserStarredFiles.objects.get_starred_files_by_username(
username)
return render_to_response('starred.html', {
"starred_files": starred_files,
}, context_instance=RequestContext(request))
@login_required
@user_mods_check
def devices(request):
"""List user devices"""
username = request.user.username
user_devices = get_user_devices(username)
return render_to_response('devices.html', {
"devices": user_devices,
}, context_instance=RequestContext(request))
@login_required_ajax
@require_POST
def unlink_device(request):
content_type = 'application/json; charset=utf-8'
platform = request.POST.get('platform', '')
device_id = request.POST.get('device_id', '')
if not platform or not device_id:
return HttpResponseBadRequest(json.dumps({'error': _(u'Argument missing')}),
content_type=content_type)
try:
do_unlink_device(request.user.username, platform, device_id)
except:
return HttpResponse(json.dumps({'error': _(u'Internal server error')}),
status=500, content_type=content_type)
return HttpResponse(json.dumps({'success': True}), content_type=content_type)
@login_required
@require_POST
def unsetinnerpub(request, repo_id):
"""Unshare repos in organization or in share admin page.
Only system admin, organization admin or repo owner can perform this op.
"""
repo = get_repo(repo_id)
perm = request.GET.get('permission', None)
if perm is None:
return render_error(request, _(u'Argument is not valid'))
if not repo:
messages.error(request, _('Failed to unshare the library, as it does not exist.'))
return HttpResponseRedirect(reverse('share_admin'))
# permission check
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
repo_owner = seafile_api.get_org_repo_owner(repo.id)
is_repo_owner = True if repo_owner == username else False
if not (request.user.org.is_staff or is_repo_owner):
raise Http404
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
is_repo_owner = True if repo_owner == username else False
if not (request.user.is_staff or is_repo_owner):
raise Http404
try:
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.unset_org_inner_pub_repo(org_id,
repo.id)
else:
seaserv.unset_inner_pub_repo(repo.id)
origin_repo_id, origin_path = get_origin_repo_info(repo.id)
if origin_repo_id is not None:
perm_repo_id = origin_repo_id
perm_path = origin_path
else:
perm_repo_id = repo.id
perm_path = '/'
send_perm_audit_msg('delete-repo-perm', username, 'all',
perm_repo_id, perm_path, perm)
messages.success(request, _('Unshare "%s" successfully.') % repo.name)
except SearpcError:
messages.error(request, _('Failed to unshare "%s".') % repo.name)
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
return HttpResponseRedirect(next)
# @login_required
# def ownerhome(request, owner_name):
# owned_repos = []
# quota_usage = 0
# owned_repos = seafserv_threaded_rpc.list_owned_repos(owner_name)
# quota_usage = seafserv_threaded_rpc.get_user_quota_usage(owner_name)
# user_dict = user_info(request, owner_name)
# return render_to_response('ownerhome.html', {
# "owned_repos": owned_repos,
# "quota_usage": quota_usage,
# "owner": owner_name,
# "user_dict": user_dict,
# }, context_instance=RequestContext(request))
@login_required
def repo_set_access_property(request, repo_id):
ap = request.GET.get('ap', '')
seafserv_threaded_rpc.repo_set_access_property(repo_id, ap)
return HttpResponseRedirect(reverse("view_common_lib_dir", args=[repo_id, '/']))
@login_required
def file_upload_progress_page(request):
'''
As iframe in repo_upload_file.html, for solving problem in chrome.
'''
uuid = request.GET.get('uuid', '')
fileserver_root = get_fileserver_root()
upload_progress_con_id = request.GET.get('upload_progress_con_id', '')
return render_to_response('file_upload_progress_page.html', {
'uuid': uuid,
'fileserver_root': fileserver_root,
'upload_progress_con_id': upload_progress_con_id,
}, context_instance=RequestContext(request))
@login_required
def validate_filename(request):
repo_id = request.GET.get('repo_id')
filename = request.GET.get('filename')
if not (repo_id and filename):
return render_error(request)
result = {'ret':'yes'}
try:
ret = is_valid_filename(filename)
except SearpcError:
result['ret'] = 'error'
else:
result['ret'] = 'yes' if ret == 1 else 'no'
content_type = 'application/json; charset=utf-8'
return HttpResponse(json.dumps(result), content_type=content_type)
def render_file_revisions (request, repo_id):
"""List all history versions of a file."""
days_str = request.GET.get('days', '')
try:
days = int(days_str)
except ValueError:
days = 7
path = request.GET.get('p', '/')
if path[-1] == '/':
path = path[:-1]
u_filename = os.path.basename(path)
if not path:
return render_error(request)
repo = get_repo(repo_id)
if not repo:
error_msg = _(u"Library does not exist")
return render_error(request, error_msg)
filetype = get_file_type_and_ext(u_filename)[0].lower()
if filetype == 'text' or filetype == 'markdown':
can_compare = True
else:
can_compare = False
try:
commits = seafile_api.get_file_revisions(repo_id, path, -1, -1, days)
except SearpcError, e:
logger.error(e.msg)
return render_error(request, e.msg)
if not commits:
return render_error(request, _(u'No revisions found'))
# Check whether user is repo owner
if validate_owner(request, repo_id):
is_owner = True
else:
is_owner = False
cur_path = path
for commit in commits:
commit.path = cur_path
if commit.rev_renamed_old_path:
cur_path = '/' + commit.rev_renamed_old_path
zipped = gen_path_link(path, repo.name)
can_revert_file = True
username = request.user.username
is_locked, locked_by_me = check_file_lock(repo_id, path, username)
if seafile_api.check_permission_by_path(repo_id, path, username) != 'rw' or \
(is_locked and not locked_by_me):
can_revert_file = False
return render_to_response('file_revisions.html', {
'repo': repo,
'path': path,
'u_filename': u_filename,
'zipped': zipped,
'commits': commits,
'is_owner': is_owner,
'can_compare': can_compare,
'can_revert_file': can_revert_file,
'days': days,
}, context_instance=RequestContext(request))
@login_required
@require_POST
def repo_revert_file(request, repo_id):
repo = get_repo(repo_id)
if not repo:
raise Http404
commit_id = request.GET.get('commit')
path = request.GET.get('p')
if not (commit_id and path):
return render_error(request, _(u"Invalid arguments"))
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
username = request.user.username
# perm check
if check_folder_permission(request, repo.id, path) != 'rw':
messages.error(request, _("Permission denied"))
return HttpResponseRedirect(next)
is_locked, locked_by_me = check_file_lock(repo_id, path, username)
if (is_locked, locked_by_me) == (None, None):
messages.error(request, _("Check file lock error"))
return HttpResponseRedirect(next)
if is_locked and not locked_by_me:
messages.error(request, _("File is locked"))
return HttpResponseRedirect(next)
try:
ret = seafile_api.revert_file(repo_id, commit_id, path, username)
except Exception as e:
logger.error(e)
messages.error(request, _('Failed to restore, please try again later.'))
return HttpResponseRedirect(next)
if ret == 1:
root_url = reverse('view_common_lib_dir', args=[repo_id, '/'])
msg = _(u'Successfully revert %(path)s to <a href="%(root)s">root directory.</a>') % {"path": escape(path.lstrip('/')), "root": root_url}
messages.success(request, msg, extra_tags='safe')
else:
file_view_url = reverse('view_lib_file', args=[repo_id, urllib2.quote(path.encode('utf-8'))])
msg = _(u'Successfully revert <a href="%(url)s">%(path)s</a>') % {"url": file_view_url, "path": escape(path.lstrip('/'))}
messages.success(request, msg, extra_tags='safe')
return HttpResponseRedirect(next)
@login_required
@require_POST
def repo_revert_dir(request, repo_id):
repo = get_repo(repo_id)
if not repo:
raise Http404
commit_id = request.GET.get('commit')
path = request.GET.get('p')
if not (commit_id and path):
return render_error(request, _(u"Invalid arguments"))
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
# perm check
if check_folder_permission(request, repo.id, path) != 'rw':
messages.error(request, _("Permission denied"))
return HttpResponseRedirect(next)
try:
ret = seafile_api.revert_dir(repo_id, commit_id, path, request.user.username)
except Exception as e:
logger.error(e)
messages.error(request, _('Failed to restore, please try again later.'))
return HttpResponseRedirect(next)
if ret == 1:
root_url = reverse('view_common_lib_dir', args=[repo_id, '/'])
msg = _(u'Successfully revert %(path)s to <a href="%(url)s">root directory.</a>') % {"path": escape(path.lstrip('/')), "url": root_url}
messages.success(request, msg, extra_tags='safe')
else:
dir_view_url = reverse('view_common_lib_dir', args=[repo_id, urllib2.quote(path.strip('/').encode('utf-8'))])
msg = _(u'Successfully revert <a href="%(url)s">%(path)s</a>') % {"url": dir_view_url, "path": escape(path.lstrip('/'))}
messages.success(request, msg, extra_tags='safe')
return HttpResponseRedirect(next)
@login_required
def file_revisions(request, repo_id):
"""List file revisions in file version history page.
"""
repo = get_repo(repo_id)
if not repo:
raise Http404
# perm check
if check_repo_access_permission(repo.id, request.user) is None:
raise Http404
return render_file_revisions(request, repo_id)
def demo(request):
"""
Login as demo account.
"""
user = User.objects.get(email=settings.CLOUD_DEMO_USER)
for backend in get_backends():
user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
auth_login(request, user)
redirect_to = settings.SITE_ROOT
return HttpResponseRedirect(redirect_to)
def list_inner_pub_repos(request):
"""List inner pub repos.
"""
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
return seaserv.list_org_inner_pub_repos(org_id, username)
if not request.cloud_mode:
return seaserv.list_inner_pub_repos(username)
return []
@login_required
def pubrepo(request):
"""
Show public libraries.
"""
if not request.user.permissions.can_view_org():
raise Http404
username = request.user.username
if request.cloud_mode and request.user.org is not None:
org_id = request.user.org.org_id
public_repos = seaserv.list_org_inner_pub_repos(org_id, username)
for r in public_repos:
if r.user == username:
r.share_from_me = True
return render_to_response('organizations/pubrepo.html', {
'public_repos': public_repos,
'create_shared_repo': True,
}, context_instance=RequestContext(request))
if not request.cloud_mode:
public_repos = seaserv.list_inner_pub_repos(username)
for r in public_repos:
if r.user == username:
r.share_from_me = True
return render_to_response('pubrepo.html', {
'public_repos': public_repos,
'create_shared_repo': True,
}, context_instance=RequestContext(request))
raise Http404
def get_pub_users(request, start, limit):
if is_org_context(request):
url_prefix = request.user.org.url_prefix
users_plus_one = seaserv.get_org_users_by_url_prefix(url_prefix,
start, limit)
elif request.cloud_mode:
raise Http404 # no pubuser in cloud mode
else:
users_plus_one = seaserv.get_emailusers('DB', start,
limit, is_active=True)
return users_plus_one
def count_pub_users(request):
if is_org_context(request):
url_prefix = request.user.org.url_prefix
# TODO: need a new api to count org users.
org_users = seaserv.get_org_users_by_url_prefix(url_prefix, -1, -1)
return len(org_users)
elif request.cloud_mode:
return 0
else:
return seaserv.ccnet_threaded_rpc.count_emailusers('DB')
@login_required
def pubuser(request):
"""
Show public users in database or ldap depending on request arg ``ldap``.
"""
if not request.user.permissions.can_view_org():
raise Http404
# Make sure page request is an int. If not, deliver first page.
try:
current_page = int(request.GET.get('page', '1'))
except ValueError:
current_page = 1
per_page = 20 # show 20 users per-page
# Show LDAP users or Database users.
have_ldap_user = False
if len(seaserv.get_emailusers('LDAPImport', 0, 1, is_active=True)) > 0:
have_ldap_user = True
try:
ldap = True if int(request.GET.get('ldap', 0)) == 1 else False
except ValueError:
ldap = False
if ldap and have_ldap_user:
# return ldap imported active users
users_plus_one = seaserv.get_emailusers('LDAPImport',
per_page * (current_page - 1),
per_page + 1,
is_active=True)
else:
users_plus_one = get_pub_users(request, per_page * (current_page - 1),
per_page + 1)
has_prev = False if current_page == 1 else True
has_next = True if len(users_plus_one) == per_page + 1 else False
if ldap and have_ldap_user:
# return the number of ldap imported active users
emailusers_count = seaserv.ccnet_threaded_rpc.count_emailusers('LDAP')
else:
emailusers_count = count_pub_users(request)
num_pages = int(ceil(emailusers_count / float(per_page)))
page_range = get_page_range(current_page, num_pages)
show_paginator = True if len(page_range) > 1 else False
users = users_plus_one[:per_page]
return render_to_response('pubuser.html', {
'users': users,
'current_page': current_page,
'has_prev': has_prev,
'has_next': has_next,
'page_range': page_range,
'show_paginator': show_paginator,
'have_ldap_user': have_ldap_user,
'ldap': ldap,
}, context_instance=RequestContext(request))
@login_required_ajax
def repo_set_password(request):
content_type = 'application/json; charset=utf-8'
form = RepoPassowrdForm(request.POST)
if form.is_valid():
return HttpResponse(json.dumps({'success': True}), content_type=content_type)
else:
return HttpResponse(json.dumps({'error': str(form.errors.values()[0])}),
status=400, content_type=content_type)
def i18n(request):
"""
Set client language preference, lasts for one month
"""
from django.conf import settings
next = request.META.get('HTTP_REFERER', settings.SITE_ROOT)
lang = request.GET.get('lang', settings.LANGUAGE_CODE)
if lang not in [e[0] for e in settings.LANGUAGES]:
# language code is not supported, use default.
lang = settings.LANGUAGE_CODE
# set language code to user profile if user is logged in
if not request.user.is_anonymous():
p = Profile.objects.get_profile_by_user(request.user.username)
if p is not None:
# update exist record
p.set_lang_code(lang)
else:
# add new record
Profile.objects.add_or_update(request.user.username, '', '', lang)
# set language code to client
res = HttpResponseRedirect(next)
res.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang, max_age=30*24*60*60)
return res
@login_required
def repo_download_dir(request, repo_id):
repo = get_repo(repo_id)
if not repo:
return render_error(request, _(u'Library does not exist'))
path = request.GET.get('p', '/')
if path[-1] != '/': # Normalize dir path
path += '/'
if not seafile_api.get_dir_id_by_path(repo.id, path):
return render_error(request, _('"%s" does not exist.') % path)
if len(path) > 1:
dirname = os.path.basename(path.rstrip('/')) # Here use `rstrip` to cut out last '/' in path
else:
dirname = repo.name
allow_download = True if check_repo_access_permission(
repo_id, request.user) else False
if allow_download:
dir_id = seafserv_threaded_rpc.get_dirid_by_path (repo.id,
repo.head_cmmt_id,
path.encode('utf-8'))
try:
total_size = seafserv_threaded_rpc.get_dir_size(repo.store_id, repo.version,
dir_id)
except Exception, e:
logger.error(str(e))
return render_error(request, _(u'Internal Error'))
if total_size > MAX_DOWNLOAD_DIR_SIZE:
return render_error(request, _(u'Unable to download directory "%s": size is too large.') % dirname)
token = seafile_api.get_fileserver_access_token(repo_id,
dir_id,
'download-dir',
request.user.username)
else:
return render_error(request, _(u'Unable to download "%s"') % dirname )
url = gen_file_get_url(token, dirname)
return redirect(url)
@login_required
@user_mods_check
def activities(request):
if not EVENTS_ENABLED:
raise Http404
events_count = 15
username = request.user.username
start = int(request.GET.get('start', 0))
if is_org_context(request):
org_id = request.user.org.org_id
events, start = get_org_user_events(org_id, username, start, events_count)
else:
events, start = get_user_events(username, start, events_count)
events_more = True if len(events) == events_count else False
event_groups = group_events_data(events)
return render_to_response('activities.html', {
'event_groups': event_groups,
'events_more': events_more,
'new_start': start,
}, context_instance=RequestContext(request))
def group_events_data(events):
"""
Group events according to the date.
"""
event_groups = []
for e in events:
e.time = utc_to_local(e.timestamp)
e.date = e.time.strftime("%Y-%m-%d")
if e.etype == 'repo-update':
e.author = e.commit.creator_name
elif e.etype == 'repo-create':
e.author = e.creator
else:
e.author = e.repo_owner
if len(event_groups) == 0 or \
len(event_groups) > 0 and e.date != event_groups[-1]['date']:
event_group = {}
event_group['date'] = e.date
event_group['events'] = [e]
event_groups.append(event_group)
else:
event_groups[-1]['events'].append(e)
return event_groups
@login_required
def convert_cmmt_desc_link(request):
"""Return user to file/directory page based on the changes in commit.
"""
repo_id = request.GET.get('repo_id')
cmmt_id = request.GET.get('cmmt_id')
name = request.GET.get('nm')
repo = get_repo(repo_id)
if not repo:
raise Http404
# perm check
if check_repo_access_permission(repo_id, request.user) is None:
raise Http404
diff_result = seafserv_threaded_rpc.get_diff(repo_id, '', cmmt_id)
if not diff_result:
raise Http404
for d in diff_result:
if name not in d.name:
# skip to next diff_result if file/folder user clicked does not
# match the diff_result
continue
if d.status == 'add' or d.status == 'mod': # Add or modify file
return HttpResponseRedirect(
reverse('view_lib_file', args=[repo_id, '/' + urlquote(d.name)]))
elif d.status == 'mov': # Move or Rename file
return HttpResponseRedirect(
reverse('view_lib_file', args=[repo_id, '/' + urlquote(d.new_name)]))
elif d.status == 'newdir':
return HttpResponseRedirect(
reverse('view_common_lib_dir', args=[repo_id, urlquote(d.name).strip('/')]))
else:
continue
# Shoud never reach here.
logger.warn('OUT OF CONTROL!')
logger.warn('repo_id: %s, cmmt_id: %s, name: %s' % (repo_id, cmmt_id, name))
for d in diff_result:
logger.warn('diff_result: %s' % (d.__dict__))
raise Http404
@login_required
def toggle_modules(request):
"""Enable or disable modules.
"""
if request.method != 'POST':
raise Http404
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
username = request.user.username
personal_wiki = request.POST.get('personal_wiki', 'off')
if personal_wiki == 'on':
enable_mod_for_user(username, MOD_PERSONAL_WIKI)
messages.success(request, _('Successfully enable "Personal Wiki".'))
else:
disable_mod_for_user(username, MOD_PERSONAL_WIKI)
if referer.find('wiki') > 0:
next = reverse('myhome')
messages.success(request, _('Successfully disable "Personal Wiki".'))
return HttpResponseRedirect(next)
storage = get_avatar_file_storage()
def latest_entry(request, filename):
try:
return storage.modified_time(filename)
except Exception as e:
logger.error(e)
return None
@condition(last_modified_func=latest_entry)
def image_view(request, filename):
if AVATAR_FILE_STORAGE is None:
raise Http404
# read file from cache, if hit
filename_md5 = hashlib.md5(filename).hexdigest()
cache_key = 'image_view__%s' % filename_md5
file_content = cache.get(cache_key)
if file_content is None:
# otherwise, read file from database and update cache
image_file = storage.open(filename, 'rb')
if not image_file:
raise Http404
file_content = image_file.read()
cache.set(cache_key, file_content, 365 * 24 * 60 * 60)
# Prepare response
content_type, content_encoding = mimetypes.guess_type(filename)
response = HttpResponse(content=file_content, mimetype=content_type)
response['Content-Disposition'] = 'inline; filename=%s' % filename
if content_encoding:
response['Content-Encoding'] = content_encoding
return response
def shib_login(request):
return HttpResponseRedirect(request.GET.get("next",reverse('myhome')))
def underscore_template(request, template):
"""Serve underscore template through Django, mainly for I18n.
Arguments:
- `request`:
- `template`:
"""
if not template.startswith('js'): # light security check
raise Http404
return render_to_response(template, {},
context_instance=RequestContext(request))
def fake_view(request, **kwargs):
"""
Used for 'view_common_lib_dir' and 'view_group' url
As the two urls aboved starts with '#',
http request will not access this function
"""
pass
def client_token_login(request):
"""Login from desktop client with a generated token.
"""
tokenstr = request.GET.get('token', '')
user = None
if len(tokenstr) == 32:
try:
username = ClientLoginToken.objects.get_username(tokenstr)
except ClientLoginToken.DoesNotExist:
pass
else:
try:
user = User.objects.get(email=username)
for backend in get_backends():
user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
except User.DoesNotExist:
pass
if user:
if request.user.is_authenticated() and request.user.username == user.username:
pass
else:
request.client_token_login = True
auth_login(request, user)
return HttpResponseRedirect(request.GET.get("next", reverse('libraries')))
<file_sep>/tests/seahub/share/views/test_send_shared_upload_link.py
from mock import patch
from django.core import mail
from django.core.urlresolvers import reverse
from seahub.test_utils import BaseTestCase
class SendSharedUploadLinkTest(BaseTestCase):
def setUp(self):
mail.outbox = []
@patch('seahub.share.views.IS_EMAIL_CONFIGURED', True)
def test_can_send(self):
self.login_as(self.user)
resp = self.client.post(reverse('send_shared_upload_link'), {
'email': self.user.email,
'shared_upload_link': 'http://xxx',
'extra_msg': ''
}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(200, resp.status_code)
self.assertEqual(len(mail.outbox), 1)
assert '<a href="http://xxx">http://xxx</a>' in mail.outbox[0].body
<file_sep>/thirdpart/rest_framework/pagination.py
from rest_framework import serializers
from rest_framework.templatetags.rest_framework import replace_query_param
# TODO: Support URLconf kwarg-style paging
class NextPageField(serializers.Field):
"""
Field that returns a link to the next page in paginated results.
"""
page_field = 'page'
def to_native(self, value):
if not value.has_next():
return None
page = value.next_page_number()
request = self.context.get('request')
url = request and request.build_absolute_uri() or ''
return replace_query_param(url, self.page_field, page)
class PreviousPageField(serializers.Field):
"""
Field that returns a link to the previous page in paginated results.
"""
page_field = 'page'
def to_native(self, value):
if not value.has_previous():
return None
page = value.previous_page_number()
request = self.context.get('request')
url = request and request.build_absolute_uri() or ''
return replace_query_param(url, self.page_field, page)
class PaginationSerializerOptions(serializers.SerializerOptions):
"""
An object that stores the options that may be provided to a
pagination serializer by using the inner `Meta` class.
Accessible on the instance as `serializer.opts`.
"""
def __init__(self, meta):
super(PaginationSerializerOptions, self).__init__(meta)
self.object_serializer_class = getattr(meta, 'object_serializer_class',
serializers.Field)
class BasePaginationSerializer(serializers.Serializer):
"""
A base class for pagination serializers to inherit from,
to make implementing custom serializers more easy.
"""
_options_class = PaginationSerializerOptions
results_field = 'results'
def __init__(self, *args, **kwargs):
"""
Override init to add in the object serializer field on-the-fly.
"""
super(BasePaginationSerializer, self).__init__(*args, **kwargs)
results_field = self.results_field
object_serializer = self.opts.object_serializer_class
self.fields[results_field] = object_serializer(source='object_list')
def to_native(self, obj):
"""
Prevent default behaviour of iterating over elements, and serializing
each in turn.
"""
return self.convert_object(obj)
class PaginationSerializer(BasePaginationSerializer):
"""
A default implementation of a pagination serializer.
"""
count = serializers.Field(source='paginator.count')
next = NextPageField(source='*')
previous = PreviousPageField(source='*')
<file_sep>/seahub/thumbnail/views.py
import os
import json
import logging
import posixpath
import datetime
from django.utils.translation import ugettext as _
from django.utils.http import urlquote
from django.http import HttpResponse
from django.views.decorators.http import condition
from django.shortcuts import render_to_response
from django.template import RequestContext
from seaserv import get_repo, get_file_id_by_path
from seahub.auth.decorators import login_required_ajax, login_required
from seahub.views import check_folder_permission
from seahub.settings import THUMBNAIL_DEFAULT_SIZE, THUMBNAIL_EXTENSION, \
THUMBNAIL_ROOT, ENABLE_THUMBNAIL
from seahub.thumbnail.utils import generate_thumbnail, \
get_thumbnail_src, get_share_link_thumbnail_src
from seahub.share.models import FileShare, check_share_link_common
# Get an instance of a logger
logger = logging.getLogger(__name__)
@login_required_ajax
def thumbnail_create(request, repo_id):
"""create thumbnail from repo file list
return thumbnail src
"""
content_type = 'application/json; charset=utf-8'
result = {}
repo = get_repo(repo_id)
if not repo:
err_msg = _(u"Library does not exist.")
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
path = request.GET.get('path', None)
if not path:
err_msg = _(u"Invalid arguments.")
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
if repo.encrypted or not ENABLE_THUMBNAIL or \
check_folder_permission(request, repo_id, path) is None:
err_msg = _(u"Permission denied.")
return HttpResponse(json.dumps({"error": err_msg}), status=403,
content_type=content_type)
size = request.GET.get('size', THUMBNAIL_DEFAULT_SIZE)
success, status_code = generate_thumbnail(request, repo_id, size, path)
if success:
src = get_thumbnail_src(repo_id, size, path)
result['encoded_thumbnail_src'] = urlquote(src)
return HttpResponse(json.dumps(result), content_type=content_type)
else:
err_msg = _('Failed to create thumbnail.')
return HttpResponse(json.dumps({'err_msg': err_msg}),
status=status_code, content_type=content_type)
def latest_entry(request, repo_id, size, path):
obj_id = get_file_id_by_path(repo_id, path)
if obj_id:
try:
thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id)
last_modified_time = os.path.getmtime(thumbnail_file)
# convert float to datatime obj
return datetime.datetime.fromtimestamp(last_modified_time)
except Exception as e:
# no thumbnail file exists
logger.error(e)
return None
else:
return None
@login_required
@condition(last_modified_func=latest_entry)
def thumbnail_get(request, repo_id, size, path):
""" handle thumbnail src from repo file list
return thumbnail file to web
"""
repo = get_repo(repo_id)
obj_id = get_file_id_by_path(repo_id, path)
# check if file exist
if not repo or not obj_id:
return HttpResponse()
# check if is allowed
if repo.encrypted or not ENABLE_THUMBNAIL or \
check_folder_permission(request, repo_id, path) is None:
return HttpResponse()
try:
size = int(size)
except ValueError as e:
logger.error(e)
return HttpResponse()
success = True
thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id)
if not os.path.exists(thumbnail_file):
success, status_code = generate_thumbnail(request, repo_id, size, path)
if success:
try:
with open(thumbnail_file, 'rb') as f:
thumbnail = f.read()
return HttpResponse(content=thumbnail, mimetype='image/'+THUMBNAIL_EXTENSION)
except IOError as e:
logger.error(e)
return HttpResponse()
else:
return HttpResponse()
def share_link_thumbnail_create(request, token):
"""generate thumbnail from dir download link page
return thumbnail src to web
"""
content_type = 'application/json; charset=utf-8'
result = {}
fileshare = FileShare.objects.get_valid_file_link_by_token(token)
if not fileshare:
err_msg = _(u"Invalid token.")
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
if not repo:
err_msg = _(u"Library does not exist.")
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
if repo.encrypted or not ENABLE_THUMBNAIL:
err_msg = _(u"Permission denied.")
return HttpResponse(json.dumps({"error": err_msg}), status=403,
content_type=content_type)
req_path = request.GET.get('path', None)
if not req_path or '../' in req_path:
err_msg = _(u"Invalid arguments.")
return HttpResponse(json.dumps({"error": err_msg}), status=400,
content_type=content_type)
if fileshare.path == '/':
real_path = req_path
else:
real_path = posixpath.join(fileshare.path, req_path.lstrip('/'))
size = request.GET.get('size', THUMBNAIL_DEFAULT_SIZE)
success, status_code = generate_thumbnail(request, repo_id, size, real_path)
if success:
src = get_share_link_thumbnail_src(token, size, req_path)
result['encoded_thumbnail_src'] = urlquote(src)
return HttpResponse(json.dumps(result), content_type=content_type)
else:
err_msg = _('Failed to create thumbnail.')
return HttpResponse(json.dumps({'err_msg': err_msg}),
status=status_code, content_type=content_type)
def share_link_latest_entry(request, token, size, path):
fileshare = FileShare.objects.get_valid_file_link_by_token(token)
if not fileshare:
return None
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
if not repo:
return None
if fileshare.path == '/':
image_path = path
else:
image_path = posixpath.join(fileshare.path, path.lstrip('/'))
obj_id = get_file_id_by_path(repo_id, image_path)
if obj_id:
try:
thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id)
last_modified_time = os.path.getmtime(thumbnail_file)
# convert float to datatime obj
return datetime.datetime.fromtimestamp(last_modified_time)
except Exception as e:
logger.error(e)
# no thumbnail file exists
return None
else:
return None
@condition(last_modified_func=share_link_latest_entry)
def share_link_thumbnail_get(request, token, size, path):
""" handle thumbnail src from dir download link page
return thumbnail file to web
"""
try:
size = int(size)
except ValueError as e:
logger.error(e)
return HttpResponse()
fileshare = FileShare.objects.get_valid_file_link_by_token(token)
if not fileshare:
return HttpResponse()
password_check_passed, err_msg = check_share_link_common(request, fileshare)
if not password_check_passed:
d = {'token': token, 'view_name': 'view_shared_dir', 'err_msg': err_msg}
return render_to_response('share_access_validation.html', d,
context_instance=RequestContext(request))
if fileshare.path == '/':
image_path = path
else:
image_path = posixpath.join(fileshare.path, path.lstrip('/'))
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
obj_id = get_file_id_by_path(repo_id, image_path)
# check if file exist
if not repo or not obj_id:
return HttpResponse()
# check if is allowed
if repo.encrypted or not ENABLE_THUMBNAIL:
return HttpResponse()
success = True
thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id)
if not os.path.exists(thumbnail_file):
success, status_code = generate_thumbnail(request, repo_id, size, image_path)
if success:
try:
with open(thumbnail_file, 'rb') as f:
thumbnail = f.read()
return HttpResponse(content=thumbnail, mimetype='image/'+THUMBNAIL_EXTENSION)
except IOError as e:
logger.error(e)
return HttpResponse()
else:
return HttpResponse()
<file_sep>/thirdpart/rest_framework/filters.py
from rest_framework.compat import django_filters
FilterSet = django_filters and django_filters.FilterSet or None
class BaseFilterBackend(object):
"""
A base class from which all filter backend classes should inherit.
"""
def filter_queryset(self, request, queryset, view):
"""
Return a filtered queryset.
"""
raise NotImplementedError(".filter_queryset() must be overridden.")
class DjangoFilterBackend(BaseFilterBackend):
"""
A filter backend that uses django-filter.
"""
default_filter_set = FilterSet
def __init__(self):
assert django_filters, 'Using DjangoFilterBackend, but django-filter is not installed'
def get_filter_class(self, view):
"""
Return the django-filters `FilterSet` used to filter the queryset.
"""
filter_class = getattr(view, 'filter_class', None)
filter_fields = getattr(view, 'filter_fields', None)
view_model = getattr(view, 'model', None)
if filter_class:
filter_model = filter_class.Meta.model
assert issubclass(filter_model, view_model), \
'FilterSet model %s does not match view model %s' % \
(filter_model, view_model)
return filter_class
if filter_fields:
class AutoFilterSet(self.default_filter_set):
class Meta:
model = view_model
fields = filter_fields
return AutoFilterSet
return None
def filter_queryset(self, request, queryset, view):
filter_class = self.get_filter_class(view)
if filter_class:
return filter_class(request.GET, queryset=queryset)
return queryset
<file_sep>/static/scripts/app/views/dir.js
define([
'jquery',
'jquery.ui.progressbar',
'jquery.magnific-popup',
'simplemodal',
'underscore',
'backbone',
'common',
'file-tree',
'app/collections/dirents',
'app/views/dirent',
'app/views/fileupload',
'app/views/share'
], function($, progressbar, magnificPopup, simplemodal, _, Backbone, Common,
FileTree, DirentCollection, DirentView, FileUploadView, ShareView) {
'use strict';
var DirView = Backbone.View.extend({
el: $('#dir-view'),
path_bar_template: _.template($('#dir-path-bar-tmpl').html()),
dir_op_bar_template: _.template($('#dir-op-bar-tmpl').html()),
dirents_hd_template: _.template($('#dirents-hd-tmpl').html()),
top_search_form_template: _.template($('#top-search-form-tmpl').html()),
newDirTemplate: _.template($("#add-new-dir-form-template").html()),
newFileTemplate: _.template($("#add-new-file-form-template").html()),
mvcpTemplate: _.template($("#mvcp-form-template").html()),
mvProgressTemplate: _.template($("#mv-progress-popup-template").html()),
initialize: function(options) {
this.$dirent_list = this.$('.repo-file-list tbody');
this.$path_bar = this.$('.path');
// For compatible with css, we use .repo-op instead of .dir-op
this.$dir_op_bar = this.$('.repo-op');
this.dir = new DirentCollection();
this.listenTo(this.dir, 'add', this.addOne);
this.listenTo(this.dir, 'reset', this.reset);
this.fileUploadView = new FileUploadView({dirView: this});
this.$el.magnificPopup({
type: 'image',
delegate: '.img-name-link',
tClose: gettext("Close (Esc)"), // Alt text on close button
tLoading: gettext("Loading..."), // Text that is displayed during loading. Can contain %curr% and %total% keys
gallery: {
enabled: true,
tPrev: gettext("Previous (Left arrow key)"), // Alt text on left arrow
tNext: gettext("Next (Right arrow key)"), // Alt text on right arrow
tCounter: gettext("%curr% of %total%") // Markup for "1 of 7" counter
},
image: {
titleSrc: function(item) {
var el = item.el;
var img_name = el[0].innerHTML;
var img_link = '<a href="' + el.attr('href') + '" target="_blank">' + gettext("Open in New Tab") + '</a>';
return img_name + '<br />' + img_link;
},
tError: gettext('<a href="%url%" target="_blank">The image</a> could not be loaded.') // Error message when image could not be loaded
}
});
// scroll window: get 'more', fix 'op bar'
var _this = this;
$(window).scroll(function() {
if ($(_this.el).is(':visible')) {
_this.onWindowScroll();
}
});
// hide 'hidden-op' popup
$(document).click(function(e) {
var target = e.target || event.srcElement;
var $popup = $('.hidden-op:visible');
if ($popup.length > 0 && // There is a visible popup
!$('.more-op-icon', $popup.closest('tr')).is(target) &&
!$popup.is(target) &&
!$popup.find('*').is(target)) {
$popup.addClass('hide');
var $tr = $popup.closest('tr');
if (!$tr.find('*').is(target)) {
$tr.removeClass('hl').find('.repo-file-op').addClass('vh');
$('.repo-file-list tr:gt(0)').each(function() {
if ($(this).find('*').is(target)) {
$(this).addClass('hl').find('.repo-file-op').removeClass('vh');
}
});
}
}
});
// hide 'rename form'
$(document).click(function(e) {
var target = e.target || event.srcElement;
var $form = $('#rename-form');
if ($form.length && !$form.find('*').is(target)) {
var $tr = $form.closest('tr'); // get $tr before $form removed in `.cancel click()`
$('.cancel', $form).click();
if (!$tr.find('*').is(target)) {
$tr.removeClass('hl').find('.repo-file-op').addClass('vh');
$('.repo-file-list tr:gt(0)').each(function() {
if ($(this).find('*').is(target)) {
$(this).addClass('hl').find('.repo-file-op').removeClass('vh');
}
});
}
}
});
},
showDir: function(category, repo_id, path) {
$('#top-search-form').html(this.top_search_form_template({
search_repo_id: repo_id
}));
this.$el.show();
this.$dirent_list.empty();
var loading_tip = this.$('.loading-tip').show();
var dir = this.dir;
dir.setPath(category, repo_id, path);
var _this = this;
dir.fetch({
cache: false,
reset: true,
data: {'p': path},
success: function (collection, response, opts) {
dir.last_start = 0; // for 'more'
if (response.dirent_list.length == 0 || // the dir is empty
!response.dirent_more ) { // no 'more'
loading_tip.hide();
}
},
error: function (collection, response, opts) {
loading_tip.hide();
var $el_con = _this.$('.repo-file-list-topbar, .repo-file-list').hide();
var $error = _this.$('.error');
var err_msg;
var lib_need_decrypt = false;
if (response.responseText) {
if (response.responseJSON.lib_need_decrypt) {
lib_need_decrypt = true;
} else {
err_msg = response.responseJSON.error;
}
} else {
err_msg = gettext('Please check the network.');
}
if (err_msg) {
$error.html(err_msg).show();
}
if (lib_need_decrypt) {
var form = $($('#repo-decrypt-form-template').html());
var decrypt_success = false;
form.modal({
containerCss: {'padding': '1px'},
onClose: function () {
$.modal.close();
$el_con.show();
if (!decrypt_success) {
app.router.navigate(
category + '/', // need to append '/' at end
{trigger: true}
);
}
}
});
$('#simplemodal-container').css({'height':'auto'});
form.submit(function() {
var passwd = $.trim($('[name="password"]', form).val());
if (!passwd) {
$('.error', form).html(gettext("Password is required.")).removeClass('hide');
return false;
}
Common.ajaxPost({
form: form,
form_id: form.attr('id'),
post_url: Common.getUrl({'name':'repo_set_password'}),
post_data: {
repo_id: repo_id,
password: <PASSWORD>,
username: app.pageOptions.username
},
after_op_success: function() {
decrypt_success = true;
$.modal.close();
_this.showDir(category, repo_id, path);
}
});
return false;
});
}
}
});
},
hide: function() {
$('#top-search-form').html(this.top_search_form_template({
search_repo_id: ''
}));
this.$el.hide();
},
addOne: function(dirent) {
var view = new DirentView({model: dirent, dirView: this});
this.$dirent_list.append(view.render().el);
},
reset: function() {
this.dir.each(this.addOne, this);
this.renderPath();
this.renderDirOpBar();
this.renderDirentsHd();
this.fileUploadView.setFileInput();
this.getImageThumbnail();
},
getImageThumbnail: function() {
if (!app.pageOptions.enable_thumbnail || this.dir.encrypted) {
return false;
}
var images_with_no_thumbnail = this.dir.filter(function(dirent) {
// 'dirent' is a model
return dirent.get('is_img') && !dirent.get('encoded_thumbnail_src');
});
if (images_with_no_thumbnail.length == 0) {
return ;
}
var images_len = images_with_no_thumbnail.length,
repo_id = this.dir.repo_id,
cur_path = this.dir.path,
_this = this;
var get_thumbnail = function(i) {
var cur_img = images_with_no_thumbnail[i];
var cur_img_path = Common.pathJoin([cur_path, cur_img.get('obj_name')]);
$.ajax({
url: Common.getUrl({name: 'thumbnail_create', repo_id: repo_id}),
data: {'path': cur_img_path},
cache: false,
dataType: 'json',
success: function(data) {
cur_img.set({
'encoded_thumbnail_src': data.encoded_thumbnail_src
});
},
complete: function() {
// cur path may be changed. e.g., the user enter another directory
if (i < images_len - 1 &&
_this.dir.repo_id == repo_id &&
_this.dir.path == cur_path) {
get_thumbnail(++i);
}
}
});
};
get_thumbnail(0);
},
renderPath: function() {
var dir = this.dir;
var path = dir.path;
var context = 'my';
var category_start = dir.category.split('/')[0];
if (category_start == 'org') {
context = 'org';
} else if (category_start == 'group') {
context = 'group';
} else if (category_start == 'common') {
context = 'common';
}
var obj = {
path: path,
repo_name: dir.repo_name,
category: dir.category,
context: context
};
var path_list = path.substr(1).split('/');
var path_list_encoded = Common.encodePath(path.substr(1)).split('/');
if (path != '/') {
$.extend(obj, {
path_list: path_list,
path_list_encoded: path_list_encoded,
repo_id: dir.repo_id
});
}
this.$path_bar.html(this.path_bar_template(obj));
},
renderDirOpBar: function() {
var dir = this.dir;
this.$dir_op_bar.html($.trim(this.dir_op_bar_template({
user_perm: dir.user_perm,
encrypted: dir.encrypted,
path: dir.path,
repo_id: dir.repo_id,
site_root: app.pageOptions.site_root,
is_repo_owner: dir.is_repo_owner,
is_virtual: dir.is_virtual,
can_generate_shared_link: app.pageOptions.can_generate_shared_link,
enable_upload_folder: app.pageOptions.enable_upload_folder
})));
},
renderDirentsHd: function() {
this.$('thead').html(this.dirents_hd_template());
},
// Directory Operations
events: {
'click .path-link': 'visitDir',
'click #add-new-dir': 'newDir',
'click #add-new-file': 'newFile',
'click #share-cur-dir': 'share',
'click th.select': 'select',
'click #mv-dirents': 'mv',
'click #cp-dirents': 'cp',
'click #del-dirents': 'del',
'click .by-name': 'sortByName',
'click .by-time': 'sortByTime'
},
newDir: function() {
var form = $(this.newDirTemplate()),
form_id = form.attr('id'),
dir = this.dir,
dirView = this;
form.modal({appendTo:'#main'});
$('#simplemodal-container').css({'height':'auto'});
form.submit(function() {
var dirent_name = $.trim($('input[name="name"]', form).val());
if (!dirent_name) {
Common.showFormError(form_id, gettext("It is required."));
return false;
};
// make sure it does not have invalid windows chars
if (Common.isFilenameProblematicForSyncing(dirent_name)) {
Common.showFormError(form_id, gettext("The following characters are not supported: Angular brackets \\ / : ? * \" |"));
return false;
}
var post_data = {'dirent_name': dirent_name},
post_url = Common.getUrl({name: "new_dir", repo_id: dir.repo_id})
+ '?parent_dir=' + encodeURIComponent(dir.path);
var after_op_success = function(data) {
$.modal.close();
var new_dirent = dir.add({
'is_dir': true,
'obj_name': data['name'],
'perm': 'rw',
'last_modified': new Date().getTime() / 1000,
'last_update': gettext("Just now"),
'p_dpath': data['p_dpath']
}, {silent:true});
dirView.addNewDir(new_dirent);
};
Common.ajaxPost({
'form': form,
'post_url': post_url,
'post_data': post_data,
'after_op_success': after_op_success,
'form_id': form_id
});
return false;
});
},
newFile: function() {
var form = $(this.newFileTemplate()),
form_id = form.attr('id'),
file_name = form.find('input[name="name"]'),
dir = this.dir,
dirView = this;
form.modal({
appendTo: '#main',
focus: false,
containerCss: {'padding':'20px 25px'}
});
$('#simplemodal-container').css({'height':'auto'});
$('.set-file-type', form).click(function() {
file_name.val('.' + $(this).data('filetype'));
Common.setCaretPos(file_name[0], 0);
file_name.focus();
});
form.submit(function() {
var dirent_name = $.trim(file_name.val());
if (!dirent_name) {
Common.showFormError(form_id, gettext("It is required."));
return false;
};
// if it has an extension, make sure it has a name
if (dirent_name.lastIndexOf('.') != -1 && dirent_name.substr(0, dirent_name.lastIndexOf('.')).length == 0) {
Common.showFormError(form_id, gettext("Only an extension there, please input a name."));
return false;
}
// make sure it does not have invalid windows chars
if (Common.isFilenameProblematicForSyncing(dirent_name)) {
Common.showFormError(form_id, gettext("The following characters are not supported: Angular brackets \\ / : ? * \" |"));
return false;
}
var post_data = {'dirent_name': dirent_name},
post_url = Common.getUrl({name: "new_file", repo_id: dir.repo_id})
+ '?parent_dir=' + encodeURIComponent(dir.path);
var after_op_success = function(data) {
$.modal.close();
var new_dirent = dir.add({
'is_file': true,
'is_img': Common.imageCheck(data['name']),
'is_gimp_editable': Common.gimpEditableCheck(data['name']),
'obj_name': data['name'],
'file_size': Common.fileSizeFormat(0),
'obj_id': '0000000000000000000000000000000000000000',
'file_icon': 'file.png',
'starred': false,
'perm': 'rw',
'last_modified': new Date().getTime() / 1000,
'last_update': gettext("Just now")
}, {silent: true});
dirView.addNewFile(new_dirent);
};
Common.ajaxPost({
'form': form,
'post_url': post_url,
'post_data': post_data,
'after_op_success': after_op_success,
'form_id': form_id
});
return false;
});
},
addNewFile: function(new_dirent) {
var dirView = this,
dir = this.dir;
var view = new DirentView({model: new_dirent, dirView: dirView});
var new_file = view.render().el;
// put the new file as the first file
if ($('tr', dirView.$dirent_list).length == 0) {
dirView.$dirent_list.append(new_file);
} else {
var dirs = dir.where({'is_dir':true});
if (dirs.length == 0) {
dirView.$dirent_list.prepend(new_file);
} else {
// put the new file after the last dir
$($('tr', dirView.$dirent_list)[dirs.length - 1]).after(new_file);
}
}
},
addNewDir: function(new_dirent) {
var dirView = this;
var view = new DirentView({model: new_dirent, dirView: dirView});
dirView.$dirent_list.prepend(view.render().el); // put the new dir as the first one
},
share: function () {
var dir = this.dir;
var path = dir.path;
var options = {
'is_repo_owner': dir.is_repo_owner,
'is_virtual': dir.is_virtual,
'user_perm': dir.user_perm,
'repo_id': dir.repo_id,
'is_dir': true,
'dirent_path': path,
'obj_name': path == '/' ? dir.repo_name : path.substr(path.lastIndexOf('/') + 1)
};
new ShareView(options);
},
sortByName: function() {
this.$('.by-time .sort-icon').hide();
var dirents = this.dir;
var el = this.$('.by-name .sort-icon');
dirents.comparator = function(a, b) {
if (a.get('is_dir') && b.get('is_file')) {
return -1;
}
if (a.get('is_file') && b.get('is_dir')) {
return 1;
}
var result = Common.compareTwoWord(a.get('obj_name'), b.get('obj_name'));
if (el.hasClass('icon-caret-up')) {
return -result;
} else {
return result;
}
};
dirents.sort();
this.$dirent_list.empty();
dirents.each(this.addOne, this);
el.toggleClass('icon-caret-up icon-caret-down').show();
dirents.comparator = null;
},
sortByTime: function () {
this.$('.by-name .sort-icon').hide();
var dirents = this.dir;
var el = this.$('.by-time .sort-icon');
dirents.comparator = function(a, b) {
if (a.get('is_dir') && b.get('is_file')) {
return -1;
}
if (a.get('is_file') && b.get('is_dir')) {
return 1;
}
if (el.hasClass('icon-caret-down')) {
return a.get('last_modified') < b.get('last_modified') ? 1 : -1;
} else {
return a.get('last_modified') < b.get('last_modified') ? -1 : 1;
}
};
dirents.sort();
this.$dirent_list.empty();
dirents.each(this.addOne, this);
el.toggleClass('icon-caret-up icon-caret-down').show();
dirents.comparator = null;
},
select: function () {
var el = this.$('th .checkbox');
el.toggleClass('checkbox-checked');
var dir = this.dir;
var all_dirent_checkbox = this.$('.checkbox');
var $dirents_op = this.$('#multi-dirents-op');
if (el.hasClass('checkbox-checked')) {
all_dirent_checkbox.addClass('checkbox-checked');
dir.each(function(model) {
model.set({'selected': true}, {silent: true});
});
$dirents_op.css({'display':'inline'});
} else {
all_dirent_checkbox.removeClass('checkbox-checked');
dir.each(function(model) {
model.set({'selected': false}, {silent: true});
});
$dirents_op.hide();
}
},
del: function () {
var dirents = this.dir;
var _this = this;
var del_dirents = function() {
$('#confirm-popup').append('<p style="color:red;">' + gettext("Processing...") + '</p>');
var selected_dirents = dirents.where({'selected':true}),
selected_names = [];
$(selected_dirents).each(function() {
selected_names.push(this.get('obj_name'));
});
$.ajax({
url: Common.getUrl({
name: 'del_dirents',
repo_id: dirents.repo_id
}) + '?parent_dir=' + encodeURIComponent(dirents.path),
type: 'POST',
dataType: 'json',
beforeSend: Common.prepareCSRFToken,
traditional: true,
data: {
'dirents_names': selected_names
},
success: function(data) {
var del_len = data['deleted'].length,
not_del_len = data['undeleted'].length,
msg_s, msg_f;
if (del_len > 0) {
if (del_len == selected_names.length) {
dirents.remove(selected_dirents);
_this.$('th .checkbox').removeClass('checkbox-checked');
_this.$('#multi-dirents-op').hide();
} else {
$(selected_dirents).each(function() {
if (data['deleted'].indexOf(this.get('obj_name')) != -1) {
dirents.remove(this);
}
});
}
if (del_len == 1) {
msg_s = gettext("Successfully deleted %(name)s.");
} else if (del_len == 2) {
msg_s = gettext("Successfully deleted %(name)s and 1 other item.");
} else {
msg_s = gettext("Successfully deleted %(name)s and %(amount)s other items.");
}
msg_s = msg_s.replace('%(name)s', Common.HTMLescape(data['deleted'][0])).replace('%(amount)s', del_len - 1);
Common.feedback(msg_s, 'success');
}
if (not_del_len > 0) {
if (not_del_len == 1) {
msg_f = gettext("Failed to delete %(name)s.");
} else if (not_del_len == 2) {
msg_f = gettext("Failed to delete %(name)s and 1 other item.");
} else {
msg_f = gettext("Failed to delete %(name)s and %(amount)s other items.");
}
msg_f = msg_f.replace('%(name)s', Common.HTMLescape(data['undeleted'][0])).replace('%(amount)s', not_del_len - 1);
Common.feedback(msg_f, 'error');
}
$.modal.close();
},
error: function(xhr, textStatus, errorThrown) {
$.modal.close();
Common.ajaxErrorHandler(xhr, textStatus, errorThrown);
}
});
};
Common.showConfirm(gettext("Delete Items"),
gettext("Are you sure you want to delete these selected items?"),
del_dirents);
},
mv: function () {
this.mvcp({'op':'mv'});
},
cp: function () {
this.mvcp({'op':'cp'});
},
mvcp: function (params) {
var dir = this.dir;
var op = params.op;
var title = op == 'mv' ? gettext("Move selected item(s) to:") : gettext("Copy selected item(s) to:");
var show_cur_repo = true;
if (dir.user_perm == 'r') {
show_cur_repo = false;
}
var form = $(this.mvcpTemplate({
form_title: title,
op_type: op,
obj_type: '',
obj_name: '',
show_cur_repo: show_cur_repo,
show_other_repos: !dir.encrypted
}));
form.modal({appendTo:'#main', autoResize:true, focus:false});
$('#simplemodal-container').css({'width':'auto', 'height':'auto'});
if (show_cur_repo) {
FileTree.renderTreeForPath({
repo_name: dir.repo_name,
repo_id: dir.repo_id,
path: dir.path
});
}
if (!dir.encrypted) {
FileTree.prepareOtherReposTree({cur_repo_id: dir.repo_id});
}
var _this = this;
var dirents = this.dir;
// get models
var dirs = dirents.where({'is_dir':true, 'selected':true}),
files = dirents.where({'is_file':true, 'selected':true});
var dir_names = [], file_names = [];
$(dirs).each(function() {
dir_names.push(this.get('obj_name'));
});
$(files).each(function() {
file_names.push(this.get('obj_name'));
});
form.submit(function() {
var dst_repo = $('[name="dst_repo"]', form).val(),
dst_path = $('[name="dst_path"]', form).val(),
url_main;
var cur_path = dirents.path;
var url_obj = {repo_id:dirents.repo_id};
if (!$.trim(dst_repo) || !$.trim(dst_path)) {
$('.error', form).removeClass('hide');
return false;
}
if (dst_repo == dirents.repo_id && dst_path == cur_path) {
$('.error', form).html(gettext("Invalid destination path")).removeClass('hide');
return false;
}
Common.disableButton($('[type="submit"]', form));
form.append('<p style="color:red;">' + gettext("Processing...") + '</p>');
if (dst_repo == dirents.repo_id) {
// when mv/cp in current lib, files/dirs can be handled in batch, and no need to show progress
url_obj.name = op == 'mv' ? 'mv_dirents' : 'cp_dirents';
$.ajax({
url: Common.getUrl(url_obj) + '?parent_dir=' + encodeURIComponent(cur_path),
type: 'POST',
dataType: 'json',
beforeSend: Common.prepareCSRFToken,
traditional: true,
data: {
'file_names': file_names,
'dir_names': dir_names,
'dst_repo': dst_repo,
'dst_path': dst_path
},
success: function(data) {
var success_len = data['success'].length,
msg_s, msg_f,
view_url = data['url'];
$.modal.close();
if (success_len > 0) {
if (op == 'mv') {
if (success_len == files.length + dirs.length) {
dirents.remove(dirs);
dirents.remove(files);
_this.$('th .checkbox').removeClass('checkbox-checked');
_this.$('#multi-dirents-op').hide();
} else {
$(dirs).each(function() {
if (this.get('obj_name') in data['success']) {
dirents.remove(this);
}
});
$(files).each(function() {
if (this.get('obj_name') in data['success']) {
dirents.remove(this);
}
});
}
if (success_len == 1) {
msg_s = gettext("Successfully moved %(name)s.");
} else if (success_len == 2) {
msg_s = gettext("Successfully moved %(name)s and 1 other item.");
} else {
msg_s = gettext("Successfully moved %(name)s and %(amount)s other items.");
}
} else { // cp
if (success_len == 1) {
msg_s = gettext("Successfully copied %(name)s.");
} else if (success_len == 2) {
msg_s = gettext("Successfully copied %(name)s and 1 other item.");
} else {
msg_s = gettext("Successfully copied %(name)s and %(amount)s other items.");
}
}
msg_s = msg_s.replace('%(name)s', Common.HTMLescape(data['success'][0])).replace('%(amount)s', success_len - 1);
//msg_s += ' <a href="' + view_url + '">' + "View" + '</a>';
Common.feedback(msg_s, 'success');
}
if (data['failed'].length > 0) {
if (op == 'mv') {
if (data['failed'].length > 1) {
msg_f = gettext("Internal error. Failed to move %(name)s and %(amount)s other item(s).");
} else {
msg_f = gettext("Internal error. Failed to move %(name)s.");
}
} else {
if (data['failed'].length > 1) {
msg_f = gettext("Internal error. Failed to copy %(name)s and %(amount)s other item(s).");
} else {
msg_f = gettext("Internal error. Failed to copy %(name)s.");
}
}
msg_f = msg_f.replace('%(name)s', Common.HTMLescape(data['failed'][0])).replace('%(amount)s', data['failed'].length - 1);
Common.feedback(msg_f, 'error');
}
},
error: function(xhr, textStatus, errorThrown) {
$.modal.close();
Common.ajaxErrorHandler(xhr, textStatus, errorThrown);
}
});
} else {
// when mv/cp to another lib, files/dirs should be handled one by one, and need to show progress
var op_objs = dirents.where({'selected':true}),
i = 0;
// progress popup
var mv_progress_popup = $(_this.mvProgressTemplate());
var details = $('#mv-details', mv_progress_popup),
cancel_btn = $('#cancel-mv', mv_progress_popup),
other_info = $('#mv-other-info', mv_progress_popup);
var mvcpDirent = function () {
var op_obj = op_objs[i],
obj_type = op_obj.get('is_dir') ? 'dir':'file',
obj_name = op_obj.get('obj_name'),
post_url,
post_data;
if (op == 'mv') {
url_obj.name = obj_type == 'dir' ? 'mv_dir' : 'mv_file';
} else {
url_obj.name = obj_type == 'dir' ? 'cp_dir' : 'cp_file';
}
post_url = Common.getUrl(url_obj) + '?path=' + encodeURIComponent(cur_path) + '&obj_name=' + encodeURIComponent(obj_name);
post_data = {
'dst_repo': dst_repo,
'dst_path': dst_path
};
var after_op_success = function (data) {
var det_text = op == 'mv' ? gettext("Moving file %(index)s of %(total)s") : gettext("Copying file %(index)s of %(total)s");
details.html(det_text.replace('%(index)s', i + 1).replace('%(total)s', op_objs.length)).removeClass('vh');
cancel_btn.removeClass('hide');
var req_progress = function () {
var task_id = data['task_id'];
cancel_btn.data('task_id', task_id);
$.ajax({
url: Common.getUrl({name:'get_cp_progress'}) + '?task_id=' + encodeURIComponent(task_id),
dataType: 'json',
success: function(data) {
var bar = $('.ui-progressbar-value', $('#mv-progress'));
if (!data['failed'] && !data['canceled'] && !data['successful']) {
setTimeout(req_progress, 1000);
} else {
if (data['successful']) {
bar.css('width', parseInt((i + 1)/op_objs.length*100, 10) + '%').show();
if (op == 'mv') {
dirents.remove(op_obj);
}
endOrContinue();
} else { // failed or canceled
if (data['failed']) {
var error_msg = op == 'mv' ? gettext('Failed to move %(name)s') : gettext('Failed to copy %(name)s');
cancel_btn.after('<p class="error">' + error_msg.replace('%(name)s', Common.HTMLescape(obj_name)) + '</p>');
end();
}
}
}
},
error: function(xhr, textStatus, errorThrown) {
var error;
if (xhr.responseText) {
error = $.parseJSON(xhr.responseText).error;
} else {
error = gettext("Failed. Please check the network.");
}
cancel_btn.after('<p class="error">' + error + '</p>');
end();
}
});
}; // 'req_progress' ends
if (i == 0) {
$.modal.close();
setTimeout(function () {
mv_progress_popup.modal({containerCss: {
width: 300,
height: 150,
paddingTop: 50
}, focus:false});
$('#mv-progress').progressbar();
req_progress();
}, 100);
} else {
req_progress();
}
}; // 'after_op_success' ends
Common.ajaxPost({
'form': form,
'post_url': post_url,
'post_data': post_data,
'after_op_success': after_op_success,
'form_id': form.attr('id')
});
}; // 'mvcpDirent' ends
var endOrContinue = function () {
if (i == op_objs.length - 1) {
setTimeout(function () { $.modal.close(); }, 500);
} else {
mvcpDirent(++i);
}
};
var end = function () {
setTimeout(function () { $.modal.close(); }, 500);
};
mvcpDirent();
cancel_btn.click(function() {
Common.disableButton(cancel_btn);
var task_id = $(this).data('task_id');
$.ajax({
url: Common.getUrl({name:'cancel_cp'}) + '?task_id=' + encodeURIComponent(task_id),
dataType: 'json',
success: function(data) {
other_info.html(gettext("Canceled.")).removeClass('hide');
cancel_btn.addClass('hide');
end();
},
error: function(xhr, textStatus, errorThrown) {
var error;
if (xhr.responseText) {
error = $.parseJSON(xhr.responseText).error;
} else {
error = gettext("Failed. Please check the network.");
}
other_info.html(error).removeClass('hide');
Common.enableButton(cancel_btn);
}
});
});
}
return false;
});
},
onWindowScroll: function () {
// 'more'
var dir = this.dir,
start = dir.more_start;
if (dir.dirent_more &&
$(window).scrollTop() + $(window).height() > $(document).height() - $('#footer').outerHeight(true) &&
start != dir.last_start) {
var loading_tip = this.$('.loading-tip'),
_this = this;
dir.last_start = start;
dir.fetch({
cache: false,
remove: false,
data: {
'p': dir.path,
'start': dir.more_start
},
success: function (collection, response, opts) {
if (!response.dirent_more ) { // no 'more'
loading_tip.hide();
}
_this.getImageThumbnail();
},
error: function(xhr, textStatus, errorThrown) {
loading_tip.hide();
Common.ajaxErrorHandler(xhr, textStatus, errorThrown);
}
});
}
// fixed 'dir-op-bar'
var op_bar = this.$dir_op_bar,
path_bar = this.$path_bar, // the element before op_bar
repo_file_list = this.$('.repo-file-list'); // the element after op_bar
var op_bar_top = path_bar.offset().top + path_bar.outerHeight(true);
var fixed_styles = {
'position': 'fixed',
'top': 0,
'left': path_bar.offset().left,
'z-index': 12 // make 'op_bar' shown on top of the checkboxes
};
if ($(window).scrollTop() >= op_bar_top) {
repo_file_list.css({'margin-top':op_bar.outerHeight(true)});
op_bar.outerWidth(this.$el.width()).css(fixed_styles);
} else {
repo_file_list.css({'margin-top':0});
op_bar.removeAttr('style');
}
}
});
return DirView;
});
<file_sep>/seahub/api2/views_auth.py
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
from seaserv import seafile_api
from seahub import settings
from seahub.api2.utils import json_response, api_error
from seahub.api2.authentication import TokenAuthentication
from seahub.api2.models import Token, TokenV2
from seahub.base.models import ClientLoginToken
from seahub.utils import gen_token
class LogoutDeviceView(APIView):
"""Removes the api token of a device that has already logged in. If the device
is a desktop client, also remove all sync tokens of repos synced on that
client .
"""
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle,)
@json_response
def post(self, request, format=None):
auth_token = request.auth
if isinstance(auth_token, TokenV2) and auth_token.is_desktop_client():
seafile_api.delete_repo_tokens_by_peer_id(request.user.username, auth_token.device_id)
auth_token.delete()
return {}
class ClientLoginTokenView(APIView):
"""Generate a token which can be used later to login directly.
This is used to quickly login to seahub from desktop clients. The token
can only be used once, and would only be valid in 30 seconds after
creation.
"""
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle,)
@json_response
def post(self, request, format=None):
randstr = gen_token(max_length=32)
token = ClientLoginToken(randstr, request.user.username)
token.save()
return {'token': randstr}
<file_sep>/static/scripts/app/views/group.js
define([
'jquery',
'underscore',
'backbone',
'common',
'app/collections/group-repos',
'app/views/group-repo',
'app/views/add-group-repo',
'app/views/group-side-nav'
], function($, _, Backbone, Common, GroupRepos, GroupRepoView,
AddGroupRepoView, GroupSideNavView) {
'use strict';
var GroupView = Backbone.View.extend({
el: '#group-repo-tabs',
reposHdTemplate: _.template($('#shared-repos-hd-tmpl').html()),
events: {
'click .repo-create': 'createRepo',
'click .by-name': 'sortByName',
'click .by-time': 'sortByTime'
},
initialize: function(options) {
this.$tabs = this.$el;
this.$table = this.$('table');
this.$tableHead = this.$('thead');
this.$tableBody = this.$('tbody');
this.$loadingTip = this.$('.loading-tip');
this.$emptyTip = this.$('.empty-tips');
this.sideNavView = new GroupSideNavView();
this.repos = new GroupRepos();
this.listenTo(this.repos, 'add', this.addOne);
this.listenTo(this.repos, 'reset', this.reset);
this.dirView = options.dirView;
},
addOne: function(repo, collection, options) {
var view = new GroupRepoView({
model: repo,
group_id: this.group_id,
is_staff: this.repos.is_staff
});
if (options.prepend) {
this.$tableBody.prepend(view.render().el);
} else {
this.$tableBody.append(view.render().el);
}
},
renderReposHd: function() {
this.$tableHead.html(this.reposHdTemplate());
},
reset: function() {
this.$('.error').hide();
this.$loadingTip.hide();
if (this.repos.length) {
this.$emptyTip.hide();
this.renderReposHd();
this.$tableBody.empty();
this.repos.each(this.addOne, this);
this.$table.show();
} else {
this.$emptyTip.show();
this.$table.hide();
}
},
showSideNav: function () {
var sideNavView = this.sideNavView;
if (sideNavView.group_id && sideNavView.group_id == this.group_id) {
sideNavView.show();
return;
}
sideNavView.render(this.group_id);
sideNavView.show();
},
showRepoList: function(group_id) {
this.group_id = group_id;
this.showSideNav();
this.dirView.hide();
this.$emptyTip.hide();
this.$tabs.show();
this.$table.hide();
var $loadingTip = this.$loadingTip;
$loadingTip.show();
var _this = this;
this.repos.setGroupID(group_id);
this.repos.fetch({
cache: false,
reset: true,
data: {from: 'web'},
success: function (collection, response, opts) {
},
error: function (collection, response, opts) {
$loadingTip.hide();
var $error = _this.$('.error');
var err_msg;
if (response.responseText) {
if (response['status'] == 401 || response['status'] == 403) {
err_msg = gettext("Permission error");
} else {
err_msg = gettext("Error");
}
} else {
err_msg = gettext('Please check the network.');
}
$error.html(err_msg).show();
}
});
},
hideRepoList: function() {
this.$tabs.hide();
},
showDir: function(group_id, repo_id, path) {
this.group_id = group_id;
this.showSideNav();
this.hideRepoList();
this.dirView.showDir('group/' + this.group_id, repo_id, path);
},
createRepo: function() {
new AddGroupRepoView(this.repos);
},
sortByName: function() {
this.$('.by-time .sort-icon').hide();
var repos = this.repos;
var el = this.$('.by-name .sort-icon');
repos.comparator = function(a, b) { // a, b: model
var result = Common.compareTwoWord(a.get('name'), b.get('name'));
if (el.hasClass('icon-caret-up')) {
return -result;
} else {
return result;
}
};
repos.sort();
this.$tableBody.empty();
repos.each(this.addOne, this);
el.toggleClass('icon-caret-up icon-caret-down').show();
repos.comparator = null;
},
sortByTime: function() {
this.$('.by-name .sort-icon').hide();
var repos = this.repos;
var el = this.$('.by-time .sort-icon');
repos.comparator = function(a, b) { // a, b: model
if (el.hasClass('icon-caret-down')) {
return a.get('mtime') < b.get('mtime') ? 1 : -1;
} else {
return a.get('mtime') < b.get('mtime') ? -1 : 1;
}
};
repos.sort();
this.$tableBody.empty();
repos.each(this.addOne, this);
el.toggleClass('icon-caret-up icon-caret-down').show();
repos.comparator = null;
},
hide: function() {
this.sideNavView.hide();
this.hideRepoList();
this.dirView.hide();
this.$emptyTip.hide();
}
});
return GroupView;
});
<file_sep>/seahub/group/signals.py
import django.dispatch
grpmsg_added = django.dispatch.Signal(providing_args=["group_id", "from_email", "message"])
grpmsg_reply_added = django.dispatch.Signal(providing_args=["msg_id", "from_email", "grpmsg_topic", "reply_msg"])
group_join_request = django.dispatch.Signal(providing_args=["staffs", "username", "group", "join_reqeust_msg"])
add_user_to_group = django.dispatch.Signal(providing_args=["group_staff", "group_id", "added_user"])
<file_sep>/seahub/notifications/views.py
import json
import logging
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from seahub.auth.decorators import login_required, login_required_ajax
from seahub.notifications.models import Notification, NotificationForm, \
UserNotification
from seahub.notifications.utils import refresh_cache
from seahub.avatar.util import get_default_avatar_url
# Get an instance of a logger
logger = logging.getLogger(__name__)
@login_required
def notification_list(request):
if not request.user.is_staff:
raise Http404
notes = Notification.objects.all().order_by('-id')
return render_to_response('notifications/notification_list.html', {
'notes': notes,
}, context_instance=RequestContext(request))
@login_required
def notification_add(request):
if not request.user.is_staff or request.method != 'POST':
raise Http404
f = NotificationForm(request.POST)
f.save()
return HttpResponseRedirect(reverse('notification_list', args=[]))
@login_required
def notification_delete(request, nid):
if not request.user.is_staff:
raise Http404
Notification.objects.filter(id=nid).delete()
refresh_cache()
return HttpResponseRedirect(reverse('notification_list', args=[]))
@login_required
def set_primary(request, nid):
if not request.user.is_staff:
raise Http404
# TODO: use transaction?
Notification.objects.filter(primary=1).update(primary=0)
Notification.objects.filter(id=nid).update(primary=1)
refresh_cache()
return HttpResponseRedirect(reverse('notification_list', args=[]))
########## user notifications
@login_required
def user_notification_list(request):
"""
Arguments:
- `request`:
"""
username = request.user.username
count = 25 # initial notification count
limit = 25 # next a mount of notifications fetched by AJAX
notices = UserNotification.objects.get_user_notifications(username)[:count]
# Add 'msg_from' or 'default_avatar_url' to notice.
notices = add_notice_from_info(notices)
notices_more = True if len(notices) == count else False
return render_to_response("notifications/user_notification_list.html", {
'notices': notices,
'start': count,
'limit': limit,
'notices_more': notices_more,
}, context_instance=RequestContext(request))
@login_required_ajax
def user_notification_more(request):
"""Fetch next ``limit`` notifications starts from ``start``.
Arguments:
- `request`:
- `start`:
- `limit`:
"""
username = request.user.username
start = int(request.GET.get('start', 0))
limit = int(request.GET.get('limit', 0))
notices = UserNotification.objects.get_user_notifications(username)[
start: start+limit]
# Add 'msg_from' or 'default_avatar_url' to notice.
notices = add_notice_from_info(notices)
notices_more = True if len(notices) == limit else False
new_start = start+limit
ctx = {'notices': notices}
html = render_to_string("notifications/user_notification_tr.html", ctx)
ct = 'application/json; charset=utf-8'
return HttpResponse(json.dumps({
'html':html,
'notices_more':notices_more,
'new_start': new_start}), content_type=ct)
@login_required
def user_notification_remove(request):
"""
Arguments:
- `request`:
"""
UserNotification.objects.remove_user_notifications(request.user.username)
messages.success(request, _("Successfully cleared all notices."))
next = request.META.get('HTTP_REFERER', None)
if not next:
next = settings.SITE_ROOT
return HttpResponseRedirect(next)
def add_notice_from_info(notices):
'''Add 'msg_from' or 'default_avatar_url' to notice.
'''
default_avatar_url = get_default_avatar_url()
for notice in notices:
if notice.is_user_message():
d = notice.user_message_detail_to_dict()
if d.get('msg_from') is not None:
notice.msg_from = d.get('msg_from')
else:
notice.default_avatar_url = default_avatar_url
elif notice.is_group_msg():
d = notice.group_message_detail_to_dict()
if d.get('msg_from') is not None:
notice.msg_from = d.get('msg_from')
else:
notice.default_avatar_url = default_avatar_url
elif notice.is_grpmsg_reply():
d = notice.grpmsg_reply_detail_to_dict()
if d.get('reply_from') is not None:
notice.msg_from = d.get('reply_from')
else:
notice.default_avatar_url = default_avatar_url
elif notice.is_file_uploaded_msg():
notice.default_avatar_url = default_avatar_url
elif notice.is_repo_share_msg() or notice.is_priv_file_share_msg():
try:
d = json.loads(notice.detail)
notice.msg_from = d['share_from']
except Exception as e:
logger.error(e)
notice.default_avatar_url = default_avatar_url
elif notice.is_group_join_request():
try:
d = json.loads(notice.detail)
notice.msg_from = d['username']
except Exception as e:
logger.error(e)
notice.default_avatar_url = default_avatar_url
elif notice.is_add_user_to_group():
try:
d = json.loads(notice.detail)
notice.msg_from = d['group_staff']
except Exception as e:
logger.error(e)
notice.default_avatar_url = default_avatar_url
else:
pass
return notices
<file_sep>/tests/api/test_misc.py
import json
import unittest
import pytest
import requests
from django.test import TestCase
from seahub import settings
from tests.api.apitestbase import ApiTestBase
from tests.api.urls import LIST_GROUP_AND_CONTACTS_URL, SERVER_INFO_URL
class MiscApiTest(ApiTestBase, TestCase):
def test_list_group_and_contacts(self):
res = self.get(LIST_GROUP_AND_CONTACTS_URL).json()
self.assertIsNotNone(res)
self.assertIsInstance(res['contacts'], list)
self.assertIsNotNone(res['umsgnum'])
self.assertIsNotNone(res['replynum'])
self.assertIsInstance(res['groups'], list)
self.assertIsNotNone(res['gmsgnum'])
self.assertIsNotNone(res['newreplies'])
def test_server_info(self):
r = requests.get(SERVER_INFO_URL)
r.raise_for_status()
info = r.json()
self.assertTrue('version' in info)
self.assertTrue('seafile-basic' in info['features'])
self.assertFalse('disable-sync-with-any-folder' in info['features'])
@pytest.mark.xfail
def test_server_info_with_disable_sync(self):
settings.DISABLE_SYNC_WITH_ANY_FOLDER = True
resp = self.client.get('/api2/server-info/')
info = json.loads(resp.content)
self.assertTrue('disable-sync-with-any-folder' in info['features'])
<file_sep>/test-requirements.txt
exam==0.10.5
splinter==0.7.2
requests==2.3.0
pytest==2.7.0
pytest-django==2.8.0
mock==1.0.1
<file_sep>/seahub/auth/models.py
import datetime
import hashlib
import urllib
# import auth
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.db.models.manager import EmptyManager
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _
UNUSABLE_PASSWORD = '!' # This will never be a valid hash
def get_hexdigest(algorithm, salt, raw_password):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or 'crypt').
"""
raw_password, salt = smart_str(raw_password), smart_str(salt)
if algorithm == 'crypt':
try:
import crypt
except ImportError:
raise ValueError('"crypt" password algorithm not supported in this environment')
return crypt.crypt(raw_password, salt)
if algorithm == 'md5':
return hashlib.md5(salt + raw_password).hexdigest()
elif algorithm == 'sha1':
return hashlib.sha1(salt + raw_password).hexdigest()
raise ValueError("Got unknown password algorithm type in password.")
def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
"""
algo, salt, hsh = enc_password.split('$')
return hsh == get_hexdigest(algo, salt, raw_password)
class SiteProfileNotAvailable(Exception):
pass
class AnonymousUser(object):
id = None
username = ''
is_staff = False
is_active = False
is_superuser = False
_groups = EmptyManager()
_user_permissions = EmptyManager()
def __init__(self):
pass
def __unicode__(self):
return 'AnonymousUser'
def __str__(self):
return unicode(self).encode('utf-8')
def __eq__(self, other):
return isinstance(other, self.__class__)
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return 1 # instances always return the same hash value
def save(self):
raise NotImplementedError
def delete(self):
raise NotImplementedError
def set_password(self, raw_password):
raise NotImplementedError
def check_password(self, raw_password):
raise NotImplementedError
def _get_groups(self):
return self._groups
groups = property(_get_groups)
def _get_user_permissions(self):
return self._user_permissions
user_permissions = property(_get_user_permissions)
def get_group_permissions(self, obj=None):
return set()
def get_all_permissions(self, obj=None):
return _user_get_all_permissions(self, obj=obj)
def has_perm(self, perm, obj=None):
return _user_has_perm(self, perm, obj=obj)
def has_perms(self, perm_list, obj=None):
for perm in perm_list:
if not self.has_perm(perm, obj):
return False
return True
def has_module_perms(self, module):
return _user_has_module_perms(self, module)
def get_and_delete_messages(self):
return []
def is_anonymous(self):
return True
def is_authenticated(self):
return False
<file_sep>/tests/api/urls.py
from tests.common.common import USERNAME
from tests.common.utils import apiurl
PING_URL = apiurl('/api2/ping/')
TOKEN_URL = apiurl('/api2/auth-token/')
AUTH_PING_URL = apiurl('/api2/auth/ping/')
ACCOUNTS_URL = apiurl('/api2/accounts/')
ACCOUNT_INFO_URL = apiurl('/api2/account/info/')
AVATAR_BASE_URL = apiurl(u'/api2/avatars/')
REPOS_URL = apiurl('/api2/repos/')
DEFAULT_REPO_URL = apiurl('/api2/default-repo/')
VIRTUAL_REPOS_URL = apiurl('/api2/virtual-repos/')
GET_REPO_TOKENS_URL = apiurl('/api2/repo-tokens/')
GROUPS_URL = apiurl(u'/api2/groups/')
USERMSGS_URL = apiurl('/api2/user/msgs/', USERNAME)
USERMSGS_COUNT_URL = apiurl('/api2/unseen_messages/')
GROUPMSGS_URL = apiurl('/api2/group/msgs/')
GROUPMSGS_NREPLY_URL = apiurl('/api2/new_replies/')
STARREDFILES_URL = apiurl('/api2/starredfiles/')
SHARED_LINKS_URL = apiurl('/api2/shared-links/')
SHARED_LIBRARIES_URL = apiurl('/api2/shared-repos/')
BESHARED_LIBRARIES_URL = apiurl('/api2/beshared-repos/')
SHARED_FILES_URL = apiurl('/api2/shared-files/')
F_URL = apiurl('/api2/f/')
S_F_URL = apiurl('/api2/s/f/')
LIST_GROUP_AND_CONTACTS_URL = apiurl('/api2/groupandcontacts/')
DOWNLOAD_REPO_URL = apiurl('api2/repos/%s/download-info/')
LOGOUT_DEVICE_URL = apiurl('api2/logout-device/')
SERVER_INFO_URL = apiurl('/api2/server-info/')
CLIENT_LOGIN_TOKEN_URL = apiurl('/api2/client-login/')
<file_sep>/static/scripts/app/views/myhome.js
define([
'jquery',
'underscore',
'backbone',
'common',
'app/views/myhome-repos',
'app/views/myhome-sub-repos',
'app/views/myhome-shared-repos',
'app/views/starred-file',
'app/views/activities',
'app/views/myhome-side-nav'
], function($, _, Backbone, Common, ReposView, SubReposView,
SharedReposView, StarredFileView, ActivitiesView, MyhomeSideNavView) {
'use strict';
var MyHomeView = Backbone.View.extend({
el: '#main',
initialize: function(options) {
this.sideNavView = new MyhomeSideNavView();
this.reposView = new ReposView();
this.subReposView = new SubReposView();
this.sharedReposView = new SharedReposView();
this.starredFileView = new StarredFileView();
this.activitiesView = new ActivitiesView();
this.dirView = options.dirView;
this.currentView = this.reposView;
$('#initial-loading-view').hide();
},
showMyRepos: function() {
this.sideNavView.show();
this.currentView.hide();
this.reposView.show();
this.currentView = this.reposView;
},
showMySubRepos: function() {
this.sideNavView.show();
this.currentView.hide();
this.subReposView.show();
this.currentView = this.subReposView;
},
showSharedRepos: function() {
this.sideNavView.show();
this.currentView.hide();
this.sharedReposView.show();
this.currentView = this.sharedReposView;
},
showStarredFile: function() {
this.sideNavView.show({'cur_tab': 'starred'});
this.currentView.hide();
this.starredFileView.show();
this.currentView = this.starredFileView;
},
showActivities: function() {
this.sideNavView.show({'cur_tab': 'activities'});
this.currentView.hide();
this.activitiesView.show();
this.currentView = this.activitiesView;
},
showDir: function(category, repo_id, path) {
this.sideNavView.show();
var path = path || '/';
this.currentView.hide();
this.dirView.showDir(category, repo_id, path);
this.currentView = this.dirView;
},
hide: function() {
this.currentView.hide();
this.sideNavView.hide();
}
});
return MyHomeView;
});
<file_sep>/seahub/templates/pub_base.html
{% extends "myhome_base.html" %}
{% load seahub_tags i18n %}
{% load url from future %}
{% block sub_title %}{% trans "Organization" %} - {% endblock %}
{% block cur_pubinfo %}cur{% endblock %}
{% block left_panel %}
<div class="side-tabnav">
<h3 class="hd">{% trans "Organization" %}</h3>
<ul class="side-tabnav-tabs">
<li class="tab {% block cur_lib %}{% endblock %}"><a href="{{ SITE_ROOT }}#org/"><span class="sf2-icon-library"></span>{% trans "Libraries" %}</a></li>
<li class="tab {% block cur_user %}{% endblock %}"><a href="{% url 'pubuser' %}"><span class="sf2-icon-user"></span>{% trans "Members" %}</a></li>
</ul>
</div>
{% endblock %}
<file_sep>/seahub/notifications/urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('seahub.notifications.views',
# url(r'^$', 'notification_list', name='notification_list'),
url(r'^add/$', 'notification_add', name='notification_add'),
url(r'^delete/(?P<nid>[\d]+)/$', 'notification_delete', name='notification_delete'),
url(r'^set-primary/(?P<nid>[\d]+)/$', 'set_primary', name='set_primary'),
########## user notifications
url(r'^list/$', 'user_notification_list', name='user_notification_list'),
url(r'^more/$', 'user_notification_more', name='user_notification_more'),
url(r'^remove/$', 'user_notification_remove', name='user_notification_remove'),
)
<file_sep>/seahub/base/decorators.py
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseRedirect, HttpResponseNotAllowed
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.http import urlquote
from seaserv import get_repo, is_passwd_set
from seahub.options.models import UserOptions, CryptoOptionNotSetError
from seahub.base.sudo_mode import sudo_mode_check
from seahub.utils import render_error
from django.utils.translation import ugettext as _
from seahub.settings import FORCE_SERVER_CRYPTO, ENABLE_SUDO_MODE
def sys_staff_required(func):
"""
Decorator for views that checks the user is system staff.
"""
def _decorated(request, *args, **kwargs):
if not request.user.is_staff:
raise Http404
if ENABLE_SUDO_MODE and not sudo_mode_check(request):
return HttpResponseRedirect(
reverse('sys_sudo_mode') + '?next=' + urlquote(request.get_full_path()))
return func(request, *args, **kwargs)
return _decorated
def user_mods_check(func):
"""Decorator for views that need user's enabled/available modules.
Populate modules to ``request.user``.
Arguments:
- `func`:
"""
def _decorated(request, *args, **kwargs):
username = request.user.username
request.user.mods_available = get_available_mods_by_user(username)
request.user.mods_enabled = get_enabled_mods_by_user(username)
return func(request, *args, **kwargs)
_decorated.__name__ = func.__name__
return _decorated
def repo_passwd_set_required(func):
"""
Decorator for views to redirect user to repo decryption page if repo is
encrypt and password is not set by user.
"""
def _decorated(request, *args, **kwargs):
repo_id = kwargs.get('repo_id', None)
if not repo_id:
raise Exception, 'Repo id is not found in url.'
repo = get_repo(repo_id)
if not repo:
raise Http404
username = request.user.username
if repo.encrypted:
try:
server_crypto = UserOptions.objects.is_server_crypto(username)
except CryptoOptionNotSetError:
return render_to_response('options/set_user_options.html', {
}, context_instance=RequestContext(request))
if (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \
and not is_passwd_set(repo_id, username):
return render_to_response('decrypt_repo_form.html', {
'repo': repo,
'next': request.get_full_path(),
'force_server_crypto': FORCE_SERVER_CRYPTO,
}, context_instance=RequestContext(request))
if repo.enc_version == 2 and not server_crypto:
return render_error(request, _(u'Files in this library can not be viewed online.'))
return func(request, *args, **kwargs)
return _decorated
def require_POST(func):
def decorated(request, *args, **kwargs):
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
return func(request, *args, **kwargs)
return decorated
from seahub.views.modules import get_enabled_mods_by_user, \
get_available_mods_by_user # Move here to avoid circular import
<file_sep>/tests/seahub/views/test_sysadmin.py
import os
from mock import patch
from django.core.urlresolvers import reverse
from django.http.cookie import parse_cookie
from tests.common.utils import randstring
from seahub.base.accounts import User
from seahub.utils.ms_excel import write_xls as real_write_xls
from seahub.test_utils import BaseTestCase
from seahub.share.models import FileShare
from seaserv import ccnet_threaded_rpc, seafile_api
class UserToggleStatusTest(BaseTestCase):
def setUp(self):
self.login_as(self.admin)
def test_can_activate(self):
old_passwd = self.user.enc_password
resp = self.client.post(
reverse('user_toggle_status', args=[self.user.username]),
{'s': 1},
HTTP_X_REQUESTED_WITH='XMLHttpRequest'
)
self.assertEqual(200, resp.status_code)
self.assertContains(resp, '"success": true')
u = User.objects.get(email=self.user.username)
assert u.is_active is True
assert u.enc_password == old_<PASSWORD>
def test_can_deactivate(self):
old_passwd = self.user.<PASSWORD>
resp = self.client.post(
reverse('user_toggle_status', args=[self.user.username]),
{'s': 0},
HTTP_X_REQUESTED_WITH='XMLHttpRequest'
)
self.assertEqual(200, resp.status_code)
self.assertContains(resp, '"success": true')
u = User.objects.get(email=self.user.username)
assert u.is_active is False
assert u.enc_password == <PASSWORD>passwd
class UserResetTest(BaseTestCase):
def setUp(self):
self.login_as(self.admin)
def test_can_reset(self):
old_passwd = self.user.enc_password
resp = self.client.post(
reverse('user_reset', args=[self.user.email])
)
self.assertEqual(302, resp.status_code)
u = User.objects.get(email=self.user.username)
assert u.enc_password != old_passwd
class BatchUserMakeAdminTest(BaseTestCase):
def setUp(self):
self.login_as(self.admin)
def test_can_make_admins(self):
resp = self.client.post(
reverse('batch_user_make_admin'), {
'set_admin_emails': self.user.username
}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'
)
old_passwd = <PASSWORD>
self.assertContains(resp, '"success": true')
u = User.objects.get(email=self.user.username)
assert u.is_staff is True
assert u.enc_password == old_passwd
# class UserMakeAdminTest(TestCase, Fixtures):
# def test_can_make_admin(self):
# self.client.post(
# reverse('auth_login'), {'username': self.admin.username,
# 'password': '<PASSWORD>'}
# )
# resp = self.client.get(
# reverse('user_make_admin', args=[self.user.id])
# )
# old_passwd = <PASSWORD>
# self.assertEqual(302, resp.status_code)
# u = User.objects.get(email=self.user.username)
# assert u.is_staff is True
# assert u.enc_password == <PASSWORD>
class UserRemoveTest(BaseTestCase):
def setUp(self):
self.login_as(self.admin)
def test_can_remove(self):
# create one user
username = self.user.username
resp = self.client.post(
reverse('user_remove', args=[username])
)
self.assertEqual(302, resp.status_code)
assert 'Successfully deleted %s' % username in parse_cookie(resp.cookies)['messages']
assert len(ccnet_threaded_rpc.search_emailusers('DB', username, -1, -1)) == 0
class SudoModeTest(BaseTestCase):
def test_normal_user_raise_404(self):
self.login_as(self.user)
resp = self.client.get(reverse('sys_sudo_mode'))
self.assertEqual(404, resp.status_code)
def test_admin_get(self):
self.login_as(self.admin)
resp = self.client.get(reverse('sys_sudo_mode'))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed('sysadmin/sudo_mode.html')
def test_admin_post(self):
self.login_as(self.admin)
resp = self.client.post(reverse('sys_sudo_mode'), {
'username': self.admin.username,
'password': <PASSWORD>,
})
self.assertEqual(302, resp.status_code)
self.assertRedirects(resp, reverse('sys_useradmin'))
class SysGroupAdminExportExcelTest(BaseTestCase):
def setUp(self):
self.login_as(self.admin)
def test_can_export_excel(self):
resp = self.client.get(reverse('sys_group_admin_export_excel'))
self.assertEqual(200, resp.status_code)
assert 'application/ms-excel' in resp._headers['content-type']
class SysUserAdminExportExcelTest(BaseTestCase):
def setUp(self):
self.login_as(self.admin)
def test_can_export_excel(self):
resp = self.client.get(reverse('sys_useradmin_export_excel'))
self.assertEqual(200, resp.status_code)
assert 'application/ms-excel' in resp._headers['content-type']
def write_xls(self, sheet_name, head, data_list):
assert 'Role' in head
return real_write_xls(sheet_name, head, data_list)
@patch('seahub.views.sysadmin.write_xls')
@patch('seahub.views.sysadmin.is_pro_version')
def test_can_export_excel_in_pro(self, mock_is_pro_version, mock_write_xls):
mock_is_pro_version.return_value = True
mock_write_xls.side_effect = self.write_xls
mock_write_xls.assert_called_once()
resp = self.client.get(reverse('sys_useradmin_export_excel'))
self.assertEqual(200, resp.status_code)
assert 'application/ms-excel' in resp._headers['content-type']
class UserInfoTest(BaseTestCase):
def setUp(self):
self.login_as(self.admin)
# create group for admin user
self.admin_group_1_name = randstring(6)
self.admin_group_1_id = ccnet_threaded_rpc.create_group(self.admin_group_1_name,
self.admin.email)
# create another group for admin user
self.admin_group_2_name = randstring(6)
self.admin_group_2_id = ccnet_threaded_rpc.create_group(self.admin_group_2_name,
self.admin.email)
# create repo for admin user
self.admin_repo_name = randstring(6)
r = seafile_api.get_repo(self.create_repo(name=self.admin_repo_name,
desc='', username=self.admin.email, passwd=None))
self.admin_repo_id = r.id
# set common user as staff in admin user's group
ccnet_threaded_rpc.group_add_member(self.admin_group_1_id,
self.admin.email, self.user.email)
ccnet_threaded_rpc.group_set_admin(self.admin_group_1_id, self.user.email)
# add common user to admin user's another group
ccnet_threaded_rpc.group_add_member(self.admin_group_2_id,
self.admin.email, self.user.email)
# share admin user's repo to common user
seafile_api.share_repo(self.admin_repo_id, self.admin.email,
self.user.email, 'rw')
def tearDown(self):
# remove common user's repo and group
self.remove_group()
self.remove_repo()
# remove admin user's group
ccnet_threaded_rpc.remove_group(self.admin_group_1_id, self.admin.email)
# remove admin user's another group
ccnet_threaded_rpc.remove_group(self.admin_group_2_id, self.admin.email)
# remove amdin user's repo
seafile_api.remove_repo(self.admin_repo_id)
def test_can_render(self):
resp = self.client.get(reverse('user_info', kwargs={'email': self.user.email}))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed('sysadmin/userinfo.html')
self.assertContains(resp, 'id="owned"')
self.assertContains(resp, 'id="shared"')
self.assertContains(resp, 'id="shared-links"')
self.assertContains(resp, 'id="user-admin-groups"')
def test_can_list_owned_repos(self):
repo_id = self.repo.id
resp = self.client.get(reverse('user_info', kwargs={'email': self.user.email}))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed('sysadmin/userinfo.html')
self.assertContains(resp, repo_id)
def test_can_list_shared_repos(self):
resp = self.client.get(reverse('user_info', kwargs={'email': self.user.email}))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed('sysadmin/userinfo.html')
self.assertContains(resp, self.admin_repo_name)
def test_can_list_shared_links(self):
repo_id = self.repo.id
file_path = self.file
dir_path = self.folder
file_name = os.path.basename(file_path)
dir_name = os.path.basename(dir_path)
# create dir shared link for common user
share_info = {
'username': self.user.email,
'repo_id': repo_id,
'path': dir_path,
'password': <PASSWORD>,
'expire_date': None,
}
FileShare.objects.create_dir_link(**share_info)
# create file shared link for common user
share_info = {
'username': self.user.email,
'repo_id': repo_id,
'path': file_path,
'password': <PASSWORD>,
'expire_date': None,
}
FileShare.objects.create_file_link(**share_info)
resp = self.client.get(reverse('user_info', kwargs={'email': self.user.email}))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed('sysadmin/userinfo.html')
self.assertContains(resp, dir_name)
self.assertContains(resp, file_name)
def test_can_list_groups(self):
group_name = self.group.group_name
resp = self.client.get(reverse('user_info', kwargs={'email': self.user.email}))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed('sysadmin/userinfo.html')
self.assertContains(resp, 'Owned')
self.assertContains(resp, group_name)
self.assertContains(resp, 'Admin')
self.assertContains(resp, self.admin_group_1_name)
self.assertContains(resp, 'Member')
self.assertContains(resp, self.admin_group_2_name)
<file_sep>/seahub/api2/endpoints/be_shared_repo.py
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import UserRateThrottle
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
import seaserv
from seaserv import seafile_api
from seahub.api2.authentication import TokenAuthentication
from seahub.api2.utils import api_error
from seahub.utils import is_valid_username, is_org_context
json_content_type = 'application/json; charset=utf-8'
class BeSharedReposView(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def delete(self, request, repo_id, format=None):
if not seafile_api.get_repo(repo_id):
return api_error(status.HTTP_400_BAD_REQUEST, 'Library does not exist')
username = request.user.username
share_type = request.GET.get('share_type', None)
if share_type == 'personal':
from_email = request.GET.get('from', None)
if not is_valid_username(from_email):
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid argument')
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.org_remove_share(org_id,
repo_id,
from_email,
username)
else:
seaserv.remove_share(repo_id, from_email, username)
elif share_type == 'group':
from_email = request.GET.get('from', None)
if not is_valid_username(from_email):
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid argument')
group_id = request.GET.get('group_id', None)
group = seaserv.get_group(group_id)
if not group:
return api_error(status.HTTP_400_BAD_REQUEST, 'Group does not exist')
if not seaserv.check_group_staff(group_id, username) and \
not seafile_api.is_repo_owner(username, repo_id):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied')
if seaserv.is_org_group(group_id):
org_id = seaserv.get_org_id_by_group(group_id)
seaserv.del_org_group_repo(repo_id, org_id, group_id)
else:
seafile_api.unset_group_repo(repo_id, group_id, from_email)
elif share_type == 'public':
if is_org_context(request):
org_repo_owner = seafile_api.get_org_repo_owner(repo_id)
is_org_repo_owner = True if org_repo_owner == username else False
if not request.user.org.is_staff and not is_org_repo_owner:
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied')
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.unset_org_inner_pub_repo(org_id,
repo_id)
else:
if not seafile_api.is_repo_owner(username, repo_id) and \
not request.user.is_staff:
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied')
seaserv.unset_inner_pub_repo(repo_id)
else:
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid argument')
return Response({'success': True}, status=status.HTTP_200_OK)
<file_sep>/seahub/utils/http.py
"""Copied from latest django/utils/http.py::is_safe_url
"""
import unicodedata
import urlparse
import json
from functools import wraps
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
class _HTTPException(Exception):
def __init__(self, message=''):
self.message = message
def __str__(self):
return '%s: %s' % (self.__class__.__name__, self.message)
class BadRequestException(_HTTPException):
pass
class RequestForbbiddenException(_HTTPException):
pass
def is_safe_url(url, host=None):
"""
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host and uses a safe scheme).
Always returns ``False`` on an empty url.
"""
if url is not None:
url = url.strip()
if not url:
return False
# Chrome treats \ completely as /
url = url.replace('\\', '/')
# Chrome considers any URL with more than two slashes to be absolute, but
# urlparse is not so flexible. Treat any url with three slashes as unsafe.
if url.startswith('///'):
return False
url_info = urlparse.urlparse(url)
# Forbid URLs like http:///example.com - with a scheme, but without a hostname.
# In that URL, example.com is not the hostname but, a path component. However,
# Chrome will still consider example.com to be the hostname, so we must not
# allow this syntax.
if not url_info.netloc and url_info.scheme:
return False
# Forbid URLs that start with control characters. Some browsers (like
# Chrome) ignore quite a few control characters at the start of a
# URL and might consider the URL as scheme relative.
if unicodedata.category(url[0])[0] == 'C':
return False
return ((not url_info.netloc or url_info.netloc == host) and
(not url_info.scheme or url_info.scheme in ['http', 'https']))
JSON_CONTENT_TYPE = 'application/json; charset=utf-8'
def json_response(func):
@wraps(func)
def wrapped(*a, **kw):
try:
result = func(*a, **kw)
except BadRequestException, e:
return HttpResponseBadRequest(e.message)
except RequestForbbiddenException, e:
return HttpResponseForbidden(e.messages)
if isinstance(result, HttpResponse):
return result
else:
return HttpResponse(json.dumps(result), status=200,
content_type=JSON_CONTENT_TYPE)
return wrapped
def int_param(request, key):
v = request.GET.get(key, None)
if not v:
raise BadRequestException()
try:
return int(v)
except ValueError:
raise BadRequestException()
<file_sep>/static/scripts/app/views/folder-perm-item.js
define([
'jquery',
'underscore',
'backbone',
'common'
], function($, _, Backbone, Common) {
'use strict';
var FolderPermItemView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#folder-perm-item-tmpl').html()),
initialize: function(options) {
this.item_data = options.item_data;
this.repo_id = options.repo_id;
this.path = options.path;
this.render();
},
render: function () {
this.$el.html(this.template(this.item_data));
return this;
},
events: {
'mouseenter': 'showPermOpIcons',
'mouseleave': 'hidePermOpIcons',
'click .perm-edit-icon': 'editIconClick',
'change .perm-toggle-select': 'editPerm',
'click .delete-icon': 'deletePerm'
},
showPermOpIcons: function () {
this.$el.find('.op-icon').removeClass('vh');
},
hidePermOpIcons: function () {
this.$el.find('.op-icon').addClass('vh');
},
editIconClick: function (e) {
$(e.currentTarget).closest('td')
.find('.perm').addClass('hide').end()
.find('.perm-toggle-select').removeClass('hide');
},
editPerm: function (e) {
var _this = this;
var perm = $(e.currentTarget).val();
var post_data = {
'perm': perm,
'path': this.path,
'type': 'modify'
};
var for_user = this.item_data.for_user;
if (for_user) {
$.extend(post_data, {'user': this.item_data.user});
} else {
$.extend(post_data, {'group_id': this.item_data.group_id});
}
$.ajax({
url: Common.getUrl({
name: for_user ? 'set_user_folder_perm' : 'set_group_folder_perm',
repo_id: this.repo_id
}),
type: 'POST',
dataType: 'json',
cache: false,
beforeSend: Common.prepareCSRFToken,
data: post_data,
success: function() {
_this.item_data.perm = perm;
_this.render();
},
error: function(xhr) {
var err;
if (xhr.responseText) {
err = $.parseJSON(xhr.responseText).error;
} else {
err = gettext("Failed. Please check the network.");
}
if (for_user) {
$('#user-folder-perm .error').html(err).removeClass('hide');
} else {
$('#group-folder-perm .error').html(err).removeClass('hide');
}
}
});
},
deletePerm: function () {
var _this = this;
var post_data = {
'perm': this.item_data.perm,
'path': this.path,
'type': 'delete'
};
var for_user = this.item_data.for_user;
if (for_user) {
$.extend(post_data, {'user': this.item_data.user});
} else {
$.extend(post_data, {'group_id': this.item_data.group_id});
}
$.ajax({
url: Common.getUrl({
name: for_user ? 'set_user_folder_perm' : 'set_group_folder_perm',
repo_id: this.repo_id
}),
type: 'POST',
dataType: 'json',
cache: false,
beforeSend: Common.prepareCSRFToken,
data: post_data,
success: function() {
_this.remove();
},
error: function(xhr) {
var err;
if (xhr.responseText) {
err = $.parseJSON(xhr.responseText).error;
} else {
err = gettext("Failed. Please check the network.");
}
if (for_user) {
$('#user-folder-perm .error').html(err).removeClass('hide');
} else {
$('#group-folder-perm .error').html(err).removeClass('hide');
}
}
});
}
});
return FolderPermItemView;
});
<file_sep>/seahub/message/urls.py
from django.conf.urls.defaults import *
from django.views.generic.base import RedirectView
from views import message_list, message_send ,user_msg_list ,msg_count
urlpatterns = patterns("",
(r'^$', RedirectView.as_view(url='list')),
url(r'^list/$', message_list, name='message_list'),
# url(r'^u/(?P<to_email>[^/]+)/$', user_msg_list, name='user_msg_list'),
url(r'^message_send/$', message_send, name='message_send'),
url(r'^msg_count/$', msg_count, name='msg_count'),
)
<file_sep>/seahub/share/signals.py
import django.dispatch
share_repo_to_user_successful = django.dispatch.Signal(providing_args=["from_user", "to_user", "repo"])
<file_sep>/tests/seahub/thirdpart/shibboleth/test_middleware.py
from mock import Mock
from django.conf import settings
from django.test import RequestFactory
from seahub.profile.models import Profile
from seahub.test_utils import BaseTestCase
from shibboleth.middleware import ShibbolethRemoteUserMiddleware
settings.AUTHENTICATION_BACKENDS += (
'shibboleth.backends.ShibbolethRemoteUserBackend',
)
class ShibbolethRemoteUserMiddlewareTest(BaseTestCase):
def setUp(self):
self.middleware = ShibbolethRemoteUserMiddleware()
self.factory = RequestFactory()
# Create an instance of a GET request.
self.request = self.factory.get('/foo/')
# self.request = Mock()
self.request.user = self.user
self.request.user.is_authenticated = lambda: False
self.request.cloud_mode = False
self.request.session = {}
self.request.META = {}
self.request.META['REMOTE_USER'] = self.user.username
self.request.META['eppn'] = 'test eppn'
self.request.META['givenname'] = 'test_gname'
self.request.META['surname'] = 'test_sname'
# def test_can_process(self):
# assert len(Profile.objects.all()) == 0
# self.middleware.process_request(self.request)
# assert len(Profile.objects.all()) == 1
# assert self.request.shib_login is True
def test_make_profile_for_display_name(self):
assert len(Profile.objects.all()) == 0
self.middleware.make_profile(self.user, {
'display_name': 'display name',
'givenname': 'g',
'surname': 's',
'institution': 'i',
'contact_email': '<EMAIL>'
})
assert len(Profile.objects.all()) == 1
assert Profile.objects.all()[0].nickname == 'display name'
def test_make_profile_for_givenname_surname(self):
assert len(Profile.objects.all()) == 0
self.middleware.make_profile(self.user, {
'givenname': 'g',
'surname': 's',
'institution': 'i',
'contact_email': '<EMAIL>'
})
assert len(Profile.objects.all()) == 1
assert Profile.objects.all()[0].nickname == 'g s'
def test_make_profile_for_name_missing(self):
assert len(Profile.objects.all()) == 0
self.middleware.make_profile(self.user, {
'institution': 'i',
'contact_email': '<EMAIL>'
})
assert len(Profile.objects.all()) == 1
assert Profile.objects.all()[0].nickname == ''
<file_sep>/seahub/views/wiki.py
# -*- coding: utf-8 -*-
"""
File related views, including view_file, edit_file, view_history_file,
view_trash_file, view_snapshot_file
"""
import os
import hashlib
import logging
import json
import stat
import tempfile
import urllib
import urllib2
import chardet
from django.contrib.sites.models import Site, RequestSite
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.http import HttpResponse, HttpResponseBadRequest, Http404, \
HttpResponseRedirect
from django.shortcuts import render_to_response, redirect
from django.template import Context, loader, RequestContext
from django.template.loader import render_to_string
from django.utils.http import urlquote
from django.utils.translation import ugettext as _
import seaserv
from seaserv import seafile_api
from pysearpc import SearpcError
from seahub.auth.decorators import login_required
from seahub.base.decorators import user_mods_check
from seahub.wiki.models import PersonalWiki, WikiDoesNotExist, WikiPageMissing
from seahub.wiki import get_personal_wiki_page, get_personal_wiki_repo, \
convert_wiki_link, get_wiki_pages
from seahub.wiki.forms import WikiCreateForm, WikiNewPageForm
from seahub.wiki.utils import clean_page_name, page_name_to_file_name
from seahub.utils import render_error
# Get an instance of a logger
logger = logging.getLogger(__name__)
@login_required
@user_mods_check
def personal_wiki(request, page_name="home"):
username = request.user.username
wiki_exists = True
try:
content, repo, dirent = get_personal_wiki_page(username, page_name)
except WikiDoesNotExist:
wiki_exists = False
owned_repos = seafile_api.get_owned_repo_list(username)
owned_repos = [r for r in owned_repos if not r.encrypted]
return render_to_response("wiki/personal_wiki.html", {
"wiki_exists": wiki_exists,
"owned_repos": owned_repos,
}, context_instance=RequestContext(request))
except WikiPageMissing:
repo = get_personal_wiki_repo(username)
filename = page_name_to_file_name(clean_page_name(page_name))
if not seaserv.post_empty_file(repo.id, "/", filename, username):
return render_error(request, _("Failed to create wiki page. Please retry later."))
return HttpResponseRedirect(reverse('personal_wiki', args=[page_name]))
else:
url_prefix = reverse('personal_wiki', args=[])
# fetch file modified time and modifier
path = '/' + dirent.obj_name
try:
dirent = seafile_api.get_dirent_by_path(repo.id, path)
if dirent:
latest_contributor, last_modified = dirent.modifier, dirent.mtime
else:
latest_contributor, last_modified = None, 0
except SearpcError as e:
logger.error(e)
latest_contributor, last_modified = None, 0
wiki_index_exists = True
index_pagename = 'index'
index_content = None
try:
index_content, index_repo, index_dirent = get_personal_wiki_page(username, index_pagename)
except (WikiDoesNotExist, WikiPageMissing) as e:
wiki_index_exists = False
return render_to_response("wiki/personal_wiki.html", {
"wiki_exists": wiki_exists,
"content": content,
"page": os.path.splitext(dirent.obj_name)[0],
"last_modified": last_modified,
"latest_contributor": latest_contributor or _("Unknown"),
"path": path,
"repo_id": repo.id,
"search_repo_id": repo.id,
"search_wiki": True,
"wiki_index_exists": wiki_index_exists,
"index_content": index_content,
}, context_instance=RequestContext(request))
@login_required
@user_mods_check
def personal_wiki_pages(request):
"""
List personal wiki pages.
"""
try:
username = request.user.username
repo = get_personal_wiki_repo(username)
pages = get_wiki_pages(repo)
except SearpcError:
return render_error(request, _('Internal Server Error'))
except WikiDoesNotExist:
return render_error(request, _('Wiki does not exists.'))
return render_to_response("wiki/personal_wiki_pages.html", {
"pages": pages,
"repo_id": repo.id,
"search_repo_id": repo.id,
"search_wiki": True,
}, context_instance=RequestContext(request))
@login_required
def personal_wiki_create(request):
if request.method != 'POST':
raise Http404
content_type = 'application/json; charset=utf-8'
def json_error(err_msg, status=400):
result = {'error': err_msg}
return HttpResponse(json.dumps(result), status=status,
content_type=content_type)
if not request.user.permissions.can_add_repo():
return json_error(_('You do not have permission to create wiki'), 403)
form = WikiCreateForm(request.POST)
if not form.is_valid():
return json_error(str(form.errors.values()[0]))
# create group repo in user context
repo_name = form.cleaned_data['repo_name']
repo_desc = form.cleaned_data['repo_desc']
username = request.user.username
passwd = <PASSWORD>
permission = "rw"
repo_id = seaserv.create_repo(repo_name, repo_desc, username, passwd)
if not repo_id:
return json_error(_(u'Failed to create'), 500)
PersonalWiki.objects.save_personal_wiki(username=username, repo_id=repo_id)
# create home page
page_name = "home.md"
if not seaserv.post_empty_file(repo_id, "/", page_name, username):
return json_error(_(u'Failed to create home page. Please retry later'), 500)
next = reverse('personal_wiki', args=[])
return HttpResponse(json.dumps({'href': next}), content_type=content_type)
@login_required
def personal_wiki_use_lib(request):
if request.method != 'POST':
raise Http404
repo_id = request.POST.get('dst_repo', '')
username = request.user.username
next = reverse('personal_wiki', args=[])
repo = seafile_api.get_repo(repo_id)
if repo is None:
messages.error(request, _('Failed to set wiki library.'))
return HttpResponseRedirect(next)
PersonalWiki.objects.save_personal_wiki(username=username, repo_id=repo_id)
# create home page if not exist
page_name = "home.md"
if not seaserv.get_file_id_by_path(repo_id, "/" + page_name):
if not seaserv.post_empty_file(repo_id, "/", page_name, username):
messages.error(request, _('Failed to create home page. Please retry later'))
return HttpResponseRedirect(next)
@login_required
def personal_wiki_page_new(request, page_name="home"):
if request.method == 'POST':
page_name = request.POST.get('page_name', '')
if not page_name:
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
page_name = clean_page_name(page_name)
try:
repo = get_personal_wiki_repo(request.user.username)
except WikiDoesNotExist:
return render_error(request, _('Wiki is not found.'))
filename = page_name + ".md"
filepath = "/" + page_name + ".md"
# check whether file exists
if seaserv.get_file_id_by_path(repo.id, filepath):
return render_error(request, _('Page "%s" already exists.') % filename)
if not seaserv.post_empty_file(repo.id, "/", filename, request.user.username):
return render_error(request, _('Failed to create wiki page. Please retry later.'))
url = "%s?p=%s&from=personal_wiki_page_new" % (
reverse('file_edit', args=[repo.id]),
urlquote(filepath.encode('utf-8')))
return HttpResponseRedirect(url)
@login_required
def personal_wiki_page_edit(request, page_name="home"):
try:
repo = get_personal_wiki_repo(request.user.username)
except WikiDoesNotExist:
return render_error(request, _('Wiki is not found.'))
filepath = "/" + page_name + ".md"
url = "%s?p=%s&from=personal_wiki_page_edit" % (
reverse('file_edit', args=[repo.id]),
urllib2.quote(filepath.encode('utf-8')))
return HttpResponseRedirect(url)
@login_required
def personal_wiki_page_delete(request, page_name):
try:
repo = get_personal_wiki_repo(request.user.username)
except WikiDoesNotExist:
return render_error(request, _('Wiki is not found.'))
file_name = page_name + '.md'
username = request.user.username
if seaserv.del_file(repo.id, '/', file_name, username):
messages.success(request, 'Successfully deleted "%s".' % page_name)
else:
messages.error(request, 'Failed to delete "%s". Please retry later.' % page_name)
return HttpResponseRedirect(reverse('personal_wiki', args=[]))
<file_sep>/seahub/api2/views.py
# encoding: utf-8
import logging
import os
import stat
import json
import datetime
import posixpath
import re
from dateutil.relativedelta import relativedelta
from urllib2 import unquote, quote
from rest_framework import parsers
from rest_framework import status
from rest_framework import renderers
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.reverse import reverse
from rest_framework.response import Response
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
from rest_framework.views import APIView
from django.contrib.auth.hashers import check_password
from django.contrib.sites.models import RequestSite
from django.db import IntegrityError
from django.db.models import F, Q
from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.template.loader import render_to_string
from django.template.defaultfilters import filesizeformat
from django.shortcuts import render_to_response
from django.utils import timezone
from .throttling import ScopedRateThrottle
from .authentication import TokenAuthentication
from .serializers import AuthTokenSerializer, AccountSerializer
from .utils import is_repo_writable, is_repo_accessible, \
api_error, get_file_size, prepare_starred_files, \
get_groups, get_group_and_contacts, prepare_events, \
get_person_msgs, api_group_check, get_email, get_timestamp, \
get_group_message_json, get_group_msgs, get_group_msgs_json, get_diff_details, \
json_response, to_python_boolean, is_seafile_pro
from seahub.avatar.templatetags.avatar_tags import api_avatar_url, avatar
from seahub.avatar.templatetags.group_avatar_tags import api_grp_avatar_url, \
grp_avatar
from seahub.base.accounts import User
from seahub.base.models import FileDiscuss, UserStarredFiles, DeviceToken
from seahub.base.templatetags.seahub_tags import email2nickname, \
translate_commit_desc, translate_seahub_time, translate_commit_desc_escape
from seahub.group.models import GroupMessage, MessageReply, MessageAttachment
from seahub.group.signals import grpmsg_added, grpmsg_reply_added
from seahub.group.views import group_check, remove_group_common, \
rename_group_with_new_name
from seahub.group.utils import BadGroupNameError, ConflictGroupNameError, \
validate_group_name
from seahub.thumbnail.utils import generate_thumbnail
from seahub.message.models import UserMessage
from seahub.notifications.models import UserNotification
from seahub.options.models import UserOptions
from seahub.contacts.models import Contact
from seahub.profile.models import Profile, DetailedProfile
from seahub.shortcuts import get_first_object_or_none
from seahub.signals import (repo_created, repo_deleted,
share_file_to_user_successful)
from seahub.share.models import PrivateFileDirShare, FileShare, OrgFileShare, \
UploadLinkShare
from seahub.share.signals import share_repo_to_user_successful
from seahub.share.views import list_shared_repos
from seahub.utils import gen_file_get_url, gen_token, gen_file_upload_url, \
check_filename_with_rename, is_valid_username, EVENTS_ENABLED, \
get_user_events, EMPTY_SHA1, get_ccnet_server_addr_port, is_pro_version, \
gen_block_get_url, get_file_type_and_ext, HAS_FILE_SEARCH, \
gen_file_share_link, gen_dir_share_link, is_org_context, gen_shared_link, \
get_org_user_events, calculate_repos_last_modify, send_perm_audit_msg, \
gen_shared_upload_link, convert_cmmt_desc_link, is_org_repo_creation_allowed
from seahub.utils.repo import get_sub_repo_abbrev_origin_path
from seahub.utils.star import star_file, unstar_file
from seahub.utils.file_types import IMAGE, DOCUMENT
from seahub.utils.file_size import get_file_size_unit
from seahub.utils.timeutils import utc_to_local
from seahub.views import validate_owner, is_registered_user, check_file_lock, \
group_events_data, get_diff, create_default_library, get_owned_repo_list, \
list_inner_pub_repos, get_virtual_repos_by_owner, \
check_folder_permission, check_file_permission
from seahub.views.ajax import get_share_in_repo_list, get_groups_by_user, \
get_group_repos
from seahub.views.file import get_file_view_path_and_perm, send_file_access_msg
if HAS_FILE_SEARCH:
from seahub_extra.search.views import search_keyword
from seahub.utils import HAS_OFFICE_CONVERTER
if HAS_OFFICE_CONVERTER:
from seahub.utils import query_office_convert_status, prepare_converted_html
import seahub.settings as settings
from seahub.settings import THUMBNAIL_EXTENSION, THUMBNAIL_ROOT, \
ENABLE_GLOBAL_ADDRESSBOOK, FILE_LOCK_EXPIRATION_DAYS, ENABLE_THUMBNAIL
try:
from seahub.settings import CLOUD_MODE
except ImportError:
CLOUD_MODE = False
try:
from seahub.settings import MULTI_TENANCY
except ImportError:
MULTI_TENANCY = False
try:
from seahub.settings import ORG_MEMBER_QUOTA_DEFAULT
except ImportError:
ORG_MEMBER_QUOTA_DEFAULT = None
from pysearpc import SearpcError, SearpcObjEncoder
import seaserv
from seaserv import seafserv_rpc, seafserv_threaded_rpc, \
get_personal_groups_by_user, get_session_info, is_personal_repo, \
get_repo, check_permission, get_commits, is_passwd_set,\
list_personal_repos_by_owner, check_quota, \
list_share_repos, get_group_repos_by_owner, get_group_repoids, \
list_inner_pub_repos_by_owner, is_group_user, \
remove_share, unshare_group_repo, unset_inner_pub_repo, get_group, \
get_commit, get_file_id_by_path, MAX_DOWNLOAD_DIR_SIZE, edit_repo, \
ccnet_threaded_rpc, get_personal_groups, seafile_api, check_group_staff, \
create_org
from constance import config
logger = logging.getLogger(__name__)
json_content_type = 'application/json; charset=utf-8'
# Define custom HTTP status code. 4xx starts from 440, 5xx starts from 520.
HTTP_440_REPO_PASSWD_REQUIRED = 440
HTTP_441_REPO_PASSWD_MAGIC_REQUIRED = 441
HTTP_520_OPERATION_FAILED = 520
def UTF8Encode(s):
if isinstance(s, unicode):
return s.encode('utf-8')
else:
return s
def check_filename_with_rename_utf8(repo_id, parent_dir, filename):
newname = check_filename_with_rename(repo_id, parent_dir, filename)
return UTF8Encode(newname)
########## Test
class Ping(APIView):
"""
Returns a simple `pong` message when client calls `api2/ping/`.
For example:
curl http://127.0.0.1:8000/api2/ping/
"""
throttle_classes = (ScopedRateThrottle, )
throttle_scope = 'ping'
def get(self, request, format=None):
return Response('pong')
def head(self, request, format=None):
return Response(headers={'foo': 'bar',})
class AuthPing(APIView):
"""
Returns a simple `pong` message when client provided an auth token.
For example:
curl -H "Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b" http://127.0.0.1:8000/api2/auth/ping/
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
return Response('pong')
########## Token
class ObtainAuthToken(APIView):
"""
Returns auth token if username and password are valid.
For example:
curl -d "username=<EMAIL>&password=<PASSWORD>" http://127.0.0.1:8000/api2/auth-token/
"""
throttle_classes = (AnonRateThrottle, )
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
def post(self, request):
context = { 'request': request }
serializer = AuthTokenSerializer(data=request.DATA, context=context)
if serializer.is_valid():
key = serializer.object
return Response({'token': key})
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
########## Accounts
class Accounts(APIView):
"""List all accounts.
Administrator permission is required.
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAdminUser, )
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
# list accounts
start = int(request.GET.get('start', '0'))
limit = int(request.GET.get('limit', '100'))
# reading scope user list
scope = request.GET.get('scope', None)
accounts_ldap = []
accounts_db = []
if scope:
scope = scope.upper()
if scope == 'LDAP':
accounts_ldap = seaserv.get_emailusers('LDAP', start, limit)
elif scope == 'DB':
accounts_db = seaserv.get_emailusers('DB', start, limit)
else:
return api_error(status.HTTP_400_BAD_REQUEST, "%s is not a valid scope value" % scope)
else:
# old way - search first in LDAP if available then DB if no one found
accounts_ldap = seaserv.get_emailusers('LDAP', start, limit)
if len(accounts_ldap) == 0:
accounts_db = seaserv.get_emailusers('DB', start, limit)
accounts_json = []
for account in accounts_ldap:
accounts_json.append({'email': account.email, 'source' : 'LDAP'})
for account in accounts_db:
accounts_json.append({'email': account.email, 'source' : 'DB'})
return Response(accounts_json)
class AccountInfo(APIView):
""" Show account info.
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
info = {}
email = request.user.username
p = Profile.objects.get_profile_by_user(email)
d_p = DetailedProfile.objects.get_detailed_profile_by_user(email)
info['email'] = email
info['name'] = email2nickname(email)
info['total'] = seafile_api.get_user_quota(email)
info['usage'] = seafile_api.get_user_self_usage(email)
info['login_id'] = p.login_id if p else ""
info['department'] = d_p.department if d_p else ""
info['contact_email'] = p.contact_email if p else ""
info['institution'] = p.institution if p else ""
return Response(info)
class RegDevice(APIView):
"""Reg device for iOS push notification.
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def post(self, request, format=None):
version = request.POST.get('version')
platform = request.POST.get('platform')
pversion = request.POST.get('pversion')
devicetoken = request.POST.get('deviceToken')
if not devicetoken or not version or not platform or not pversion:
return api_error(status.HTTP_400_BAD_REQUEST, "Missing argument")
token, modified = DeviceToken.objects.get_or_create(
token=devicetoken, user=request.user.username)
if token.version != version:
token.version = version
modified = True
if token.pversion != pversion:
token.pversion = pversion
modified = True
if token.platform != platform:
token.platform = platform
modified = True
if modified:
token.save()
return Response("success")
class SearchUser(APIView):
""" Search user from contacts/all users
"""
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
if not request.user.permissions.can_use_global_address_book():
return api_error(status.HTTP_403_FORBIDDEN,
'Guest user can not use global address book.')
q = request.GET.get('q', None)
if not q:
return api_error(status.HTTP_400_BAD_REQUEST, 'Argument missing.')
username = request.user.username
search_result = []
searched_users = []
searched_profiles = []
if request.cloud_mode:
if is_org_context(request):
url_prefix = request.user.org.url_prefix
users = seaserv.get_org_users_by_url_prefix(url_prefix, -1, -1)
searched_users = filter(lambda u: q in u.email, users)
# 'user__in' for only get profile of user in org
# 'nickname__icontains' for search by nickname
searched_profiles = Profile.objects.filter(Q(user__in=[u.email for u in users]) & \
Q(nickname__icontains=q)).values('user')
elif ENABLE_GLOBAL_ADDRESSBOOK:
searched_users = get_searched_users(q)
searched_profiles = Profile.objects.filter(nickname__icontains=q).values('user')
else:
users = []
contacts = Contact.objects.get_contacts_by_user(username)
for c in contacts:
try:
user = User.objects.get(email = c.contact_email)
c.is_active = user.is_active
except User.DoesNotExist:
continue
c.email = c.contact_email
users.append(c)
searched_users = filter(lambda u: q in u.email, users)
# 'user__in' for only get profile of contacts
# 'nickname__icontains' for search by nickname
searched_profiles = Profile.objects.filter(Q(user__in=[u.email for u in users]) & \
Q(nickname__icontains=q)).values('user')
else:
searched_users = get_searched_users(q)
searched_profiles = Profile.objects.filter(nickname__icontains=q).values('user')
# remove inactive users and add to result
for u in searched_users[:10]:
if u.is_active:
search_result.append(u.email)
for p in searched_profiles[:10]:
try:
user = User.objects.get(email = p['user'])
except User.DoesNotExist:
continue
if not user.is_active:
continue
search_result.append(p['user'])
# remove duplicate emails
search_result = {}.fromkeys(search_result).keys()
# reomve myself
if username in search_result:
search_result.remove(username)
if is_valid_username(q) and q not in search_result:
search_result.insert(0, q)
try:
size = int(request.GET.get('avatar_size', 32))
except ValueError:
size = 32
# Remove users that aren't in the same domain as the user performing the search
user_domain = '@' + request.user.username.split('@')[1]
search_result = [result for result in search_result if result.endswith(user_domain)]
formated_result = format_user_result(request, search_result, size)[:10]
return HttpResponse(json.dumps({"users": formated_result}), status=200,
content_type=json_content_type)
def format_user_result(request, users, size):
results = []
# Get contact_emails from users' profiles
profiles = Profile.objects.filter(user__in=users)
contact_email_dict = {}
for e in profiles:
contact_email_dict[e.user] = e.contact_email
for email in users:
url, is_default, date_uploaded = api_avatar_url(email, size)
results.append({
"email": email,
"avatar": avatar(email, size),
"avatar_url": request.build_absolute_uri(url),
"name": email2nickname(email),
"contact_email": contact_email_dict.get(email, ""),
})
return results
def get_searched_users(q):
searched_users = []
searched_db_users = []
searched_ldap_users = []
searched_db_users = seaserv.ccnet_threaded_rpc.search_emailusers('DB', q, 0, 10)
count = len(searched_db_users)
if count < 10:
searched_ldap_users = seaserv.ccnet_threaded_rpc.search_emailusers('LDAP', q, 0, 10 - count)
searched_users.extend(searched_db_users)
searched_users.extend(searched_ldap_users)
return searched_users
class Search(APIView):
""" Search all the repos
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
if not HAS_FILE_SEARCH:
return api_error(status.HTTP_404_NOT_FOUND, "Search not supported")
keyword = request.GET.get('q', None)
if not keyword:
return api_error(status.HTTP_400_BAD_REQUEST, "Missing argument")
results, total, has_more = search_keyword(request, keyword)
for e in results:
e.pop('repo', None)
e.pop('content_highlight', None)
e.pop('exists', None)
e.pop('last_modified_by', None)
e.pop('name_highlight', None)
e.pop('score', None)
try:
path = e['fullpath'].encode('utf-8')
file_id = seafile_api.get_file_id_by_path(e['repo_id'], path)
e['oid'] = file_id
repo = get_repo(e['repo_id'])
e['size'] = get_file_size(repo.store_id, repo.version, file_id)
except SearpcError, err:
pass
res = { "total":total, "results":results, "has_more":has_more }
return Response(res)
########## Repo related
def repo_download_info(request, repo_id, gen_sync_token=True):
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
# generate download url for client
relay_id = get_session_info().id
addr, port = get_ccnet_server_addr_port()
email = request.user.username
if gen_sync_token:
token = seafile_api.generate_repo_token(repo_id, email)
else:
token = ''
repo_name = repo.name
repo_desc = repo.desc
repo_size = repo.size
repo_size_formatted = filesizeformat(repo.size)
enc = 1 if repo.encrypted else ''
magic = repo.magic if repo.encrypted else ''
random_key = repo.random_key if repo.random_key else ''
enc_version = repo.enc_version
repo_version = repo.version
calculate_repos_last_modify([repo])
info_json = {
'relay_id': relay_id,
'relay_addr': addr,
'relay_port': port,
'email': email,
'token': token,
'repo_id': repo_id,
'repo_name': repo_name,
'repo_desc': repo_desc,
'repo_size': repo_size,
'repo_size_formatted': repo_size_formatted,
'mtime': repo.latest_modify,
'mtime_relative': translate_seahub_time(repo.latest_modify),
'encrypted': enc,
'enc_version': enc_version,
'magic': magic,
'random_key': random_key,
'repo_version': repo_version,
}
return Response(info_json)
class Repos(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
# parse request params
filter_by = {
'mine': False,
'sub': False,
'shared': False,
'group': False,
'org': False,
}
rtype = request.GET.get('type', "")
if not rtype:
# set all to True, no filter applied
filter_by = filter_by.fromkeys(filter_by.iterkeys(), True)
for f in rtype.split(','):
f = f.strip()
filter_by[f] = True
email = request.user.username
if not UserOptions.objects.is_sub_lib_enabled(email):
filter_by['sub'] = False
repos_json = []
if filter_by['mine']:
if is_org_context(request):
org_id = request.user.org.org_id
owned_repos = seafile_api.get_org_owned_repo_list(org_id,
email, ret_corrupted=True)
else:
owned_repos = seafile_api.get_owned_repo_list(email,
ret_corrupted=True)
owned_repos.sort(lambda x, y: cmp(y.last_modify, x.last_modify))
for r in owned_repos:
# do not return virtual repos
if r.is_virtual:
continue
repo = {
"type": "repo",
"id": r.id,
"owner": email,
"name": r.name,
"desc": r.desc,
"mtime": r.last_modify,
"mtime_relative": translate_seahub_time(r.last_modify),
"size": r.size,
"size_formatted": filesizeformat(r.size),
"encrypted": r.encrypted,
"permission": 'rw', # Always have read-write permission to owned repo
"virtual": r.is_virtual,
"root": r.root,
}
if r.encrypted:
repo["enc_version"] = r.enc_version
repo["magic"] = r.magic
repo["random_key"] = r.random_key
repos_json.append(repo)
if filter_by['sub']:
# compose abbrev origin path for display
sub_repos = []
sub_repos = get_virtual_repos_by_owner(request)
for repo in sub_repos:
repo.abbrev_origin_path = get_sub_repo_abbrev_origin_path(
repo.origin_repo_name, repo.origin_path)
sub_repos.sort(lambda x, y: cmp(y.last_modify, x.last_modify))
for r in sub_repos:
# print r._dict
repo = {
"type": "repo",
"id": r.id,
"name": r.name,
"origin_repo_id": r.origin_repo_id,
"origin_path": r.origin_path,
"abbrev_origin_path": r.abbrev_origin_path,
"mtime": r.last_modify,
"mtime_relative": translate_seahub_time(r.last_modify),
"owner": email,
"desc": r.desc,
"size": r.size,
"encrypted": r.encrypted,
"permission": 'rw',
"virtual": r.is_virtual,
"root": r.root,
}
if r.encrypted:
repo["enc_version"] = r.enc_version
repo["magic"] = r.magic
repo["random_key"] = r.random_key
repos_json.append(repo)
if filter_by['shared']:
shared_repos = get_share_in_repo_list(request, -1, -1)
shared_repos.sort(lambda x, y: cmp(y.last_modify, x.last_modify))
for r in shared_repos:
r.password_need = is_passwd_set(r.repo_id, email)
repo = {
"type": "srepo",
"id": r.repo_id,
"owner": r.user,
"name": r.repo_name,
"owner_nickname": email2nickname(r.user),
"desc": r.repo_desc,
"mtime": r.last_modify,
"mtime_relative": translate_seahub_time(r.last_modify),
"size": r.size,
"size_formatted": filesizeformat(r.size),
"encrypted": r.encrypted,
"permission": r.user_perm,
"share_type": r.share_type,
"root": r.root,
}
if r.encrypted:
repo["enc_version"] = r.enc_version
repo["magic"] = r.magic
repo["random_key"] = r.random_key
repos_json.append(repo)
if filter_by['group']:
groups = get_groups_by_user(request)
group_repos = get_group_repos(request, groups)
group_repos.sort(lambda x, y: cmp(y.last_modify, x.last_modify))
for r in group_repos:
repo = {
"type": "grepo",
"id": r.id,
"owner": r.group.group_name,
"groupid": r.group.id,
"name": r.name,
"desc": r.desc,
"mtime": r.last_modify,
"size": r.size,
"encrypted": r.encrypted,
"permission": check_permission(r.id, email),
"root": r.root,
}
if r.encrypted:
repo["enc_version"] = r.enc_version
repo["magic"] = r.magic
repo["random_key"] = r.random_key
repos_json.append(repo)
if filter_by['org'] and request.user.permissions.can_view_org():
public_repos = list_inner_pub_repos(request)
for r in public_repos:
repo = {
"type": "grepo",
"id": r.repo_id,
"name": r.repo_name,
"desc": r.repo_desc,
"owner": "Organization",
"mtime": r.last_modified,
"mtime_relative": translate_seahub_time(r.last_modified),
"size": r.size,
"size_formatted": filesizeformat(r.size),
"encrypted": r.encrypted,
"permission": r.permission,
"share_from": r.user,
"share_type": r.share_type,
"root": r.root,
}
if r.encrypted:
repo["enc_version"] = r.enc_version
repo["magic"] = r.magic
repo["random_key"] = r.random_key
repos_json.append(repo)
response = HttpResponse(json.dumps(repos_json), status=200,
content_type=json_content_type)
response["enable_encrypted_library"] = config.ENABLE_ENCRYPTED_LIBRARY
return response
def post(self, request, format=None):
if not request.user.permissions.can_add_repo():
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to create library.')
req_from = request.GET.get('from', "")
if req_from == 'web':
gen_sync_token = False # Do not generate repo sync token
else:
gen_sync_token = True
username = request.user.username
repo_name = request.DATA.get("name", None)
if not repo_name:
return api_error(status.HTTP_400_BAD_REQUEST,
'Library name is required.')
repo_desc = request.DATA.get("desc", '')
org_id = -1
if is_org_context(request):
org_id = request.user.org.org_id
repo_id = request.DATA.get('repo_id', '')
try:
if repo_id:
# client generates magic and random key
repo_id, error = self._create_enc_repo(request, repo_id, repo_name, repo_desc, username, org_id)
else:
repo_id, error = self._create_repo(request, repo_name, repo_desc, username, org_id)
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
'Failed to create library.')
if error is not None:
return error
if not repo_id:
return api_error(HTTP_520_OPERATION_FAILED,
'Failed to create library.')
else:
repo_created.send(sender=None,
org_id=org_id,
creator=username,
repo_id=repo_id,
repo_name=repo_name)
resp = repo_download_info(request, repo_id,
gen_sync_token=gen_sync_token)
# FIXME: according to the HTTP spec, need to return 201 code and
# with a corresponding location header
# resp['Location'] = reverse('api2-repo', args=[repo_id])
return resp
def _create_repo(self, request, repo_name, repo_desc, username, org_id):
passwd = request.DATA.get("passwd", None)
# to avoid 'Bad magic' error when create repo, passwd should be 'None'
# not an empty string when create unencrypted repo
if not passwd:
passwd = None
if (passwd is not None) and (not config.ENABLE_ENCRYPTED_LIBRARY):
return api_error(status.HTTP_403_FORBIDDEN,
'NOT allow to create encrypted library.')
if org_id > 0:
repo_id = seafile_api.create_org_repo(repo_name, repo_desc,
username, passwd, org_id)
else:
repo_id = seafile_api.create_repo(repo_name, repo_desc,
username, passwd)
return repo_id, None
def _create_enc_repo(self, request, repo_id, repo_name, repo_desc, username, org_id):
if not _REPO_ID_PATTERN.match(repo_id):
return api_error(status.HTTP_400_BAD_REQUEST, 'Repo id must be a valid uuid')
magic = request.DATA.get('magic', '')
random_key = request.DATA.get('random_key', '')
try:
enc_version = int(request.DATA.get('enc_version', 0))
except ValueError:
return None, api_error(status.HTTP_400_BAD_REQUEST,
'Invalid enc_version param.')
if len(magic) != 64 or len(random_key) != 96 or enc_version < 0:
return None, api_error(status.HTTP_400_BAD_REQUEST,
'You must provide magic, random_key and enc_version.')
if org_id > 0:
repo_id = seafile_api.create_org_enc_repo(repo_id, repo_name, repo_desc,
username, magic, random_key, enc_version, org_id)
else:
repo_id = seafile_api.create_enc_repo(
repo_id, repo_name, repo_desc, username,
magic, random_key, enc_version)
return repo_id, None
class PubRepos(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
# List public repos
if not request.user.permissions.can_view_org():
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to view public libraries.')
repos_json = []
public_repos = list_inner_pub_repos(request)
for r in public_repos:
repo = {
"id": r.repo_id,
"name": r.repo_name,
"desc": r.repo_desc,
"owner": r.user,
"owner_nickname": email2nickname(r.user),
"mtime": r.last_modified,
"mtime_relative": translate_seahub_time(r.last_modified),
"size": r.size,
"size_formatted": filesizeformat(r.size),
"encrypted": r.encrypted,
"permission": r.permission,
"root": r.root,
}
if r.encrypted:
repo["enc_version"] = r.enc_version
repo["magic"] = r.magic
repo["random_key"] = r.random_key
repos_json.append(repo)
return Response(repos_json)
def post(self, request, format=None):
# Create public repo
if not request.user.permissions.can_add_repo():
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to create library.')
username = request.user.username
repo_name = request.DATA.get("name", None)
if not repo_name:
return api_error(status.HTTP_400_BAD_REQUEST,
'Library name is required.')
repo_desc = request.DATA.get("desc", '')
passwd = request.DATA.get("passwd", None)
# to avoid 'Bad magic' error when create repo, passwd should be 'None'
# not an empty string when create unencrypted repo
if not passwd:
passwd = None
if (passwd is not None) and (not config.ENABLE_ENCRYPTED_LIBRARY):
return api_error(status.HTTP_403_FORBIDDEN,
'NOT allow to create encrypted library.')
permission = request.DATA.get("permission", 'r')
if permission != 'r' and permission != 'rw':
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid permission')
if is_org_context(request):
org_id = request.user.org.org_id
repo_id = seafile_api.create_org_repo(repo_name, repo_desc,
username, passwd, org_id)
repo = seafile_api.get_repo(repo_id)
seaserv.seafserv_threaded_rpc.set_org_inner_pub_repo(
org_id, repo.id, permission)
else:
repo_id = seafile_api.create_repo(repo_name, repo_desc,
username, passwd)
repo = seafile_api.get_repo(repo_id)
seafile_api.add_inner_pub_repo(repo.id, permission)
pub_repo = {
"id": repo.id,
"name": repo.name,
"desc": repo.desc,
"size": repo.size,
"size_formatted": filesizeformat(repo.size),
"mtime": repo.last_modify,
"mtime_relative": translate_seahub_time(repo.last_modify),
"encrypted": repo.encrypted,
"permission": 'rw', # Always have read-write permission to owned repo
"owner": username,
"owner_nickname": email2nickname(username),
}
return Response(pub_repo, status=201)
def set_repo_password(request, repo, password):
assert password, '<PASSWORD>'
try:
seafile_api.set_passwd(repo.id, request.user.username, password)
except SearpcError, e:
if e.msg == 'Bad arguments':
return api_error(status.HTTP_400_BAD_REQUEST, e.msg)
elif e.msg == 'Repo is not encrypted':
return api_error(status.HTTP_409_CONFLICT, e.msg)
elif e.msg == 'Incorrect password':
return api_error(status.HTTP_400_BAD_REQUEST, e.msg)
elif e.msg == 'Internal server error':
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, e.msg)
else:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, e.msg)
def check_set_repo_password(request, repo):
if not check_permission(repo.id, request.user.username):
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this library.')
if repo.encrypted:
password = request.REQUEST.get('password', default=None)
if not password:
return api_error(HTTP_440_REPO_PASSWD_REQUIRED,
'Library password is needed.')
return set_repo_password(request, repo, password)
def check_repo_access_permission(request, repo):
if not seafile_api.check_repo_access_permission(repo.id,
request.user.username):
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this library.')
class Repo(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
username = request.user.username
if not is_repo_accessible(repo.id, username):
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this library.')
# check whether user is repo owner
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
owner = "self" if username == repo_owner else "share"
last_commit = get_commits(repo.id, 0, 1)[0]
repo.latest_modify = last_commit.ctime if last_commit else None
# query repo infomation
repo.size = seafile_api.get_repo_size(repo_id)
current_commit = get_commits(repo_id, 0, 1)[0]
root_id = current_commit.root_id if current_commit else None
repo_json = {
"type":"repo",
"id":repo.id,
"owner":owner,
"name":repo.name,
"desc":repo.desc,
"mtime":repo.latest_modify,
"size":repo.size,
"encrypted":repo.encrypted,
"root":root_id,
"permission": check_permission(repo.id, username),
}
if repo.encrypted:
repo_json["enc_version"] = repo.enc_version
repo_json["magic"] = repo.magic
repo_json["random_key"] = repo.random_key
return Response(repo_json)
def post(self, request, repo_id, format=None):
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
op = request.GET.get('op', 'setpassword')
if op == 'checkpassword':
magic = request.REQUEST.get('magic', default=None)
if not magic:
return api_error(HTTP_441_REPO_PASSWD_MAGIC_REQUIRED,
'Library password magic is needed.')
resp = check_repo_access_permission(request, repo)
if resp:
return resp
try:
seafile_api.check_passwd(repo.id, magic)
except SearpcError, e:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
"SearpcError:" + e.msg)
return Response("success")
elif op == 'setpassword':
resp = check_set_repo_password(request, repo)
if resp:
return resp
return Response("success")
elif op == 'rename':
username = request.user.username
repo_name = request.POST.get('repo_name')
repo_desc = request.POST.get('repo_desc')
# check permission
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
is_owner = True if username == repo_owner else False
if not is_owner:
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to rename this library.')
if edit_repo(repo_id, repo_name, repo_desc, username):
return Response("success")
else:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
"Unable to rename library")
return Response("unsupported operation")
def delete(self, request, repo_id, format=None):
username = request.user.username
repo = seafile_api.get_repo(repo_id)
if not repo:
return api_error(status.HTTP_400_BAD_REQUEST,
'Library does not exist.')
# check permission
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
is_owner = True if username == repo_owner else False
if not is_owner:
return api_error(
status.HTTP_403_FORBIDDEN,
'You do not have permission to delete this library.'
)
usernames = seaserv.get_related_users_by_repo(repo_id)
seafile_api.remove_repo(repo_id)
repo_deleted.send(sender=None,
org_id=-1,
usernames=usernames,
repo_owner=repo_owner,
repo_id=repo_id,
repo_name=repo.name)
return Response('success', status=status.HTTP_200_OK)
class RepoHistory(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
try:
current_page = int(request.GET.get('page', '1'))
per_page = int(request.GET.get('per_page', '25'))
except ValueError:
current_page = 1
per_page = 25
commits_all = get_commits(repo_id, per_page * (current_page - 1),
per_page + 1)
commits = commits_all[:per_page]
if len(commits_all) == per_page + 1:
page_next = True
else:
page_next = False
return HttpResponse(json.dumps({"commits": commits,
"page_next": page_next},
cls=SearpcObjEncoder),
status=200, content_type=json_content_type)
class DownloadRepo(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
username = request.user.username
if not is_repo_accessible(repo_id, username):
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this library.')
return repo_download_info(request, repo_id)
class RepoPublic(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def post(self, request, repo_id, format=None):
"""Set organization library.
"""
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library %s not found.' % repo_id)
if not is_org_repo_creation_allowed(request):
return api_error(status.HTTP_403_FORBIDDEN,
'Permission denied.')
if check_permission(repo_id, request.user.username) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this library.')
try:
seafile_api.add_inner_pub_repo(repo_id, "r")
except:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
'Unable to make library public')
return HttpResponse(json.dumps({'success': True}), status=200,
content_type=json_content_type)
def delete(self, request, repo_id, format=None):
"""Unset organization library.
"""
username = request.user.username
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
if not request.user.is_staff and \
not seafile_api.is_repo_owner(username, repo_id):
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to unshare library.')
try:
seafile_api.remove_inner_pub_repo(repo_id)
except:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
'Unable to make library private')
return HttpResponse(json.dumps({'success': True}), status=200,
content_type=json_content_type)
class RepoOwner(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAdminUser, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
else:
repo_owner = seafile_api.get_repo_owner(repo.id)
return HttpResponse(json.dumps({"owner": repo_owner}), status=200,
content_type=json_content_type)
########## File related
class FileBlockDownloadLinkView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, file_id, block_id, format=None):
parent_dir = request.GET.get('p', '/')
if check_folder_permission(request, repo_id, parent_dir) is None:
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this repo.')
if check_quota(repo_id) < 0:
return api_error(HTTP_520_OPERATION_FAILED, 'Above quota')
token = seafile_api.get_fileserver_access_token(
repo_id, file_id, 'downloadblks', request.user.username)
url = gen_block_get_url(token, block_id)
return Response(url)
class UploadLinkView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
parent_dir = request.GET.get('p', '/')
if check_folder_permission(request, repo_id, parent_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this folder.')
if check_quota(repo_id) < 0:
return api_error(HTTP_520_OPERATION_FAILED, 'Above quota')
token = seafile_api.get_fileserver_access_token(
repo_id, 'dummy', 'upload', request.user.username, use_onetime = False)
url = gen_file_upload_url(token, 'upload-api')
return Response(url)
class UpdateLinkView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
parent_dir = request.GET.get('p', '/')
if check_folder_permission(request, repo_id, parent_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this folder.')
if check_quota(repo_id) < 0:
return api_error(HTTP_520_OPERATION_FAILED, 'Above quota')
token = seafile_api.get_fileserver_access_token(
repo_id, 'dummy', 'update', request.user.username)
url = gen_file_upload_url(token, 'update-api')
return Response(url)
class UploadBlksLinkView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
parent_dir = request.GET.get('p', '/')
if check_folder_permission(request, repo_id, parent_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this folder.')
if check_quota(repo_id) < 0:
return api_error(HTTP_520_OPERATION_FAILED, 'Above quota')
token = seafile_api.get_fileserver_access_token(
repo_id, 'dummy', 'upload-blks-api', request.user.username,
use_onetime = False)
url = gen_file_upload_url(token, 'upload-blks-api')
return Response(url)
class UpdateBlksLinkView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
parent_dir = request.GET.get('p', '/')
if check_folder_permission(request, repo_id, parent_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this folder.')
if check_quota(repo_id) < 0:
return api_error(HTTP_520_OPERATION_FAILED, 'Above quota')
token = seafile_api.get_fileserver_access_token(
repo_id, 'dummy', 'update-blks-api', request.user.username,
use_onetime = False)
url = gen_file_upload_url(token, 'update-blks-api')
return Response(url)
def get_dir_recursively(username, repo_id, path, all_dirs):
path_id = seafile_api.get_dir_id_by_path(repo_id, path)
dirs = seafserv_threaded_rpc.list_dir_with_perm(repo_id, path,
path_id, username, -1, -1)
for dirent in dirs:
if stat.S_ISDIR(dirent.mode):
entry = {}
entry["type"] = 'dir'
entry["parent_dir"] = path
entry["id"] = dirent.obj_id
entry["name"] = dirent.obj_name
entry["mtime"] = dirent.mtime
entry["permission"] = dirent.permission
all_dirs.append(entry)
sub_path = posixpath.join(path, dirent.obj_name)
get_dir_recursively(username, repo_id, sub_path, all_dirs)
return all_dirs
def get_dir_entrys_by_id(request, repo, path, dir_id, request_type=None):
""" Get dirents in a dir
if request_type is 'f', only return file list,
if request_type is 'd', only return dir list,
else, return both.
"""
username = request.user.username
try:
dirs = seafserv_threaded_rpc.list_dir_with_perm(repo.id, path, dir_id,
username, -1, -1)
dirs = dirs if dirs else []
except SearpcError, e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to list dir.")
dir_list, file_list = [], []
for dirent in dirs:
dtype = "file"
entry = {}
if stat.S_ISDIR(dirent.mode):
dtype = "dir"
else:
if repo.version == 0:
entry["size"] = get_file_size(repo.store_id, repo.version,
dirent.obj_id)
else:
entry["size"] = dirent.size
if is_pro_version():
entry["is_locked"] = dirent.is_locked
entry["lock_owner"] = dirent.lock_owner
entry["lock_time"] = dirent.lock_time
if username == dirent.lock_owner:
entry["locked_by_me"] = True
else:
entry["locked_by_me"] = False
entry["type"] = dtype
entry["name"] = dirent.obj_name
entry["id"] = dirent.obj_id
entry["mtime"] = dirent.mtime
entry["permission"] = dirent.permission
if dtype == 'dir':
dir_list.append(entry)
else:
file_list.append(entry)
dir_list.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))
file_list.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))
if request_type == 'f':
dentrys = file_list
elif request_type == 'd':
dentrys = dir_list
else:
dentrys = dir_list + file_list
response = HttpResponse(json.dumps(dentrys), status=200,
content_type=json_content_type)
response["oid"] = dir_id
response["dir_perm"] = seafile_api.check_permission_by_path(repo.id, path, username)
return response
def get_shared_link(request, repo_id, path):
l = FileShare.objects.filter(repo_id=repo_id).filter(
username=request.user.username).filter(path=path)
token = None
if len(l) > 0:
fileshare = l[0]
token = fileshare.token
else:
token = gen_token(max_length=10)
fs = FileShare()
fs.username = request.user.username
fs.repo_id = repo_id
fs.path = path
fs.token = token
try:
fs.save()
except IntegrityError, e:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, e.msg)
http_or_https = request.is_secure() and 'https' or 'http'
domain = RequestSite(request).domain
file_shared_link = '%s://%s%sf/%s/' % (http_or_https, domain,
settings.SITE_ROOT, token)
return Response(file_shared_link)
def get_repo_file(request, repo_id, file_id, file_name, op, use_onetime=True):
if op == 'download':
token = seafile_api.get_fileserver_access_token(repo_id, file_id, op,
request.user.username,
use_onetime)
redirect_url = gen_file_get_url(token, file_name)
response = HttpResponse(json.dumps(redirect_url), status=200,
content_type=json_content_type)
response["oid"] = file_id
return response
if op == 'downloadblks':
blklist = []
encrypted = False
enc_version = 0
if file_id != EMPTY_SHA1:
try:
blks = seafile_api.list_file_by_file_id(repo_id, file_id)
blklist = blks.split('\n')
except SearpcError, e:
return api_error(HTTP_520_OPERATION_FAILED,
'Failed to get file block list')
blklist = [i for i in blklist if len(i) == 40]
if len(blklist) > 0:
repo = get_repo(repo_id)
encrypted = repo.encrypted
enc_version = repo.enc_version
res = {
'file_id': file_id,
'blklist': blklist,
'encrypted': encrypted,
'enc_version': enc_version,
}
response = HttpResponse(json.dumps(res), status=200,
content_type=json_content_type)
response["oid"] = file_id
return response
if op == 'sharelink':
path = request.GET.get('p', None)
if path is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing.')
return get_shared_link(request, repo_id, path)
def reloaddir(request, repo, parent_dir):
try:
dir_id = seafile_api.get_dir_id_by_path(repo.id, parent_dir)
except SearpcError, e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to get dir id by path")
if not dir_id:
return api_error(status.HTTP_404_NOT_FOUND, "Path does not exist")
return get_dir_entrys_by_id(request, repo, parent_dir, dir_id)
def reloaddir_if_necessary (request, repo, parent_dir):
reload_dir = False
s = request.GET.get('reloaddir', None)
if s and s.lower() == 'true':
reload_dir = True
if not reload_dir:
return Response('success')
return reloaddir(request, repo, parent_dir)
# deprecated
class OpDeleteView(APIView):
"""
Delete files.
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
def post(self, request, repo_id, format=None):
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
username = request.user.username
if not is_repo_writable(repo.id, username):
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to delete this file.')
resp = check_repo_access_permission(request, repo)
if resp:
return resp
parent_dir = request.GET.get('p')
file_names = request.POST.get("file_names")
if not parent_dir or not file_names:
return api_error(status.HTTP_404_NOT_FOUND,
'File or directory not found.')
parent_dir_utf8 = parent_dir.encode('utf-8')
for file_name in file_names.split(':'):
file_name = unquote(file_name.encode('utf-8'))
try:
seafile_api.del_file(repo_id, parent_dir_utf8,
file_name, username)
except SearpcError, e:
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to delete file.")
return reloaddir_if_necessary (request, repo, parent_dir_utf8)
class OpMoveView(APIView):
"""
Move files.
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
def post(self, request, repo_id, format=None):
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
username = request.user.username
parent_dir = request.GET.get('p', '/')
dst_repo = request.POST.get('dst_repo', None)
dst_dir = request.POST.get('dst_dir', None)
file_names = request.POST.get("file_names", None)
if not parent_dir or not file_names or not dst_repo or not dst_dir:
return api_error(status.HTTP_400_BAD_REQUEST,
'Missing argument.')
if check_folder_permission(request, repo_id, parent_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to move file in this folder.')
if check_folder_permission(request, dst_repo, dst_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to move file to destination folder.')
if repo_id == dst_repo and parent_dir == dst_dir:
return api_error(status.HTTP_400_BAD_REQUEST,
'The destination directory is the same as the source.')
parent_dir_utf8 = parent_dir.encode('utf-8')
for file_name in file_names.split(':'):
file_name = unquote(file_name.encode('utf-8'))
new_filename = check_filename_with_rename_utf8(dst_repo, dst_dir,
file_name)
try:
seafile_api.move_file(repo_id, parent_dir_utf8, file_name,
dst_repo, dst_dir, new_filename,
username, 0, synchronous=1)
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to move file.")
return reloaddir_if_necessary (request, repo, parent_dir_utf8)
class OpCopyView(APIView):
"""
Copy files.
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
def post(self, request, repo_id, format=None):
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
username = request.user.username
parent_dir = request.GET.get('p', '/')
dst_repo = request.POST.get('dst_repo', None)
dst_dir = request.POST.get('dst_dir', None)
file_names = request.POST.get("file_names", None)
if not parent_dir or not file_names or not dst_repo or not dst_dir:
return api_error(status.HTTP_400_BAD_REQUEST,
'Missing argument.')
if check_folder_permission(request, repo_id, parent_dir) is None:
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to copy file of this folder.')
if check_folder_permission(request, dst_repo, dst_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to copy file to destination folder.')
if not get_repo(dst_repo):
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
if seafile_api.get_dir_id_by_path(repo_id, parent_dir) is None or \
seafile_api.get_dir_id_by_path(dst_repo, dst_dir) is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path does not exist.')
parent_dir_utf8 = parent_dir.encode('utf-8')
for file_name in file_names.split(':'):
file_name = unquote(file_name.encode('utf-8'))
new_filename = check_filename_with_rename_utf8(dst_repo, dst_dir,
file_name)
try:
seafile_api.copy_file(repo_id, parent_dir_utf8, file_name,
dst_repo, dst_dir, new_filename,
username, 0, synchronous=1)
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to copy file.")
return reloaddir_if_necessary(request, repo, parent_dir_utf8)
class StarredFileView(APIView):
"""
Support uniform interface for starred file operation,
including add/delete/list starred files.
"""
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
# list starred files
personal_files = UserStarredFiles.objects.get_starred_files_by_username(
request.user.username)
starred_files = prepare_starred_files(personal_files)
return Response(starred_files)
def post(self, request, format=None):
# add starred file
repo_id = request.POST.get('repo_id', '')
path = request.POST.get('p', '')
if not (repo_id and path):
return api_error(status.HTTP_400_BAD_REQUEST,
'Library ID or path is missing.')
if check_folder_permission(request, repo_id, path) is None:
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied')
try:
file_id = seafile_api.get_file_id_by_path(repo_id, path)
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal error')
if not file_id:
return api_error(status.HTTP_404_NOT_FOUND, "File not found")
if path[-1] == '/': # Should not contain '/' at the end of path.
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid file path.')
star_file(request.user.username, repo_id, path, is_dir=False,
org_id=-1)
resp = Response('success', status=status.HTTP_201_CREATED)
resp['Location'] = reverse('starredfiles')
return resp
def delete(self, request, format=None):
# remove starred file
repo_id = request.GET.get('repo_id', '')
path = request.GET.get('p', '')
if not (repo_id and path):
return api_error(status.HTTP_400_BAD_REQUEST,
'Library ID or path is missing.')
if check_folder_permission(request, repo_id, path) is None:
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied')
try:
file_id = seafile_api.get_file_id_by_path(repo_id, path)
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal error')
if not file_id:
return api_error(status.HTTP_404_NOT_FOUND, "File not found")
if path[-1] == '/': # Should not contain '/' at the end of path.
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid file path.')
unstar_file(request.user.username, repo_id, path)
return Response('success', status=status.HTTP_200_OK)
class FileView(APIView):
"""
Support uniform interface for file related operations,
including create/delete/rename/view, etc.
"""
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
# view file
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
path = request.GET.get('p', None)
if not path:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing.')
if check_folder_permission(request, repo_id, path) is None:
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this file.')
file_id = None
try:
file_id = seafile_api.get_file_id_by_path(repo_id,
path.encode('utf-8'))
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to get file id by path.")
if not file_id:
return api_error(status.HTTP_404_NOT_FOUND, "File not found")
# send stats message
send_file_access_msg(request, repo, path, 'api')
file_name = os.path.basename(path)
op = request.GET.get('op', 'download')
reuse = request.GET.get('reuse', '0')
if reuse not in ('1', '0'):
return api_error(status.HTTP_400_BAD_REQUEST,
"If you want to reuse file server access token for download file, you should set 'reuse' argument as '1'.")
use_onetime = False if reuse == '1' else True
return get_repo_file(request, repo_id, file_id,
file_name, op, use_onetime)
def post(self, request, repo_id, format=None):
# rename, move, copy or create file
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
path = request.GET.get('p', '')
if not path or path[0] != '/':
return api_error(status.HTTP_400_BAD_REQUEST,
'Path is missing or invalid.')
username = request.user.username
parent_dir = os.path.dirname(path)
operation = request.POST.get('operation', '')
if operation.lower() == 'rename':
if check_folder_permission(request, repo_id, path) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to rename file.')
newname = request.POST.get('newname', '')
if not newname:
return api_error(status.HTTP_400_BAD_REQUEST,
'New name is missing')
newname = unquote(newname.encode('utf-8'))
if len(newname) > settings.MAX_UPLOAD_FILE_NAME_LEN:
return api_error(status.HTTP_400_BAD_REQUEST, 'New name is too long')
parent_dir_utf8 = parent_dir.encode('utf-8')
oldname = os.path.basename(path)
if oldname == newname:
return api_error(status.HTTP_409_CONFLICT,
'The new name is the same to the old')
newname = check_filename_with_rename_utf8(repo_id, parent_dir,
newname)
try:
seafile_api.rename_file(repo_id, parent_dir, oldname, newname,
username)
except SearpcError,e:
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to rename file: %s" % e)
if request.GET.get('reloaddir', '').lower() == 'true':
return reloaddir(request, repo, parent_dir_utf8)
else:
resp = Response('success', status=status.HTTP_301_MOVED_PERMANENTLY)
uri = reverse('FileView', args=[repo_id], request=request)
resp['Location'] = uri + '?p=' + quote(parent_dir_utf8) + quote(newname)
return resp
elif operation.lower() == 'move':
if check_folder_permission(request, repo_id, path) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to move file.')
src_dir = os.path.dirname(path)
src_dir_utf8 = src_dir.encode('utf-8')
src_repo_id = repo_id
dst_repo_id = request.POST.get('dst_repo', '')
dst_dir = request.POST.get('dst_dir', '')
dst_dir_utf8 = dst_dir.encode('utf-8')
if dst_dir[-1] != '/': # Append '/' to the end of directory if necessary
dst_dir += '/'
# obj_names = request.POST.get('obj_names', '')
if not (dst_repo_id and dst_dir):
return api_error(status.HTTP_400_BAD_REQUEST, 'Missing arguments.')
if src_repo_id == dst_repo_id and src_dir == dst_dir:
return Response('success', status=status.HTTP_200_OK)
if check_folder_permission(request, dst_repo_id, dst_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to move file.')
# names = obj_names.split(':')
# names = map(lambda x: unquote(x).decode('utf-8'), names)
# if dst_dir.startswith(src_dir):
# for obj_name in names:
# if dst_dir.startswith('/'.join([src_dir, obj_name])):
# return api_error(status.HTTP_409_CONFLICT,
# 'Can not move a dirctory to its subdir')
filename = os.path.basename(path)
filename_utf8 = filename.encode('utf-8')
new_filename_utf8 = check_filename_with_rename_utf8(dst_repo_id,
dst_dir,
filename)
try:
seafile_api.move_file(src_repo_id, src_dir_utf8,
filename_utf8, dst_repo_id,
dst_dir_utf8, new_filename_utf8,
username, 0, synchronous=1)
except SearpcError, e:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
"SearpcError:" + e.msg)
dst_repo = get_repo(dst_repo_id)
if not dst_repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
if request.GET.get('reloaddir', '').lower() == 'true':
return reloaddir(request, dst_repo, dst_dir)
else:
resp = Response('success', status=status.HTTP_301_MOVED_PERMANENTLY)
uri = reverse('FileView', args=[dst_repo_id], request=request)
resp['Location'] = uri + '?p=' + quote(dst_dir_utf8) + quote(new_filename_utf8)
return resp
elif operation.lower() == 'copy':
src_repo_id = repo_id
src_dir = os.path.dirname(path)
src_dir_utf8 = src_dir.encode('utf-8')
dst_repo_id = request.POST.get('dst_repo', '')
dst_dir = request.POST.get('dst_dir', '')
dst_dir_utf8 = dst_dir.encode('utf-8')
if dst_dir[-1] != '/': # Append '/' to the end of directory if necessary
dst_dir += '/'
if not (dst_repo_id and dst_dir):
return api_error(status.HTTP_400_BAD_REQUEST, 'Missing arguments.')
if src_repo_id == dst_repo_id and src_dir == dst_dir:
return Response('success', status=status.HTTP_200_OK)
# check src folder permission
if check_folder_permission(request, repo_id, path) is None:
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to copy file.')
# check dst folder permission
if check_folder_permission(request, dst_repo_id, dst_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to copy file.')
filename = os.path.basename(path)
filename_utf8 = filename.encode('utf-8')
new_filename_utf8 = check_filename_with_rename_utf8(dst_repo_id,
dst_dir,
filename)
try:
seafile_api.copy_file(src_repo_id, src_dir_utf8,
filename_utf8, dst_repo_id,
dst_dir_utf8, new_filename_utf8,
username, 0, synchronous=1)
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
"SearpcError:" + e.msg)
if request.GET.get('reloaddir', '').lower() == 'true':
return reloaddir(request, dst_repo, dst_dir)
else:
resp = Response('success', status=status.HTTP_200_OK)
uri = reverse('FileView', args=[dst_repo_id], request=request)
resp['Location'] = uri + '?p=' + quote(dst_dir_utf8) + quote(new_filename_utf8)
return resp
elif operation.lower() == 'create':
if check_folder_permission(request, repo_id, parent_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to create file.')
parent_dir_utf8 = parent_dir.encode('utf-8')
new_file_name = os.path.basename(path)
new_file_name_utf8 = check_filename_with_rename_utf8(repo_id,
parent_dir,
new_file_name)
try:
seafile_api.post_empty_file(repo_id, parent_dir,
new_file_name_utf8, username)
except SearpcError, e:
return api_error(HTTP_520_OPERATION_FAILED,
'Failed to create file.')
if request.GET.get('reloaddir', '').lower() == 'true':
return reloaddir(request, repo, parent_dir)
else:
resp = Response('success', status=status.HTTP_201_CREATED)
uri = reverse('FileView', args=[repo_id], request=request)
resp['Location'] = uri + '?p=' + quote(parent_dir_utf8) + \
quote(new_file_name_utf8)
return resp
else:
return api_error(status.HTTP_400_BAD_REQUEST,
"Operation can only be rename, create or move.")
def put(self, request, repo_id, format=None):
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
path = request.DATA.get('p', '')
file_id = seafile_api.get_file_id_by_path(repo_id, path)
if not path or not file_id:
return api_error(status.HTTP_400_BAD_REQUEST,
'Path is missing or invalid.')
username = request.user.username
# check file access permission
if check_folder_permission(request, repo_id, path) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
operation = request.DATA.get('operation', '')
if operation.lower() == 'lock':
is_locked, locked_by_me = check_file_lock(repo_id, path, username)
if is_locked:
return api_error(status.HTTP_403_FORBIDDEN, 'File is already locked')
# lock file
expire = request.DATA.get('expire', FILE_LOCK_EXPIRATION_DAYS)
try:
seafile_api.lock_file(repo_id, path.lstrip('/'), username, expire)
return Response('success', status=status.HTTP_200_OK)
except SearpcError, e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal error')
if operation.lower() == 'unlock':
is_locked, locked_by_me = check_file_lock(repo_id, path, username)
if not is_locked:
return api_error(status.HTTP_403_FORBIDDEN, 'File is not locked')
if not locked_by_me:
return api_error(status.HTTP_403_FORBIDDEN, 'You can not unlock this file')
# unlock file
try:
seafile_api.unlock_file(repo_id, path.lstrip('/'))
return Response('success', status=status.HTTP_200_OK)
except SearpcError, e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal error')
else:
return api_error(status.HTTP_400_BAD_REQUEST,
"Operation can only be lock or unlock")
def delete(self, request, repo_id, format=None):
# delete file
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
path = request.GET.get('p', None)
if not path:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing.')
parent_dir = os.path.dirname(path)
if check_folder_permission(request, repo_id, parent_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
parent_dir_utf8 = os.path.dirname(path).encode('utf-8')
file_name_utf8 = os.path.basename(path).encode('utf-8')
try:
seafile_api.del_file(repo_id, parent_dir_utf8,
file_name_utf8,
request.user.username)
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to delete file.")
return reloaddir_if_necessary(request, repo, parent_dir_utf8)
class FileDetailView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
repo = seafile_api.get_repo(repo_id)
if repo is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Library not found.')
path = request.GET.get('p', None)
if path is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing.')
commit_id = request.GET.get('commit_id', None)
if commit_id:
try:
obj_id = seafserv_threaded_rpc.get_file_id_by_commit_and_path(
repo.id, commit_id, path)
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
'Failed to get file id.')
else:
try:
obj_id = seafile_api.get_file_id_by_path(repo_id,
path.encode('utf-8'))
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
'Failed to get file id.')
if not obj_id:
return api_error(status.HTTP_404_NOT_FOUND, 'File not found.')
# fetch file contributors and latest contributor
try:
# get real path for sub repo
real_path = repo.origin_path + path if repo.origin_path else path
dirent = seafile_api.get_dirent_by_path(repo.store_id, real_path)
if dirent:
latest_contributor, last_modified = dirent.modifier, dirent.mtime
else:
latest_contributor, last_modified = None, 0
except SearpcError as e:
logger.error(e)
latest_contributor, last_modified = None, 0
entry = {}
try:
entry["size"] = get_file_size(repo.store_id, repo.version, obj_id)
except Exception, e:
entry["size"] = 0
entry["type"] = "file"
entry["name"] = os.path.basename(path)
entry["id"] = obj_id
entry["mtime"] = last_modified
return HttpResponse(json.dumps(entry), status=200,
content_type=json_content_type)
class FileRevert(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def put(self, request, repo_id, format=None):
path = request.DATA.get('p', '')
if not path:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing.')
username = request.user.username
is_locked, locked_by_me = check_file_lock(repo_id, path, username)
if (is_locked, locked_by_me) == (None, None):
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Check file lock error')
if is_locked and not locked_by_me:
return api_error(status.HTTP_403_FORBIDDEN, 'File is locked')
parent_dir = os.path.dirname(path)
if check_folder_permission(request, repo_id, parent_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this folder.')
path = unquote(path.encode('utf-8'))
commit_id = unquote(request.DATA.get('commit_id', '').encode('utf-8'))
try:
ret = seafserv_threaded_rpc.revert_file(repo_id, commit_id,
path, username)
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, "Internal error")
return HttpResponse(json.dumps({"ret": ret}), status=200, content_type=json_content_type)
class FileRevision(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
path = request.GET.get('p', None)
if path is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing.')
file_name = os.path.basename(path)
commit_id = request.GET.get('commit_id', None)
try:
obj_id = seafserv_threaded_rpc.get_file_id_by_commit_and_path(
repo_id, commit_id, path)
except:
return api_error(status.HTTP_404_NOT_FOUND, 'Revision not found.')
return get_repo_file(request, repo_id, obj_id, file_name, 'download')
class FileHistory(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
path = request.GET.get('p', None)
if path is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing.')
try:
commits = seafserv_threaded_rpc.list_file_revisions(repo_id, path,
-1, -1)
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, "Internal error")
if not commits:
return api_error(status.HTTP_404_NOT_FOUND, 'File not found.')
return HttpResponse(json.dumps({"commits": commits}, cls=SearpcObjEncoder), status=200, content_type=json_content_type)
class FileSharedLinkView(APIView):
"""
Support uniform interface for file shared link.
"""
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def put(self, request, repo_id, format=None):
repo = seaserv.get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, "Library does not exist")
path = request.DATA.get('p', None)
if not path:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing')
username = request.user.username
password = request.DATA.get('password', None)
share_type = request.DATA.get('share_type', 'download')
if password and len(password) < config.SHARE_LINK_PASSWORD_MIN_LENGTH:
return api_error(status.HTTP_400_BAD_REQUEST, 'Password is too short')
if share_type.lower() == 'download':
if check_file_permission(request, repo_id, path) is None:
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied')
expire = request.DATA.get('expire', None)
if expire:
try:
expire_days = int(expire)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid expiration days')
else:
expire_date = timezone.now() + relativedelta(days=expire_days)
else:
expire_date = None
is_dir = False
if path == '/':
is_dir = True
else:
try:
dirent = seafile_api.get_dirent_by_path(repo_id, path)
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, "Internal error")
if not dirent:
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid path')
if stat.S_ISDIR(dirent.mode):
is_dir = True
if is_dir:
# generate dir download link
fs = FileShare.objects.get_dir_link_by_path(username, repo_id, path)
if fs is None:
fs = FileShare.objects.create_dir_link(username, repo_id, path,
password, expire_date)
if is_org_context(request):
org_id = request.user.org.org_id
OrgFileShare.objects.set_org_file_share(org_id, fs)
else:
# generate file download link
fs = FileShare.objects.get_file_link_by_path(username, repo_id, path)
if fs is None:
fs = FileShare.objects.create_file_link(username, repo_id, path,
password, expire_date)
if is_org_context(request):
org_id = request.user.org.org_id
OrgFileShare.objects.set_org_file_share(org_id, fs)
token = fs.token
shared_link = gen_shared_link(token, fs.s_type)
elif share_type.lower() == 'upload':
if not seafile_api.get_dir_id_by_path(repo_id, path):
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid path')
if check_folder_permission(request, repo_id, path) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied')
# generate upload link
uls = UploadLinkShare.objects.get_upload_link_by_path(username, repo_id, path)
if uls is None:
uls = UploadLinkShare.objects.create_upload_link_share(
username, repo_id, path, password)
token = uls.token
shared_link = gen_shared_upload_link(token)
else:
return api_error(status.HTTP_400_BAD_REQUEST,
"Operation can only be download or upload.")
resp = Response(status=status.HTTP_201_CREATED)
resp['Location'] = shared_link
return resp
########## Directory related
class DirView(APIView):
"""
Support uniform interface for directory operations, including
create/delete/rename/list, etc.
"""
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
# list dir
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
path = request.GET.get('p', '/')
if path[-1] != '/':
path = path + '/'
if check_folder_permission(request, repo_id, path) is None:
return api_error(status.HTTP_403_FORBIDDEN, 'Forbid to access this folder.')
try:
dir_id = seafile_api.get_dir_id_by_path(repo_id,
path.encode('utf-8'))
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to get dir id by path.")
if not dir_id:
return api_error(status.HTTP_404_NOT_FOUND, "Path does not exist")
old_oid = request.GET.get('oid', None)
if old_oid and old_oid == dir_id:
response = HttpResponse(json.dumps("uptodate"), status=200,
content_type=json_content_type)
response["oid"] = dir_id
return response
else:
request_type = request.GET.get('t', None)
if request_type and request_type not in ('f', 'd'):
return api_error(status.HTTP_400_BAD_REQUEST,
"'t'(type) should be 'f' or 'd'.")
if request_type == 'd':
recursive = request.GET.get('recursive', '0')
if recursive not in ('1', '0'):
return api_error(status.HTTP_400_BAD_REQUEST,
"If you want to get recursive dir entries, you should set 'recursive' argument as '1'.")
if recursive == '1':
username = request.user.username
dir_list = get_dir_recursively(username, repo_id, path, [])
dir_list.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))
response = HttpResponse(json.dumps(dir_list), status=200,
content_type=json_content_type)
response["oid"] = dir_id
response["dir_perm"] = seafile_api.check_permission_by_path(repo_id, path, username)
return response
return get_dir_entrys_by_id(request, repo, path, dir_id, request_type)
def post(self, request, repo_id, format=None):
# new dir
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
path = request.GET.get('p', '')
if not path or path[0] != '/':
return api_error(status.HTTP_400_BAD_REQUEST, "Path is missing.")
if path == '/': # Can not make or rename root dir.
return api_error(status.HTTP_400_BAD_REQUEST, "Path is invalid.")
if path[-1] == '/': # Cut out last '/' if possible.
path = path[:-1]
username = request.user.username
operation = request.POST.get('operation', '')
parent_dir = os.path.dirname(path)
parent_dir_utf8 = parent_dir.encode('utf-8')
if operation.lower() == 'mkdir':
parent_dir = os.path.dirname(path)
if check_folder_permission(request, repo_id, parent_dir) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN, 'You do not have permission to access this folder.')
create_parents = request.POST.get('create_parents', '').lower() in ('true', '1')
if not create_parents:
# check whether parent dir exists
if not seafile_api.get_dir_id_by_path(repo_id, parent_dir):
return api_error(status.HTTP_400_BAD_REQUEST,
'Parent dir does not exist')
new_dir_name = os.path.basename(path)
new_dir_name_utf8 = check_filename_with_rename_utf8(repo_id,
parent_dir,
new_dir_name)
try:
seafile_api.post_dir(repo_id, parent_dir,
new_dir_name_utf8, username)
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
'Failed to make directory.')
else:
if not is_seafile_pro():
return api_error(status.HTTP_400_BAD_REQUEST,
'Feature not supported.')
try:
seafile_api.mkdir_with_parents(repo_id, '/',
path[1:], username)
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
'Failed to make directory.')
new_dir_name_utf8 = os.path.basename(path).encode('utf-8')
if request.GET.get('reloaddir', '').lower() == 'true':
resp = reloaddir(request, repo, parent_dir)
else:
resp = Response('success', status=status.HTTP_201_CREATED)
uri = reverse('DirView', args=[repo_id], request=request)
resp['Location'] = uri + '?p=' + quote(parent_dir_utf8) + \
quote(new_dir_name_utf8)
return resp
elif operation.lower() == 'rename':
if check_folder_permission(request, repo.id, path) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN, 'You do not have permission to access this folder.')
parent_dir = os.path.dirname(path)
old_dir_name = os.path.basename(path)
newname = request.POST.get('newname', '')
if not newname:
return api_error(status.HTTP_400_BAD_REQUEST, "New name is mandatory.")
if newname == old_dir_name:
return Response('success', status=status.HTTP_200_OK)
try:
# rename duplicate name
checked_newname = check_filename_with_rename(
repo_id, parent_dir, newname)
# rename dir
seafile_api.rename_file(repo_id, parent_dir, old_dir_name,
checked_newname, username)
return Response('success', status=status.HTTP_200_OK)
except SearpcError, e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
'Failed to rename folder.')
# elif operation.lower() == 'move':
# pass
else:
return api_error(status.HTTP_400_BAD_REQUEST,
"Operation not supported.")
def delete(self, request, repo_id, format=None):
# delete dir or file
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
path = request.GET.get('p', None)
if not path:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing.')
if check_folder_permission(request, repo_id, path) != 'rw':
return api_error(status.HTTP_403_FORBIDDEN, 'You do not have permission to access this folder.')
if path == '/': # Can not delete root path.
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is invalid.')
if path[-1] == '/': # Cut out last '/' if possible.
path = path[:-1]
parent_dir = os.path.dirname(path)
parent_dir_utf8 = os.path.dirname(path).encode('utf-8')
file_name_utf8 = os.path.basename(path).encode('utf-8')
username = request.user.username
try:
seafile_api.del_file(repo_id, parent_dir_utf8,
file_name_utf8, username)
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to delete file.")
return reloaddir_if_necessary(request, repo, parent_dir_utf8)
class DirDownloadView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
path = request.GET.get('p', None)
if path is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing.')
if path[-1] != '/': # Normalize dir path
path += '/'
if len(path) > 1:
dirname = os.path.basename(path.rstrip('/'))
else:
dirname = repo.name
current_commit = get_commits(repo_id, 0, 1)[0]
if not current_commit:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
'Failed to get current commit of repo %s.' % repo_id)
try:
dir_id = seafserv_threaded_rpc.get_dirid_by_path(current_commit.repo_id,
current_commit.id,
path.encode('utf-8'))
except SearpcError, e:
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to get dir id by path")
if not dir_id:
return api_error(status.HTTP_404_NOT_FOUND, "Path does not exist")
try:
total_size = seafserv_threaded_rpc.get_dir_size(repo.store_id, repo.version,
dir_id)
except Exception, e:
logger.error(str(e))
return api_error(HTTP_520_OPERATION_FAILED, "Internal error")
if total_size > MAX_DOWNLOAD_DIR_SIZE:
return api_error(status.HTTP_400_BAD_REQUEST,
'Unable to download directory "%s": size is too large.' % dirname)
token = seafile_api.get_fileserver_access_token(repo_id,
dir_id,
'download-dir',
request.user.username)
redirect_url = gen_file_get_url(token, dirname)
return HttpResponse(json.dumps(redirect_url), status=200,
content_type=json_content_type)
class DirShareView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
# from seahub.share.view::gen_private_file_share
def post(self, request, repo_id, format=None):
emails = request.POST.getlist('emails', '')
s_type = request.POST.get('s_type', '')
path = request.POST.get('path', '')
perm = request.POST.get('perm', 'r')
file_or_dir = os.path.basename(path.rstrip('/'))
username = request.user.username
for email in [e.strip() for e in emails if e.strip()]:
if not is_registered_user(email):
continue
if s_type == 'f':
pfds = PrivateFileDirShare.objects.add_read_only_priv_file_share(
username, email, repo_id, path)
elif s_type == 'd':
pfds = PrivateFileDirShare.objects.add_private_dir_share(
username, email, repo_id, path, perm)
else:
continue
# send a signal when sharing file successful
share_file_to_user_successful.send(sender=None, priv_share_obj=pfds)
return HttpResponse(json.dumps({}), status=200, content_type=json_content_type)
class DirSubRepoView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
# from seahub.views.ajax.py::sub_repo
def get(self, request, repo_id, format=None):
'''
check if a dir has a corresponding sub_repo
if it does not have, create one
'''
result = {}
path = request.GET.get('p')
name = request.GET.get('name')
password = request.GET.get('password', None)
repo = get_repo(repo_id)
if not repo:
result['error'] = 'Library not found.'
return HttpResponse(json.dumps(result), status=404, content_type=json_content_type)
if not (path and name):
result['error'] = 'Argument missing'
return HttpResponse(json.dumps(result), status=400, content_type=json_content_type)
username = request.user.username
# check if the sub-lib exist
try:
sub_repo = seafile_api.get_virtual_repo(repo_id, path, username)
except SearpcError, e:
result['error'] = e.msg
return HttpResponse(json.dumps(result), status=500, content_type=json_content_type)
if sub_repo:
result['sub_repo_id'] = sub_repo.id
else:
if not request.user.permissions.can_add_repo():
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to create library.')
# create a sub-lib
try:
# use name as 'repo_name' & 'repo_desc' for sub_repo
if repo.encrypted:
if password:
sub_repo_id = seafile_api.create_virtual_repo(repo_id,
path, name, name, username, password)
else:
result['error'] = 'Password Required.'
return HttpResponse(json.dumps(result), status=403, content_type=json_content_type)
else:
sub_repo_id = seafile_api.create_virtual_repo(repo_id, path, name, name, username)
result['sub_repo_id'] = sub_repo_id
except SearpcError, e:
result['error'] = e.msg
return HttpResponse(json.dumps(result), status=500, content_type=json_content_type)
return HttpResponse(json.dumps(result), content_type=json_content_type)
########## Sharing
class SharedRepos(APIView):
"""
List repos that a user share to others/groups/public.
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
username = request.user.username
shared_repos = []
shared_repos += list_share_repos(username, 'from_email', -1, -1)
shared_repos += get_group_repos_by_owner(username)
if not CLOUD_MODE:
shared_repos += list_inner_pub_repos_by_owner(username)
return HttpResponse(json.dumps(shared_repos, cls=SearpcObjEncoder),
status=200, content_type=json_content_type)
class BeShared(APIView):
"""
List repos that others/groups share to user.
"""
authentication_classes = (TokenAuthentication, SessionAuthentication )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
username = request.user.username
shared_repos = []
shared_repos += seafile_api.get_share_in_repo_list(username, -1, -1)
joined_groups = get_personal_groups_by_user(username)
for grp in joined_groups:
# Get group repos, and for each group repos...
for r_id in get_group_repoids(grp.id):
# No need to list my own repo
if seafile_api.is_repo_owner(username, r_id):
continue
# Convert repo properties due to the different collumns in Repo
# and SharedRepo
r = get_repo(r_id)
if not r:
continue
r.repo_id = r.id
r.repo_name = r.name
r.repo_desc = r.desc
cmmts = get_commits(r_id, 0, 1)
last_commit = cmmts[0] if cmmts else None
r.last_modified = last_commit.ctime if last_commit else 0
r._dict['share_type'] = 'group'
r.user = seafile_api.get_repo_owner(r_id)
r.user_perm = check_permission(r_id, username)
shared_repos.append(r)
if not CLOUD_MODE:
shared_repos += seaserv.list_inner_pub_repos(username)
return HttpResponse(json.dumps(shared_repos, cls=SearpcObjEncoder),
status=200, content_type=json_content_type)
class PrivateFileDirShareEncoder(json.JSONEncoder):
def default(self, obj):
if not isinstance(obj, PrivateFileDirShare):
return None
return {'from_user':obj.from_user, 'to_user':obj.to_user,
'repo_id':obj.repo_id, 'path':obj.path, 'token':obj.token,
'permission':obj.permission, 's_type':obj.s_type}
class SharedFilesView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
# from seahub.share.view::list_priv_shared_files
def get(self, request, format=None):
username = request.user.username
# Private share out/in files.
priv_share_out = PrivateFileDirShare.objects.list_private_share_out_by_user(username)
for e in priv_share_out:
e.file_or_dir = os.path.basename(e.path.rstrip('/'))
e.repo = seafile_api.get_repo(e.repo_id)
priv_share_in = PrivateFileDirShare.objects.list_private_share_in_by_user(username)
for e in priv_share_in:
e.file_or_dir = os.path.basename(e.path.rstrip('/'))
e.repo = seafile_api.get_repo(e.repo_id)
return HttpResponse(json.dumps({"priv_share_out": list(priv_share_out), "priv_share_in": list(priv_share_in)}, cls=PrivateFileDirShareEncoder),
status=200, content_type=json_content_type)
# from seahub.share.view:rm_private_file_share
def delete(self, request, format=None):
token = request.GET.get('t')
try:
pfs = PrivateFileDirShare.objects.get_priv_file_dir_share_by_token(token)
except PrivateFileDirShare.DoesNotExist:
return api_error(status.HTTP_404_NOT_FOUND, "Token does not exist")
from_user = pfs.from_user
to_user = pfs.to_user
username = request.user.username
if username == from_user or username == to_user:
pfs.delete()
return HttpResponse(json.dumps({}), status=200, content_type=json_content_type)
else:
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to access this library.')
class VirtualRepos(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
result = {}
try:
virtual_repos = get_virtual_repos_by_owner(request)
except SearpcError, e:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
"error:" + e.msg)
result['virtual-repos'] = virtual_repos
return HttpResponse(json.dumps(result, cls=SearpcObjEncoder),
content_type=json_content_type)
class PrivateSharedFileView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, token, format=None):
assert token is not None # Checked by URLconf
try:
fileshare = PrivateFileDirShare.objects.get(token=token)
except PrivateFileDirShare.DoesNotExist:
return api_error(status.HTTP_404_NOT_FOUND, "Token not found")
shared_to = fileshare.to_user
if shared_to != request.user.username:
return api_error(status.HTTP_403_FORBIDDEN, "You don't have permission to view this file")
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, "Library not found")
path = fileshare.path.rstrip('/') # Normalize file path
file_name = os.path.basename(path)
file_id = None
try:
file_id = seafserv_threaded_rpc.get_file_id_by_path(repo_id,
path.encode('utf-8'))
except SearpcError, e:
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to get file id by path.")
if not file_id:
return api_error(status.HTTP_404_NOT_FOUND, "File not found")
op = request.GET.get('op', 'download')
return get_repo_file(request, repo_id, file_id, file_name, op)
class SharedFileView(APIView):
# Anyone should be able to access a Shared File assuming they have the token
throttle_classes = (UserRateThrottle, )
def get(self, request, token, format=None):
assert token is not None # Checked by URLconf
try:
fileshare = FileShare.objects.get(token=token)
except FileShare.DoesNotExist:
return api_error(status.HTTP_404_NOT_FOUND, "Token not found")
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, "Library not found")
path = fileshare.path.rstrip('/') # Normalize file path
file_name = os.path.basename(path)
file_id = None
try:
file_id = seafserv_threaded_rpc.get_file_id_by_path(repo_id,
path.encode('utf-8'))
except SearpcError, e:
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to get file id by path.")
if not file_id:
return api_error(status.HTTP_404_NOT_FOUND, "File not found")
# Increase file shared link view_cnt, this operation should be atomic
fileshare.view_cnt = F('view_cnt') + 1
fileshare.save()
op = request.GET.get('op', 'download')
return get_repo_file(request, repo_id, file_id, file_name, op)
class SharedFileDetailView(APIView):
throttle_classes = (UserRateThrottle, )
def get(self, request, token, format=None):
assert token is not None # Checked by URLconf
try:
fileshare = FileShare.objects.get(token=token)
except FileShare.DoesNotExist:
return api_error(status.HTTP_404_NOT_FOUND, "Token not found")
if fileshare.is_encrypted():
password = request.GET.get('password', '')
if not password:
return api_error(status.HTTP_403_FORBIDDEN, "Password is required")
if not check_password(password, fileshare.password):
return api_error(status.HTTP_403_FORBIDDEN, "Invalid Password")
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, "Library not found")
path = fileshare.path.rstrip('/') # Normalize file path
file_name = os.path.basename(path)
file_id = None
try:
file_id = seafserv_threaded_rpc.get_file_id_by_path(repo_id,
path.encode('utf-8'))
commits = seafserv_threaded_rpc.list_file_revisions(repo_id, path,
-1, -1)
c = commits[0]
except SearpcError, e:
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to get file id by path.")
if not file_id:
return api_error(status.HTTP_404_NOT_FOUND, "File not found")
entry = {}
try:
entry["size"] = get_file_size(repo.store_id, repo.version, file_id)
except Exception as e:
logger.error(e)
entry["size"] = 0
entry["type"] = "file"
entry["name"] = file_name
entry["id"] = file_id
entry["mtime"] = c.ctime
entry["repo_id"] = repo_id
entry["path"] = path
return HttpResponse(json.dumps(entry), status=200,
content_type=json_content_type)
class PrivateSharedFileDetailView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, token, format=None):
assert token is not None # Checked by URLconf
try:
fileshare = PrivateFileDirShare.objects.get(token=token)
except PrivateFileDirShare.DoesNotExist:
return api_error(status.HTTP_404_NOT_FOUND, "Token not found")
shared_by = fileshare.from_user
shared_to = fileshare.to_user
if shared_to != request.user.username:
return api_error(status.HTTP_403_FORBIDDEN, "You don't have permission to view this file")
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, "Library not found")
path = fileshare.path.rstrip('/') # Normalize file path
file_name = os.path.basename(path)
file_id = None
try:
file_id = seafserv_threaded_rpc.get_file_id_by_path(repo_id,
path.encode('utf-8'))
commits = seafserv_threaded_rpc.list_file_revisions(repo_id, path,
-1, -1)
c = commits[0]
except SearpcError, e:
return api_error(HTTP_520_OPERATION_FAILED,
"Failed to get file id by path.")
if not file_id:
return api_error(status.HTTP_404_NOT_FOUND, "File not found")
entry = {}
try:
entry["size"] = get_file_size(repo.store_id, repo.version, file_id)
except Exception, e:
entry["size"] = 0
entry["type"] = "file"
entry["name"] = file_name
entry["id"] = file_id
entry["mtime"] = c.ctime
entry["repo_id"] = repo_id
entry["path"] = path
entry["shared_by"] = shared_by
return HttpResponse(json.dumps(entry), status=200,
content_type=json_content_type)
class FileShareEncoder(json.JSONEncoder):
def default(self, obj):
if not isinstance(obj, FileShare):
return None
return {'username':obj.username, 'repo_id':obj.repo_id,
'path':obj.path, 'token':obj.token,
'ctime':obj.ctime, 'view_cnt':obj.view_cnt,
's_type':obj.s_type}
class SharedLinksView(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
# from seahub.share.view::list_shared_links
def get(self, request, format=None):
username = request.user.username
fileshares = FileShare.objects.filter(username=username)
p_fileshares = [] # personal file share
for fs in fileshares:
if is_personal_repo(fs.repo_id): # only list files in personal repos
r = seafile_api.get_repo(fs.repo_id)
if not r:
fs.delete()
continue
if fs.s_type == 'f':
if seafile_api.get_file_id_by_path(r.id, fs.path) is None:
fs.delete()
continue
fs.filename = os.path.basename(fs.path)
fs.shared_link = gen_file_share_link(fs.token)
else:
if seafile_api.get_dir_id_by_path(r.id, fs.path) is None:
fs.delete()
continue
fs.filename = os.path.basename(fs.path.rstrip('/'))
fs.shared_link = gen_dir_share_link(fs.token)
fs.repo = r
p_fileshares.append(fs)
return HttpResponse(json.dumps({"fileshares": p_fileshares}, cls=FileShareEncoder), status=200, content_type=json_content_type)
def delete(self, request, format=None):
token = request.GET.get('t', None)
if not token:
return api_error(status.HTTP_400_BAD_REQUEST, 'Token is missing')
username = request.user.username
share = FileShare.objects.filter(token=token).filter(username=username) or \
UploadLinkShare.objects.filter(token=token).filter(username=username)
if not share:
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid token')
share.delete()
return HttpResponse(json.dumps({}), status=200, content_type=json_content_type)
class SharedDirView(APIView):
throttle_classes = (UserRateThrottle, )
def get(self, request, token, format=None):
"""List dirents in dir download shared link
"""
fileshare = FileShare.objects.get_valid_dir_link_by_token(token)
if not fileshare:
return api_error(status.HTTP_400_BAD_REQUEST, "Invalid token")
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_400_BAD_REQUEST, "Invalid token")
if fileshare.is_encrypted():
password = request.GET.get('password', '')
if not password:
return api_error(status.HTTP_403_FORBIDDEN, "Password is required")
if not check_password(password, fileshare.password):
return api_error(status.HTTP_403_FORBIDDEN, "Invalid Password")
req_path = request.GET.get('p', '/')
if req_path[-1] != '/':
req_path += '/'
if req_path == '/':
real_path = fileshare.path
else:
real_path = posixpath.join(fileshare.path, req_path.lstrip('/'))
if real_path[-1] != '/': # Normalize dir path
real_path += '/'
dir_id = seafile_api.get_dir_id_by_path(repo_id, real_path)
if not dir_id:
return api_error(status.HTTP_400_BAD_REQUEST, "Invalid path")
username = fileshare.username
try:
dirs = seafserv_threaded_rpc.list_dir_with_perm(repo_id, real_path, dir_id,
username, -1, -1)
dirs = dirs if dirs else []
except SearpcError, e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED, "Failed to list dir.")
dir_list, file_list = [], []
for dirent in dirs:
dtype = "file"
entry = {}
if stat.S_ISDIR(dirent.mode):
dtype = "dir"
else:
if repo.version == 0:
entry["size"] = get_file_size(repo.store_id, repo.version,
dirent.obj_id)
else:
entry["size"] = dirent.size
entry["type"] = dtype
entry["name"] = dirent.obj_name
entry["id"] = dirent.obj_id
entry["mtime"] = dirent.mtime
if dtype == 'dir':
dir_list.append(entry)
else:
file_list.append(entry)
dir_list.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))
file_list.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))
dentrys = dir_list + file_list
content_type = 'application/json; charset=utf-8'
return HttpResponse(json.dumps(dentrys), status=200, content_type=content_type)
class DefaultRepoView(APIView):
"""
Get user's default library.
"""
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
username = request.user.username
repo_id = UserOptions.objects.get_default_repo(username)
if repo_id is None or (get_repo(repo_id) is None):
json = {
'exists': False,
}
return Response(json)
else:
return self.default_repo_info(repo_id)
def default_repo_info(self, repo_id):
repo_json = {
'exists': False,
}
if repo_id is not None:
repo_json['exists'] = True
repo_json['repo_id'] = repo_id
return Response(repo_json)
def post(self, request):
if not request.user.permissions.can_add_repo():
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to create library.')
username = request.user.username
repo_id = UserOptions.objects.get_default_repo(username)
if repo_id and (get_repo(repo_id) is not None):
return self.default_repo_info(repo_id)
repo_id = create_default_library(request)
return self.default_repo_info(repo_id)
class SharedRepo(APIView):
"""
Support uniform interface for shared libraries.
"""
authentication_classes = (TokenAuthentication, SessionAuthentication )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def delete(self, request, repo_id, format=None):
"""
Unshare a library.
Repo owner and system admin can perform this operation.
"""
username = request.user.username
if not request.user.is_staff and not seafile_api.is_repo_owner(
username, repo_id):
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to unshare library.')
share_type = request.GET.get('share_type', '')
if not share_type:
return api_error(status.HTTP_400_BAD_REQUEST,
'Share type is required.')
if share_type == 'personal':
user = request.GET.get('user', '')
if not user:
return api_error(status.HTTP_400_BAD_REQUEST,
'User is required.')
if not is_valid_username(user):
return api_error(status.HTTP_400_BAD_REQUEST,
'User is not valid')
remove_share(repo_id, username, user)
elif share_type == 'group':
group_id = request.GET.get('group_id', '')
if not group_id:
return api_error(status.HTTP_400_BAD_REQUEST,
'Group ID is required.')
try:
group_id = int(group_id)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST,
'Group ID is not valid.')
seafile_api.unset_group_repo(repo_id, int(group_id), username)
elif share_type == 'public':
unset_inner_pub_repo(repo_id)
else:
return api_error(status.HTTP_400_BAD_REQUEST,
'Share type can only be personal or group or public.')
return Response('success', status=status.HTTP_200_OK)
def put(self, request, repo_id, format=None):
"""
Share a repo to users/groups/public.
"""
username = request.user.username
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo_id)
else:
repo_owner = seafile_api.get_repo_owner(repo_id)
if username != repo_owner:
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to share library.')
share_type = request.GET.get('share_type')
user = request.GET.get('user')
users = request.GET.get('users')
group_id = request.GET.get('group_id')
permission = request.GET.get('permission')
if permission != 'rw' and permission != "r":
return api_error(status.HTTP_400_BAD_REQUEST,
'Permission need to be rw or r.')
if share_type == 'personal':
from_email = seafile_api.get_repo_owner(repo_id)
shared_users = []
invalid_users = []
notexistent_users = []
notsharable_errors = []
usernames = []
if user:
usernames += user.split(",")
if users:
usernames += users.split(",")
if not user and not users:
return api_error(status.HTTP_400_BAD_REQUEST,
'User or users (comma separated are mandatory) are not provided')
for u in usernames:
if not u:
continue
if not is_valid_username(u):
invalid_users.append(u)
continue
if not is_registered_user(u):
notexistent_users.append(u)
continue
try:
seafile_api.share_repo(repo_id, from_email, u, permission)
shared_users.append(u)
except SearpcError, e:
logger.error(e)
notsharable_errors.append(e)
if invalid_users or notexistent_users or notsharable_errors:
# removing already created share
for s_user in shared_users:
try:
remove_share(repo_id, from_email, s_user)
except SearpcError, e:
# ignoring this error, go to next unsharing
continue
if invalid_users:
return api_error(status.HTTP_400_BAD_REQUEST,
'Some users are not valid, sharing rolled back')
if notexistent_users:
return api_error(status.HTTP_400_BAD_REQUEST,
'Some users are not existent, sharing rolled back')
if notsharable_errors:
# show the first sharing error
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
'Internal error occurs, sharing rolled back')
elif share_type == 'group':
try:
group_id = int(group_id)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST,
'Group ID must be integer.')
from_email = seafile_api.get_repo_owner(repo_id)
group = get_group(group_id)
if not group:
return api_error(status.HTTP_400_BAD_REQUEST,
'Group does not exist .')
try:
seafile_api.set_group_repo(repo_id, int(group_id),
from_email, permission)
except SearpcError, e:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
"Searpc Error: " + e.msg)
elif share_type == 'public':
if not CLOUD_MODE:
if not is_org_repo_creation_allowed(request):
return api_error(status.HTTP_403_FORBIDDEN,
'Failed to share library to public: permission denied.')
try:
seafile_api.add_inner_pub_repo(repo_id, permission)
except SearpcError, e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
'Failed to share library to public.')
else:
if is_org_context(request):
org_id = request.user.org.org_id
try:
seaserv.seafserv_threaded_rpc.set_org_inner_pub_repo(org_id, repo_id, permission)
send_perm_audit_msg('add-repo-perm', username, 'all', repo_id, '/', permission)
except SearpcError, e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
'Failed to share library to public.')
else:
return api_error(status.HTTP_403_FORBIDDEN,
'Failed to share library to public.')
else:
return api_error(status.HTTP_400_BAD_REQUEST,
'Share type can only be personal or group or public.')
return Response('success', status=status.HTTP_200_OK)
class GroupAndContacts(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
contacts, umsgnum, group_json, gmsgnum, replies, replynum = get_group_and_contacts(request.user.username)
res = {
"groups": group_json,
"contacts": contacts,
"newreplies":replies,
"replynum": replynum,
"umsgnum" : umsgnum,
"gmsgnum" : gmsgnum,
}
return Response(res)
class EventsView(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
if not EVENTS_ENABLED:
events = None
return api_error(status.HTTP_404_NOT_FOUND, 'Events not enabled.')
start = request.GET.get('start', '')
if not start:
start = 0
else:
try:
start = int(start)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST, 'Start id must be integer')
email = request.user.username
events_count = 15
if is_org_context(request):
org_id = request.user.org.org_id
events, events_more_offset = get_org_user_events(org_id, email,
start,
events_count)
else:
events, events_more_offset = get_user_events(email, start,
events_count)
events_more = True if len(events) == events_count else False
l = []
for e in events:
d = dict(etype=e.etype)
l.append(d)
if e.etype == 'repo-update':
d['author'] = e.commit.creator_name
d['time'] = e.commit.ctime
d['desc'] = e.commit.desc
d['repo_id'] = e.repo.id
d['repo_name'] = e.repo.name
d['commit_id'] = e.commit.id
d['converted_cmmt_desc'] = translate_commit_desc_escape(convert_cmmt_desc_link(e.commit))
d['more_files'] = e.commit.more_files
d['repo_encrypted'] = e.repo.encrypted
else:
d['repo_id'] = e.repo_id
d['repo_name'] = e.repo_name
if e.etype == 'repo-create':
d['author'] = e.creator
else:
d['author'] = e.repo_owner
epoch = datetime.datetime(1970, 1, 1)
local = utc_to_local(e.timestamp)
time_diff = local - epoch
d['time'] = time_diff.seconds + (time_diff.days * 24 * 3600)
d['nick'] = email2nickname(d['author'])
d['name'] = email2nickname(d['author'])
d['avatar'] = avatar(d['author'], 36)
d['time_relative'] = translate_seahub_time(utc_to_local(e.timestamp))
d['date'] = utc_to_local(e.timestamp).strftime("%Y-%m-%d")
ret = {
'events': l,
'more': events_more,
'more_offset': events_more_offset,
}
return Response(ret)
class UnseenMessagesCountView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
username = request.user.username
ret = { 'count' : UserNotification.objects.count_unseen_user_notifications(username)
}
return Response(ret)
########## Groups related
class Groups(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
size = request.GET.get('size', 36)
limit = int(request.GET.get('limit', 8))
with_msg = request.GET.get('with_msg', 'true')
# To not broken the old API, we need to make with_msg default
if with_msg == 'true':
group_json, replynum = get_groups(request.user.username)
res = {"groups": group_json, "replynum": replynum}
return Response(res)
else:
groups_json = []
joined_groups = get_personal_groups_by_user(request.user.username)
for g in joined_groups:
if limit <= 0:
break;
group = {
"id": g.id,
"name": g.group_name,
"creator": g.creator_name,
"ctime": g.timestamp,
"avatar": grp_avatar(g.id, int(size)),
}
groups_json.append(group)
limit = limit - 1
return Response(groups_json)
def put(self, request, format=None):
# modified slightly from groups/views.py::group_list
"""
Add a new group.
"""
result = {}
content_type = 'application/json; charset=utf-8'
username = request.user.username
if not request.user.permissions.can_add_group():
return api_error(status.HTTP_403_FORBIDDEN,
'You do not have permission to create group.')
# check plan
num_of_groups = getattr(request.user, 'num_of_groups', -1)
if num_of_groups > 0:
current_groups = len(get_personal_groups_by_user(username))
if current_groups > num_of_groups:
result['error'] = 'You can only create %d groups.' % num_of_groups
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
group_name = request.DATA.get('group_name', None)
group_name = group_name.strip()
if not validate_group_name(group_name):
result['error'] = 'Failed to rename group, group name can only contain letters, numbers, blank, hyphen or underscore.'
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
# Check whether group name is duplicated.
if request.cloud_mode:
checked_groups = get_personal_groups_by_user(username)
else:
checked_groups = get_personal_groups(-1, -1)
for g in checked_groups:
if g.group_name == group_name:
result['error'] = 'There is already a group with that name.'
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# Group name is valid, create that group.
try:
group_id = ccnet_threaded_rpc.create_group(group_name.encode('utf-8'),
username)
return HttpResponse(json.dumps({'success': True, 'group_id': group_id}),
content_type=content_type)
except SearpcError, e:
result['error'] = e.msg
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
def delete(self, request, group_id, format=None):
try:
group_id = int(group_id)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST, 'Bad group id format')
group = seaserv.get_group(group_id)
if not group:
return api_error(status.HTTP_404_NOT_FOUND, 'Group not found')
# permission check
username = request.user.username
if not seaserv.check_group_staff(group_id, username):
return api_error(status.HTTP_403_FORBIDDEN, 'You do not have permission to delete group')
# delete group
if is_org_context(request):
org_id = request.user.org.org_id
else:
org_id = None
try:
remove_group_common(group.id, username, org_id=org_id)
except SearpcError as e:
logger.error(e)
return api_error(HTTP_520_OPERATION_FAILED,
'Failed to remove group.')
return Response('success', status=status.HTTP_200_OK)
def post(self, request, group_id, format=None):
group = seaserv.get_group(group_id)
if not group:
return api_error(status.HTTP_404_NOT_FOUND, 'Group not found')
# permission check
username = request.user.username
if not seaserv.check_group_staff(group.id, username):
return api_error(status.HTTP_403_FORBIDDEN, 'You do not have permission to rename group')
operation = request.POST.get('operation', '')
if operation.lower() == 'rename':
newname = request.POST.get('newname', '')
if not newname:
return api_error(status.HTTP_400_BAD_REQUEST,
'New name is missing')
try:
rename_group_with_new_name(request, group.id, newname)
except BadGroupNameError:
return api_error(status.HTTP_400_BAD_REQUEST,
'Group name is not valid.')
except ConflictGroupNameError:
return api_error(status.HTTP_400_BAD_REQUEST,
'There is already a group with that name.')
return Response('success', status=status.HTTP_200_OK)
else:
return api_error(status.HTTP_400_BAD_REQUEST,
"Operation can only be rename.")
class GroupMembers(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def put(self, request, group_id, format=None):
"""
Add group members.
"""
try:
group_id_int = int(group_id)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid group ID')
group = get_group(group_id_int)
if not group:
return api_error(status.HTTP_404_NOT_FOUND, 'Group not found')
if not is_group_staff(group, request.user):
return api_error(status.HTTP_403_FORBIDDEN, 'Only administrators can add group members')
user_name = request.DATA.get('user_name', None)
if not is_registered_user(user_name):
return api_error(status.HTTP_400_BAD_REQUEST, 'Not a valid user')
try:
ccnet_threaded_rpc.group_add_member(group.id, request.user.username, user_name)
except SearpcError, e:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Unable to add user to group')
return HttpResponse(json.dumps({'success': True}), status=200, content_type=json_content_type)
def delete(self, request, group_id, format=None):
"""
Delete group members.
"""
try:
group_id_int = int(group_id)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid group ID')
group = get_group(group_id_int)
if not group:
return api_error(status.HTTP_404_NOT_FOUND, 'Group not found')
if not is_group_staff(group, request.user):
return api_error(status.HTTP_403_FORBIDDEN, 'Only administrators can remove group members')
user_name = request.DATA.get('user_name', None)
try:
ccnet_threaded_rpc.group_remove_member(group.id, request.user.username, user_name)
except SearpcError, e:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Unable to add user to group')
return HttpResponse(json.dumps({'success': True}), status=200, content_type=json_content_type)
class GroupChanges(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
@api_group_check
def get(self, request, group, format=None):
group_id = int(group.id)
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
repos = seaserv.get_org_group_repos(org_id, group_id, username)
else:
repos = seaserv.get_group_repos(group_id, username)
recent_commits = []
cmt_repo_dict = {}
for repo in repos:
repo.user_perm = check_permission(repo.props.id, username)
cmmts = get_commits(repo.props.id, 0, 10)
for c in cmmts:
cmt_repo_dict[c.id] = repo
recent_commits += cmmts
recent_commits.sort(lambda x, y: cmp(y.props.ctime, x.props.ctime))
recent_commits = recent_commits[:15]
for cmt in recent_commits:
cmt.repo = cmt_repo_dict[cmt.id]
cmt.repo.password_set = is_passwd_set(cmt.props.repo_id, username)
cmt.tp = cmt.props.desc.split(' ')[0]
res = []
for c in recent_commits:
cmt_tp = c.tp.lower()
if 'add' in cmt_tp:
change_tp = 'added'
elif ('delete' or 'remove') in cmt_tp:
change_tp = 'deleted'
else:
change_tp = 'modified'
change_repo = {
'id': c.repo.id,
'name': c.repo.name,
'desc': c.repo.desc,
'encrypted': c.repo.encrypted,
}
change = {
"type": change_tp,
"repo": change_repo,
"id": c.id,
"desc": c.desc,
"desc_human": translate_commit_desc(c.desc),
"ctime": c.ctime,
"ctime_human": translate_seahub_time(c.ctime),
"creator": c.creator_name,
"creator_nickname": email2nickname(c.creator_name)
}
res.append(change)
return Response(res)
class GroupRepos(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
@api_group_check
def post(self, request, group, format=None):
# add group repo
username = request.user.username
repo_name = request.DATA.get("name", None)
repo_desc = request.DATA.get("desc", '')
passwd = request.DATA.get("passwd", None)
# to avoid 'Bad magic' error when create repo, passwd should be 'None'
# not an empty string when create unencrypted repo
if not passwd:
passwd = None
if (passwd is not None) and (not config.ENABLE_ENCRYPTED_LIBRARY):
return api_error(status.HTTP_403_FORBIDDEN,
'NOT allow to create encrypted library.')
permission = request.DATA.get("permission", 'r')
if permission != 'r' and permission != 'rw':
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid permission')
if is_org_context(request):
org_id = request.user.org.org_id
repo_id = seafile_api.create_org_repo(repo_name, repo_desc,
username, passwd, org_id)
repo = seafile_api.get_repo(repo_id)
seafile_api.add_org_group_repo(repo_id, org_id, group.id,
username, permission)
else:
repo_id = seafile_api.create_repo(repo_name, repo_desc,
username, passwd)
repo = seafile_api.get_repo(repo_id)
seafile_api.set_group_repo(repo.id, group.id, username, permission)
group_repo = {
"id": repo.id,
"name": repo.name,
"desc": repo.desc,
"size": repo.size,
"size_formatted": filesizeformat(repo.size),
"mtime": repo.last_modified,
"mtime_relative": translate_seahub_time(repo.last_modified),
"encrypted": repo.encrypted,
"permission": permission,
"owner": username,
"owner_nickname": email2nickname(username),
"share_from_me": True,
}
return Response(group_repo, status=200)
@api_group_check
def get(self, request, group, format=None):
username = request.user.username
if group.is_pub:
if not request.user.is_staff and not is_group_user(group.id, username):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
if is_org_context(request):
org_id = request.user.org.org_id
repos = seafile_api.get_org_group_repos(org_id, group.id)
else:
repos = seafile_api.get_repos_by_group(group.id)
repos.sort(lambda x, y: cmp(y.last_modified, x.last_modified))
group.is_staff = is_group_staff(group, request.user)
repos_json = []
for r in repos:
repo = {
"id": r.id,
"name": r.name,
"desc": r.desc,
"size": r.size,
"size_formatted": filesizeformat(r.size),
"mtime": r.last_modified,
"mtime_relative": translate_seahub_time(r.last_modified),
"encrypted": r.encrypted,
"permission": r.permission,
"owner": r.user,
"owner_nickname": email2nickname(r.user),
"share_from_me": True if username == r.user else False,
}
repos_json.append(repo)
req_from = request.GET.get('from', "")
if req_from == 'web':
return Response({"is_staff": group.is_staff, "repos": repos_json})
else:
return Response(repos_json)
class GroupRepo(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
@api_group_check
def delete(self, request, group, repo_id, format=None):
username = request.user.username
group_id = group.id
if not group.is_staff and not seafile_api.is_repo_owner(username, repo_id):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
if seaserv.is_org_group(group_id):
org_id = seaserv.get_org_id_by_group(group_id)
seaserv.del_org_group_repo(repo_id, org_id, group_id)
else:
seafile_api.unset_group_repo(repo_id, group_id, username)
return HttpResponse(json.dumps({'success': True}), status=200,
content_type=json_content_type)
def is_group_staff(group, user):
if user.is_anonymous():
return False
return check_group_staff(group.id, user.username)
def get_page_index(request, default=1):
try:
page = int(request.GET.get('page', default))
except ValueError:
page = default
return page
class GroupMsgsView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
@api_group_check
def get(self, request, group, format=None):
username = request.user.username
page = get_page_index (request, 1)
msgs, next_page = get_group_msgs_json(group.id, page, username)
if not msgs:
msgs = []
# remove user notifications
UserNotification.objects.seen_group_msg_notices(username, group.id)
ret = {
'next_page' : next_page,
'msgs' : msgs,
}
return Response(ret)
@api_group_check
def post(self, request, group, format=None):
username = request.user.username
msg = request.POST.get('message')
message = GroupMessage()
message.group_id = group.id
message.from_email = request.user.username
message.message = msg
message.save()
# send signal
grpmsg_added.send(sender=GroupMessage, group_id=group.id,
from_email=username, message=msg)
repo_id = request.POST.get('repo_id', None)
path = request.POST.get('path', None)
if repo_id and path:
# save attachment
ma = MessageAttachment(group_message=message, repo_id=repo_id,
attach_type='file', path=path,
src='recommend')
ma.save()
# save discussion
fd = FileDiscuss(group_message=message, repo_id=repo_id, path=path)
fd.save()
ret = { "msgid" : message.id }
return Response(ret)
class GroupMsgView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
@api_group_check
def get(self, request, group, msg_id, format=None):
msg = get_group_message_json(group.id, msg_id, True)
if not msg:
return api_error(status.HTTP_404_NOT_FOUND, 'Message not found.')
UserNotification.objects.seen_group_msg_reply_notice(request.user.username, msg_id)
return Response(msg)
@api_group_check
def post(self, request, group, msg_id, format=None):
try:
group_msg = GroupMessage.objects.get(group_id=group.id, id=msg_id)
except GroupMessage.DoesNotExist:
return api_error(status.HTTP_404_NOT_FOUND, 'Message not found.')
msg = request.POST.get('message')
msg_reply = MessageReply()
msg_reply.reply_to = group_msg
msg_reply.from_email = request.user.username
msg_reply.message = msg
msg_reply.save()
grpmsg_reply_added.send(sender=MessageReply,
msg_id=msg_id,
from_email=request.user.username,
grpmsg_topic=group_msg.message,
reply_msg=msg)
ret = { "msgid" : msg_reply.id }
return Response(ret)
class UserMsgsView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, id_or_email, format=None):
username = request.user.username
to_email = get_email(id_or_email)
if not to_email:
return api_error(status.HTTP_404_NOT_FOUND, 'User not found.')
UserNotification.objects.seen_user_msg_notices(username, to_email)
UserMessage.objects.update_unread_messages(to_email, username)
page = get_page_index(request, 1)
next_page = -1
person_msgs = get_person_msgs(to_email, page, username)
if not person_msgs:
Response({
'to_email' : to_email,
'next_page' : next_page,
'msgs' : [],})
elif person_msgs.has_next():
next_page = person_msgs.next_page_number()
msgs = []
for msg in person_msgs.object_list:
atts = []
for att in msg.attachments:
atts.append({
'repo_id' : att.repo_id,
'path' : att.path,
})
m = {
'from_email' : msg.from_email,
'nickname' : email2nickname(msg.from_email),
'timestamp' : get_timestamp(msg.timestamp),
'msg' : msg.message,
'attachments' : atts,
'msgid' : msg.message_id,
}
msgs.append(m)
ret = {
'to_email' : to_email,
'next_page' : next_page,
'msgs' : msgs,
}
return Response(ret)
def post(self, request, id_or_email, format=None):
username = request.user.username
to_email = get_email(id_or_email)
if not to_email:
return api_error(status.HTTP_404_NOT_FOUND, 'User not found.')
mass_msg = request.POST.get('message')
if not mass_msg:
return api_error(status.HTTP_400_BAD_REQUEST, "Missing argument")
usermsg = UserMessage.objects.add_unread_message(username, to_email, mass_msg)
ret = { 'msgid' : usermsg.message_id }
return Response(ret)
class NewRepliesView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
notes = UserNotification.objects.get_user_notifications(request.user.username, seen=False)
grpmsg_reply_list = [ n.grpmsg_reply_detail_to_dict().get('msg_id') for n in notes if n.msg_type == 'grpmsg_reply']
group_msgs = []
for msg_id in grpmsg_reply_list:
msg = get_group_message_json (None, msg_id, True)
if msg:
group_msgs.append(msg)
# remove new group msg reply notification
UserNotification.objects.seen_group_msg_reply_notice(request.user.username)
return Response(group_msgs)
class UserAvatarView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, user, size, format=None):
url, is_default, date_uploaded = api_avatar_url(user, int(size))
ret = {
"url": request.build_absolute_uri(url),
"is_default": is_default,
"mtime": get_timestamp(date_uploaded) }
return Response(ret)
class GroupAvatarView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, group_id, size, format=None):
url, is_default, date_uploaded = api_grp_avatar_url(group_id, int(size))
ret = {
"url": request.build_absolute_uri(url),
"is_default": is_default,
"mtime": get_timestamp(date_uploaded)}
return Response(ret)
# Html related code
def html_events(request):
if not EVENTS_ENABLED:
events = None
return render_to_response('api2/events.html', {
"events":events,
}, context_instance=RequestContext(request))
email = request.user.username
start = 0
events_count = 15
if is_org_context(request):
org_id = request.user.org.org_id
events, events_more_offset = get_org_user_events(org_id, email,
start, events_count)
else:
events, events_more_offset = get_user_events(email, start,
events_count)
events_more = True if len(events) == events_count else False
event_groups = group_events_data(events)
prepare_events(event_groups)
return render_to_response('api2/events.html', {
"events": events,
"events_more_offset": events_more_offset,
"events_more": events_more,
"event_groups": event_groups,
"events_count": events_count,
}, context_instance=RequestContext(request))
def ajax_events(request):
events_count = 15
username = request.user.username
start = int(request.GET.get('start', 0))
events, start = get_user_events(username, start, events_count)
events_more = True if len(events) == events_count else False
event_groups = group_events_data(events)
prepare_events(event_groups)
ctx = {'event_groups': event_groups}
html = render_to_string("api2/events_body.html", ctx)
return HttpResponse(json.dumps({'html':html, 'events_more':events_more,
'new_start': start}),
content_type=json_content_type)
@group_check
def html_group_discussions(request, group):
username = request.user.username
if request.method == 'POST':
# only login user can post to public group
if group.view_perm == "pub" and not request.user.is_authenticated():
raise Http404
msg = request.POST.get('message')
message = GroupMessage()
message.group_id = group.id
message.from_email = request.user.username
message.message = msg
message.save()
# send signal
grpmsg_added.send(sender=GroupMessage, group_id=group.id,
from_email=username, message=msg)
repo_id = request.POST.get('repo_id', None)
path = request.POST.get('path', None)
if repo_id and path:
# save attachment
ma = MessageAttachment(group_message=message, repo_id=repo_id,
attach_type='file', path=path,
src='recommend')
ma.save()
# save discussion
fd = FileDiscuss(group_message=message, repo_id=repo_id, path=path)
fd.save()
ctx = {}
ctx['msg'] = message
html = render_to_string("api2/discussion_posted.html", ctx)
serialized_data = json.dumps({"html": html})
return HttpResponse(serialized_data, content_type=json_content_type)
group_msgs = get_group_msgs(group.id, page=1, username=request.user.username)
# remove user notifications
UserNotification.objects.seen_group_msg_notices(username, group.id)
return render_to_response("api2/discussions.html", {
"group" : group,
"group_msgs": group_msgs,
}, context_instance=RequestContext(request))
@group_check
def ajax_discussions(request, group):
try:
page = int(request.GET.get('page'))
except ValueError:
page = 2
group_msgs = get_group_msgs(group.id, page, request.user.username)
if group_msgs.has_next():
next_page = group_msgs.next_page_number()
else:
next_page = None
html = render_to_string('api2/discussions_body.html', {"group_msgs": group_msgs}, context_instance=RequestContext(request))
return HttpResponse(json.dumps({"html": html, 'next_page': next_page}), content_type=json_content_type)
def html_get_group_discussion(request, msg_id):
try:
msg = GroupMessage.objects.get(id=msg_id)
except GroupMessage.DoesNotExist:
raise Http404
try:
att = MessageAttachment.objects.get(group_message_id=msg_id)
except MessageAttachment.DoesNotExist:
att = None
if att:
path = att.path
if path == '/':
repo = get_repo(att.repo_id)
if repo:
att.name = repo.name
else:
att.err = 'the libray does not exist'
else:
path = path.rstrip('/') # cut out last '/' if possible
att.name = os.path.basename(path)
# Load to discuss page if attachment is a image and from recommend.
if att.attach_type == 'file' and att.src == 'recommend':
att.filetype, att.fileext = get_file_type_and_ext(att.name)
if att.filetype == IMAGE:
att.obj_id = get_file_id_by_path(att.repo_id, path)
if not att.obj_id:
att.err = 'File does not exist'
else:
att.token = seafile_api.get_fileserver_access_token(
att.repo_id, att.obj_id, 'view', request.user.username)
att.img_url = gen_file_get_url(att.token, att.name)
msg.attachment = att
msg.replies = MessageReply.objects.filter(reply_to=msg)
msg.reply_cnt = len(msg.replies)
return render_to_response("api2/discussion.html", {
"msg": msg,
}, context_instance=RequestContext(request))
def html_msg_reply(request, msg_id):
"""Show group message replies, and process message reply in ajax"""
ctx = {}
try:
group_msg = GroupMessage.objects.get(id=msg_id)
except GroupMessage.DoesNotExist:
raise Http404
msg = request.POST.get('message')
msg_reply = MessageReply()
msg_reply.reply_to = group_msg
msg_reply.from_email = request.user.username
msg_reply.message = msg
msg_reply.save()
grpmsg_reply_added.send(sender=MessageReply,
msg_id=msg_id,
from_email=request.user.username,
reply_msg=msg)
ctx['r'] = msg_reply
html = render_to_string("api2/reply.html", ctx)
serialized_data = json.dumps({"html": html})
return HttpResponse(serialized_data, content_type=json_content_type)
def html_user_messages(request, id_or_email):
to_email = get_email(id_or_email)
if not to_email:
return api_error(status.HTTP_404_NOT_FOUND, 'User not found.')
username = request.user.username
if request.method == 'POST':
mass_msg = request.POST.get('message')
if not mass_msg:
return api_error(status.HTTP_400_BAD_REQUEST, "Missing argument")
usermsg = UserMessage.objects.add_unread_message(username, to_email, mass_msg)
ctx = { 'msg' : usermsg }
html = render_to_string("api2/user_msg.html", ctx)
serialized_data = json.dumps({"html": html})
return HttpResponse(serialized_data, content_type=json_content_type)
UserNotification.objects.seen_user_msg_notices(username, to_email)
UserMessage.objects.update_unread_messages(to_email, username)
person_msgs = get_person_msgs(to_email, 1, username)
return render_to_response("api2/user_msg_list.html", {
"person_msgs": person_msgs,
"to_email": to_email,
}, context_instance=RequestContext(request))
def ajax_usermsgs(request, id_or_email):
try:
page = int(request.GET.get('page'))
except ValueError:
page = 2
to_email = get_email(id_or_email)
if not to_email:
return api_error(status.HTTP_404_NOT_FOUND, 'User not found.')
person_msgs = get_person_msgs(to_email, page, request.user.username)
if person_msgs.has_next():
next_page = person_msgs.next_page_number()
else:
next_page = None
html = render_to_string('api2/user_msg_body.html', {"person_msgs": person_msgs}, context_instance=RequestContext(request))
return HttpResponse(json.dumps({"html": html, 'next_page': next_page}), content_type=json_content_type)
def html_repo_history_changes(request, repo_id):
changes = {}
repo = get_repo(repo_id)
if not repo:
return HttpResponse(json.dumps({"err": 'Library does not exist'}), status=400, content_type=json_content_type)
resp = check_repo_access_permission(request, repo)
if resp:
return resp
if repo.encrypted and not is_passwd_set(repo_id, request.user.username):
return HttpResponse(json.dumps({"err": 'Library is encrypted'}), status=400, content_type=json_content_type)
commit_id = request.GET.get('commit_id', '')
if not commit_id:
return HttpResponse(json.dumps({"err": 'Invalid argument'}), status=400, content_type=json_content_type)
changes = get_diff(repo_id, '', commit_id)
c = get_commit(repo_id, repo.version, commit_id)
if c.parent_id is None:
# A commit is a first commit only if its parent id is None.
changes['cmt_desc'] = repo.desc
elif c.second_parent_id is None:
# Normal commit only has one parent.
if c.desc.startswith('Changed library'):
changes['cmt_desc'] = 'Changed library name or description'
else:
# A commit is a merge only if it has two parents.
changes['cmt_desc'] = 'No conflict in the merge.'
for k in changes:
changes[k] = [f.replace ('a href="/', 'a class="normal" href="api://') for f in changes[k] ]
html = render_to_string('api2/event_details.html', {'changes': changes})
return HttpResponse(json.dumps({"html": html}), content_type=json_content_type)
def html_new_replies(request):
notes = UserNotification.objects.get_user_notifications(request.user.username, seen=False)
grpmsg_reply_list = [ n.grpmsg_reply_detail_to_dict().get('msg_id') for n in notes if n.msg_type == 'grpmsg_reply']
group_msgs = []
for msg_id in grpmsg_reply_list:
try:
m = GroupMessage.objects.get(id=msg_id)
except GroupMessage.DoesNotExist:
continue
else:
# get group name
group = get_group(m.group_id)
if not group:
continue
m.group_name = group.group_name
# get attachement
attachment = get_first_object_or_none(m.messageattachment_set.all())
if attachment:
path = attachment.path
if path == '/':
repo = get_repo(attachment.repo_id)
if not repo:
continue
attachment.name = repo.name
else:
attachment.name = os.path.basename(path)
m.attachment = attachment
# get message replies
reply_list = MessageReply.objects.filter(reply_to=m)
m.reply_cnt = reply_list.count()
if m.reply_cnt > 3:
m.replies = reply_list[m.reply_cnt - 3:]
else:
m.replies = reply_list
group_msgs.append(m)
# remove new group msg reply notification
UserNotification.objects.seen_group_msg_reply_notice(request.user.username)
return render_to_response("api2/new_msg_reply.html", {
'group_msgs': group_msgs,
}, context_instance=RequestContext(request))
class AjaxEvents(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
return ajax_events(request)
class AjaxDiscussions(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, group_id, format=None):
return ajax_discussions(request, group_id)
class AjaxUserMsgs(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, id_or_email, format=None):
return ajax_usermsgs(request, id_or_email)
class EventsHtml(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
return html_events(request)
class NewReplyHtml(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
return html_new_replies(request)
class DiscussionsHtml(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, group_id, format=None):
return html_group_discussions(request, group_id)
def post(self, request, group_id, format=None):
return html_group_discussions(request, group_id)
class UserMsgsHtml(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, id_or_email, format=None):
return html_user_messages(request, id_or_email)
def post(self, request, id_or_email, format=None):
return html_user_messages(request, id_or_email)
class DiscussionHtml(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, msg_id, format=None):
return html_get_group_discussion(request, msg_id)
def post(self, request, msg_id, format=None):
return html_msg_reply(request, msg_id)
class RepoHistoryChange(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
repo = get_repo(repo_id)
if not repo:
return HttpResponse(json.dumps({"err": 'Library does not exist'}),
status=400,
content_type=json_content_type)
resp = check_repo_access_permission(request, repo)
if resp:
return resp
if repo.encrypted and not is_passwd_set(repo_id, request.user.username):
return HttpResponse(json.dumps({"err": 'Library is encrypted'}),
status=400,
content_type=json_content_type)
commit_id = request.GET.get('commit_id', '')
if not commit_id:
return HttpResponse(json.dumps({"err": 'Invalid argument'}),
status=400,
content_type=json_content_type)
details = get_diff_details(repo_id, '', commit_id)
return HttpResponse(json.dumps(details),
content_type=json_content_type)
class RepoHistoryChangeHtml(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
return html_repo_history_changes(request, repo_id)
# based on views/file.py::office_convert_query_status
class OfficeConvertQueryStatus(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
if not HAS_OFFICE_CONVERTER:
return api_error(status.HTTP_404_NOT_FOUND, 'Office converter not enabled.')
content_type = 'application/json; charset=utf-8'
ret = {'success': False}
file_id = request.GET.get('file_id', '')
if len(file_id) != 40:
ret['error'] = 'invalid param'
else:
try:
d = query_office_convert_status(file_id)
if d.error:
ret['error'] = d.error
else:
ret['success'] = True
ret['status'] = d.status
except Exception, e:
logging.exception('failed to call query_office_convert_status')
ret['error'] = str(e)
return HttpResponse(json.dumps(ret), content_type=content_type)
# based on views/file.py::view_file and views/file.py::handle_document
class OfficeGenerateView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated, )
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id, format=None):
username = request.user.username
# check arguments
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
path = request.GET.get('p', '/').rstrip('/')
commit_id = request.GET.get('commit_id', None)
if commit_id:
try:
obj_id = seafserv_threaded_rpc.get_file_id_by_commit_and_path(
repo.id, commit_id, path)
except:
return api_error(status.HTTP_404_NOT_FOUND, 'Revision not found.')
else:
try:
obj_id = seafile_api.get_file_id_by_path(repo_id,
path.encode('utf-8'))
except:
return api_error(status.HTTP_404_NOT_FOUND, 'File not found.')
if not obj_id:
return api_error(status.HTTP_404_NOT_FOUND, 'File not found.')
# Check whether user has permission to view file and get file raw path,
# render error page if permission deny.
raw_path, inner_path, user_perm = get_file_view_path_and_perm(request,
repo_id,
obj_id, path)
if not user_perm:
return api_error(status.HTTP_403_FORBIDDEN, 'You do not have permission to view this file.')
u_filename = os.path.basename(path)
filetype, fileext = get_file_type_and_ext(u_filename)
if filetype != DOCUMENT:
return api_error(status.HTTP_400_BAD_REQUEST, 'File is not a convertable document')
ret_dict = {}
if HAS_OFFICE_CONVERTER:
err = prepare_converted_html(inner_path, obj_id, fileext, ret_dict)
# populate return value dict
ret_dict['err'] = err
ret_dict['obj_id'] = obj_id
else:
ret_dict['filetype'] = 'Unknown'
return HttpResponse(json.dumps(ret_dict), status=200, content_type=json_content_type)
class ThumbnailView(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, repo_id):
repo = get_repo(repo_id)
if not repo:
return api_error(status.HTTP_404_NOT_FOUND, 'Library not found.')
size = request.GET.get('size', None)
if size is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Size is missing.')
try:
size = int(size)
except ValueError as e:
logger.error(e)
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid size.')
path = request.GET.get('p', None)
obj_id = get_file_id_by_path(repo_id, path)
if path is None or obj_id is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Wrong path.')
if repo.encrypted or not ENABLE_THUMBNAIL or \
check_folder_permission(request, repo_id, path) is None:
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
success, status_code = generate_thumbnail(request, repo_id, size, path)
if success:
thumbnail_dir = os.path.join(THUMBNAIL_ROOT, str(size))
thumbnail_file = os.path.join(thumbnail_dir, obj_id)
try:
with open(thumbnail_file, 'rb') as f:
thumbnail = f.read()
return HttpResponse(thumbnail, 'image/' + THUMBNAIL_EXTENSION)
except IOError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Failed to get thumbnail.')
else:
if status_code == 400:
return api_error(status.HTTP_400_BAD_REQUEST, "Invalid argument")
if status_code == 403:
return api_error(status.HTTP_403_FORBIDDEN, 'Forbidden')
if status_code == 500:
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Failed to generate thumbnail.')
_REPO_ID_PATTERN = re.compile(r'[-0-9a-f]{36}')
class RepoTokensView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
@json_response
def get(self, request, format=None):
repos = request.GET.get('repos', None)
if not repos:
return api_error(status.HTTP_400_BAD_REQUEST, "You must specify libaries ids")
repos = [repo for repo in repos.split(',') if repo]
if any([not _REPO_ID_PATTERN.match(repo) for repo in repos]):
return api_error(status.HTTP_400_BAD_REQUEST, "Libraries ids are invalid")
tokens = {}
for repo in repos:
if not seafile_api.check_repo_access_permission(repo, request.user.username):
continue
tokens[repo] = seafile_api.generate_repo_token(repo, request.user.username)
return tokens
class OrganizationView(APIView):
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAdminUser, )
throttle_classes = (UserRateThrottle, )
def post(self, request, format=None):
if not CLOUD_MODE or not MULTI_TENANCY:
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied')
username = request.POST.get('username', None)
password = request.POST.get('password', None)
org_name = request.POST.get('org_name', None)
prefix = request.POST.get('prefix', None)
quota = request.POST.get('quota', None)
member_limit = request.POST.get('member_limit', ORG_MEMBER_QUOTA_DEFAULT)
if not org_name or not username or not password or \
not prefix or not quota or not member_limit:
return api_error(status.HTTP_400_BAD_REQUEST, "Missing argument")
if not is_valid_username(username):
return api_error(status.HTTP_400_BAD_REQUEST, "Email is not valid")
try:
quota_mb = int(quota)
except ValueError as e:
logger.error(e)
return api_error(status.HTTP_400_BAD_REQUEST, "Quota is not valid")
try:
User.objects.get(email = username)
user_exist = True
except User.DoesNotExist:
user_exist = False
if user_exist:
return api_error(status.HTTP_400_BAD_REQUEST, "A user with this email already exists")
slug_re = re.compile(r'^[-a-zA-Z0-9_]+$')
if not slug_re.match(prefix):
return api_error(status.HTTP_400_BAD_REQUEST, "URL prefix can only be letters(a-z), numbers, and the underscore character")
if ccnet_threaded_rpc.get_org_by_url_prefix(prefix):
return api_error(status.HTTP_400_BAD_REQUEST, "An organization with this prefix already exists")
try:
User.objects.create_user(username, password, is_staff=False, is_active=True)
create_org(org_name, prefix, username)
new_org = ccnet_threaded_rpc.get_org_by_url_prefix(prefix)
# set member limit
from seahub_extra.organizations.models import OrgMemberQuota
OrgMemberQuota.objects.set_quota(new_org.org_id, member_limit)
# set quota
quota = quota_mb * get_file_size_unit('MB')
seafserv_threaded_rpc.set_org_quota(new_org.org_id, quota)
return Response('success', status=status.HTTP_201_CREATED)
except Exception as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, "Internal error")
#Following is only for debug
# from seahub.auth.decorators import login_required
# @login_required
# def activity2(request):
# return html_events(request)
# @login_required
# def discussions2(request, group_id):
# return html_group_discussions(request, group_id)
# @login_required
# def more_discussions2(request, group_id):
# return ajax_discussions(request, group_id)
# @login_required
# def discussion2(request, msg_id):
# return html_get_group_discussion(request, msg_id)
# @login_required
# def events2(request):
# return ajax_events(request)
# @login_required
# def api_repo_history_changes(request, repo_id):
# return html_repo_history_changes(request, repo_id)
# @login_required
# def api_msg_reply(request, msg_id):
# return html_msg_reply(request, msg_id)
# @login_required
# def api_new_replies(request):
# return html_new_replies(request)
# @login_required
# def api_usermsgs(request, id_or_email):
# return html_user_messages(request, id_or_email)
# @login_required
# def api_more_usermsgs(request, id_or_email):
# return ajax_usermsgs(request, id_or_email)
<file_sep>/thirdpart/rest_framework/fields.py
import copy
import datetime
import inspect
import re
import warnings
from io import BytesIO
from django.core import validators
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.urlresolvers import resolve, get_script_prefix
from django.conf import settings
from django.forms import widgets
from django.forms.models import ModelChoiceIterator
from django.utils.encoding import is_protected_type, smart_unicode
from django.utils.translation import ugettext_lazy as _
from rest_framework.reverse import reverse
from rest_framework.compat import parse_date, parse_datetime
from rest_framework.compat import timezone
from urlparse import urlparse
def is_simple_callable(obj):
"""
True if the object is a callable that takes no arguments.
"""
return (
(inspect.isfunction(obj) and not inspect.getargspec(obj)[0]) or
(inspect.ismethod(obj) and len(inspect.getargspec(obj)[0]) <= 1)
)
class Field(object):
creation_counter = 0
empty = ''
type_name = None
_use_files = None
def __init__(self, source=None):
self.parent = None
self.creation_counter = Field.creation_counter
Field.creation_counter += 1
self.source = source
def initialize(self, parent, field_name):
"""
Called to set up a field prior to field_to_native or field_from_native.
parent - The parent serializer.
model_field - The model field this field corresponds to, if one exists.
"""
self.parent = parent
self.root = parent.root or parent
self.context = self.root.context
if self.root.partial:
self.required = False
def field_from_native(self, data, files, field_name, into):
"""
Given a dictionary and a field name, updates the dictionary `into`,
with the field and it's deserialized value.
"""
return
def field_to_native(self, obj, field_name):
"""
Given and object and a field name, returns the value that should be
serialized for that field.
"""
if obj is None:
return self.empty
if self.source == '*':
return self.to_native(obj)
if self.source:
value = obj
for component in self.source.split('.'):
value = getattr(value, component)
if is_simple_callable(value):
value = value()
else:
value = getattr(obj, field_name)
return self.to_native(value)
def to_native(self, value):
"""
Converts the field's value into it's simple representation.
"""
if is_simple_callable(value):
value = value()
if is_protected_type(value):
return value
elif hasattr(value, '__iter__') and not isinstance(value, (dict, basestring)):
return [self.to_native(item) for item in value]
elif isinstance(value, dict):
return dict(map(self.to_native, (k, v)) for k, v in value.items())
return smart_unicode(value)
def attributes(self):
"""
Returns a dictionary of attributes to be used when serializing to xml.
"""
if self.type_name:
return {'type': self.type_name}
return {}
class WritableField(Field):
"""
Base for read/write fields.
"""
default_validators = []
default_error_messages = {
'required': _('This field is required.'),
'invalid': _('Invalid value.'),
}
widget = widgets.TextInput
default = None
def __init__(self, source=None, read_only=False, required=None,
validators=[], error_messages=None, widget=None,
default=None, blank=None):
super(WritableField, self).__init__(source=source)
self.read_only = read_only
if required is None:
self.required = not(read_only)
else:
assert not read_only, "Cannot set required=True and read_only=True"
self.required = required
messages = {}
for c in reversed(self.__class__.__mro__):
messages.update(getattr(c, 'default_error_messages', {}))
messages.update(error_messages or {})
self.error_messages = messages
self.validators = self.default_validators + validators
self.default = default if default is not None else self.default
self.blank = blank
# Widgets are ony used for HTML forms.
widget = widget or self.widget
if isinstance(widget, type):
widget = widget()
self.widget = widget
def validate(self, value):
if value in validators.EMPTY_VALUES and self.required:
raise ValidationError(self.error_messages['required'])
def run_validators(self, value):
if value in validators.EMPTY_VALUES:
return
errors = []
for v in self.validators:
try:
v(value)
except ValidationError as e:
if hasattr(e, 'code') and e.code in self.error_messages:
message = self.error_messages[e.code]
if e.params:
message = message % e.params
errors.append(message)
else:
errors.extend(e.messages)
if errors:
raise ValidationError(errors)
def field_from_native(self, data, files, field_name, into):
"""
Given a dictionary and a field name, updates the dictionary `into`,
with the field and it's deserialized value.
"""
if self.read_only:
return
try:
if self._use_files:
native = files[field_name]
else:
native = data[field_name]
except KeyError:
if self.default is not None:
native = self.default
else:
if self.required:
raise ValidationError(self.error_messages['required'])
return
value = self.from_native(native)
if self.source == '*':
if value:
into.update(value)
else:
self.validate(value)
self.run_validators(value)
into[self.source or field_name] = value
def from_native(self, value):
"""
Reverts a simple representation back to the field's value.
"""
return value
class ModelField(WritableField):
"""
A generic field that can be used against an arbitrary model field.
"""
def __init__(self, *args, **kwargs):
try:
self.model_field = kwargs.pop('model_field')
except:
raise ValueError("ModelField requires 'model_field' kwarg")
self.min_length = kwargs.pop('min_length',
getattr(self.model_field, 'min_length', None))
self.max_length = kwargs.pop('max_length',
getattr(self.model_field, 'max_length', None))
super(ModelField, self).__init__(*args, **kwargs)
if self.min_length is not None:
self.validators.append(validators.MinLengthValidator(self.min_length))
if self.max_length is not None:
self.validators.append(validators.MaxLengthValidator(self.max_length))
def from_native(self, value):
rel = getattr(self.model_field, "rel", None)
if rel is not None:
return rel.to._meta.get_field(rel.field_name).to_python(value)
else:
return self.model_field.to_python(value)
def field_to_native(self, obj, field_name):
value = self.model_field._get_val_from_obj(obj)
if is_protected_type(value):
return value
return self.model_field.value_to_string(obj)
def attributes(self):
return {
"type": self.model_field.get_internal_type()
}
##### Relational fields #####
# Not actually Writable, but subclasses may need to be.
class RelatedField(WritableField):
"""
Base class for related model fields.
If not overridden, this represents a to-one relationship, using the unicode
representation of the target.
"""
widget = widgets.Select
cache_choices = False
empty_label = None
default_read_only = True # TODO: Remove this
def __init__(self, *args, **kwargs):
self.queryset = kwargs.pop('queryset', None)
super(RelatedField, self).__init__(*args, **kwargs)
self.read_only = kwargs.pop('read_only', self.default_read_only)
def initialize(self, parent, field_name):
super(RelatedField, self).initialize(parent, field_name)
if self.queryset is None and not self.read_only:
try:
manager = getattr(self.parent.opts.model, self.source or field_name)
if hasattr(manager, 'related'): # Forward
self.queryset = manager.related.model._default_manager.all()
else: # Reverse
self.queryset = manager.field.rel.to._default_manager.all()
except:
raise
msg = ('Serializer related fields must include a `queryset`' +
' argument or set `read_only=True')
raise Exception(msg)
### We need this stuff to make form choices work...
# def __deepcopy__(self, memo):
# result = super(RelatedField, self).__deepcopy__(memo)
# result.queryset = result.queryset
# return result
def prepare_value(self, obj):
return self.to_native(obj)
def label_from_instance(self, obj):
"""
Return a readable representation for use with eg. select widgets.
"""
desc = smart_unicode(obj)
ident = smart_unicode(self.to_native(obj))
if desc == ident:
return desc
return "%s - %s" % (desc, ident)
def _get_queryset(self):
return self._queryset
def _set_queryset(self, queryset):
self._queryset = queryset
self.widget.choices = self.choices
queryset = property(_get_queryset, _set_queryset)
def _get_choices(self):
# If self._choices is set, then somebody must have manually set
# the property self.choices. In this case, just return self._choices.
if hasattr(self, '_choices'):
return self._choices
# Otherwise, execute the QuerySet in self.queryset to determine the
# choices dynamically. Return a fresh ModelChoiceIterator that has not been
# consumed. Note that we're instantiating a new ModelChoiceIterator *each*
# time _get_choices() is called (and, thus, each time self.choices is
# accessed) so that we can ensure the QuerySet has not been consumed. This
# construct might look complicated but it allows for lazy evaluation of
# the queryset.
return ModelChoiceIterator(self)
def _set_choices(self, value):
# Setting choices also sets the choices on the widget.
# choices can be any iterable, but we call list() on it because
# it will be consumed more than once.
self._choices = self.widget.choices = list(value)
choices = property(_get_choices, _set_choices)
### Regular serializer stuff...
def field_to_native(self, obj, field_name):
value = getattr(obj, self.source or field_name)
return self.to_native(value)
def field_from_native(self, data, files, field_name, into):
if self.read_only:
return
value = data.get(field_name)
into[(self.source or field_name)] = self.from_native(value)
class ManyRelatedMixin(object):
"""
Mixin to convert a related field to a many related field.
"""
widget = widgets.SelectMultiple
def field_to_native(self, obj, field_name):
value = getattr(obj, self.source or field_name)
return [self.to_native(item) for item in value.all()]
def field_from_native(self, data, files, field_name, into):
if self.read_only:
return
try:
# Form data
value = data.getlist(self.source or field_name)
except:
# Non-form data
value = data.get(self.source or field_name)
else:
if value == ['']:
value = []
into[field_name] = [self.from_native(item) for item in value]
class ManyRelatedField(ManyRelatedMixin, RelatedField):
"""
Base class for related model managers.
If not overridden, this represents a to-many relationship, using the unicode
representations of the target, and is read-only.
"""
pass
### PrimaryKey relationships
class PrimaryKeyRelatedField(RelatedField):
"""
Represents a to-one relationship as a pk value.
"""
default_read_only = False
# TODO: Remove these field hacks...
def prepare_value(self, obj):
return self.to_native(obj.pk)
def label_from_instance(self, obj):
"""
Return a readable representation for use with eg. select widgets.
"""
desc = smart_unicode(obj)
ident = smart_unicode(self.to_native(obj.pk))
if desc == ident:
return desc
return "%s - %s" % (desc, ident)
# TODO: Possibly change this to just take `obj`, through prob less performant
def to_native(self, pk):
return pk
def from_native(self, data):
if self.queryset is None:
raise Exception('Writable related fields must include a `queryset` argument')
try:
return self.queryset.get(pk=data)
except ObjectDoesNotExist:
msg = "Invalid pk '%s' - object does not exist." % smart_unicode(data)
raise ValidationError(msg)
def field_to_native(self, obj, field_name):
try:
# Prefer obj.serializable_value for performance reasons
pk = obj.serializable_value(self.source or field_name)
except AttributeError:
# RelatedObject (reverse relationship)
obj = getattr(obj, self.source or field_name)
return self.to_native(obj.pk)
# Forward relationship
return self.to_native(pk)
class ManyPrimaryKeyRelatedField(ManyRelatedField):
"""
Represents a to-many relationship as a pk value.
"""
default_read_only = False
def prepare_value(self, obj):
return self.to_native(obj.pk)
def label_from_instance(self, obj):
"""
Return a readable representation for use with eg. select widgets.
"""
desc = smart_unicode(obj)
ident = smart_unicode(self.to_native(obj.pk))
if desc == ident:
return desc
return "%s - %s" % (desc, ident)
def to_native(self, pk):
return pk
def field_to_native(self, obj, field_name):
try:
# Prefer obj.serializable_value for performance reasons
queryset = obj.serializable_value(self.source or field_name)
except AttributeError:
# RelatedManager (reverse relationship)
queryset = getattr(obj, self.source or field_name)
return [self.to_native(item.pk) for item in queryset.all()]
# Forward relationship
return [self.to_native(item.pk) for item in queryset.all()]
def from_native(self, data):
if self.queryset is None:
raise Exception('Writable related fields must include a `queryset` argument')
try:
return self.queryset.get(pk=data)
except ObjectDoesNotExist:
msg = "Invalid pk '%s' - object does not exist." % smart_unicode(data)
raise ValidationError(msg)
### Slug relationships
class SlugRelatedField(RelatedField):
default_read_only = False
def __init__(self, *args, **kwargs):
self.slug_field = kwargs.pop('slug_field', None)
assert self.slug_field, 'slug_field is required'
super(SlugRelatedField, self).__init__(*args, **kwargs)
def to_native(self, obj):
return getattr(obj, self.slug_field)
def from_native(self, data):
if self.queryset is None:
raise Exception('Writable related fields must include a `queryset` argument')
try:
return self.queryset.get(**{self.slug_field: data})
except ObjectDoesNotExist:
raise ValidationError('Object with %s=%s does not exist.' %
(self.slug_field, unicode(data)))
class ManySlugRelatedField(ManyRelatedMixin, SlugRelatedField):
pass
### Hyperlinked relationships
class HyperlinkedRelatedField(RelatedField):
"""
Represents a to-one relationship, using hyperlinking.
"""
pk_url_kwarg = 'pk'
slug_field = 'slug'
slug_url_kwarg = None # Defaults to same as `slug_field` unless overridden
default_read_only = False
def __init__(self, *args, **kwargs):
try:
self.view_name = kwargs.pop('view_name')
except:
raise ValueError("Hyperlinked field requires 'view_name' kwarg")
self.slug_field = kwargs.pop('slug_field', self.slug_field)
default_slug_kwarg = self.slug_url_kwarg or self.slug_field
self.pk_url_kwarg = kwargs.pop('pk_url_kwarg', self.pk_url_kwarg)
self.slug_url_kwarg = kwargs.pop('slug_url_kwarg', default_slug_kwarg)
self.format = kwargs.pop('format', None)
super(HyperlinkedRelatedField, self).__init__(*args, **kwargs)
def get_slug_field(self):
"""
Get the name of a slug field to be used to look up by slug.
"""
return self.slug_field
def to_native(self, obj):
view_name = self.view_name
request = self.context.get('request', None)
format = self.format or self.context.get('format', None)
pk = getattr(obj, 'pk', None)
if pk is None:
return
kwargs = {self.pk_url_kwarg: pk}
try:
return reverse(view_name, kwargs=kwargs, request=request, format=format)
except:
pass
slug = getattr(obj, self.slug_field, None)
if not slug:
raise ValidationError('Could not resolve URL for field using view name "%s"' % view_name)
kwargs = {self.slug_url_kwarg: slug}
try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format)
except:
pass
kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug}
try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format)
except:
pass
raise ValidationError('Could not resolve URL for field using view name "%s"', view_name)
def from_native(self, value):
# Convert URL -> model instance pk
# TODO: Use values_list
if self.queryset is None:
raise Exception('Writable related fields must include a `queryset` argument')
if value.startswith('http:') or value.startswith('https:'):
# If needed convert absolute URLs to relative path
value = urlparse(value).path
prefix = get_script_prefix()
if value.startswith(prefix):
value = '/' + value[len(prefix):]
try:
match = resolve(value)
except:
raise ValidationError('Invalid hyperlink - No URL match')
if match.url_name != self.view_name:
raise ValidationError('Invalid hyperlink - Incorrect URL match')
pk = match.kwargs.get(self.pk_url_kwarg, None)
slug = match.kwargs.get(self.slug_url_kwarg, None)
# Try explicit primary key.
if pk is not None:
queryset = self.queryset.filter(pk=pk)
# Next, try looking up by slug.
elif slug is not None:
slug_field = self.get_slug_field()
queryset = self.queryset.filter(**{slug_field: slug})
# If none of those are defined, it's an error.
else:
raise ValidationError('Invalid hyperlink')
try:
obj = queryset.get()
except ObjectDoesNotExist:
raise ValidationError('Invalid hyperlink - object does not exist.')
return obj
class ManyHyperlinkedRelatedField(ManyRelatedMixin, HyperlinkedRelatedField):
"""
Represents a to-many relationship, using hyperlinking.
"""
pass
class HyperlinkedIdentityField(Field):
"""
Represents the instance, or a property on the instance, using hyperlinking.
"""
pk_url_kwarg = 'pk'
slug_field = 'slug'
slug_url_kwarg = None # Defaults to same as `slug_field` unless overridden
def __init__(self, *args, **kwargs):
# TODO: Make view_name mandatory, and have the
# HyperlinkedModelSerializer set it on-the-fly
self.view_name = kwargs.pop('view_name', None)
self.format = kwargs.pop('format', None)
self.slug_field = kwargs.pop('slug_field', self.slug_field)
default_slug_kwarg = self.slug_url_kwarg or self.slug_field
self.pk_url_kwarg = kwargs.pop('pk_url_kwarg', self.pk_url_kwarg)
self.slug_url_kwarg = kwargs.pop('slug_url_kwarg', default_slug_kwarg)
super(HyperlinkedIdentityField, self).__init__(*args, **kwargs)
def field_to_native(self, obj, field_name):
request = self.context.get('request', None)
format = self.format or self.context.get('format', None)
view_name = self.view_name or self.parent.opts.view_name
kwargs = {self.pk_url_kwarg: obj.pk}
try:
return reverse(view_name, kwargs=kwargs, request=request, format=format)
except:
pass
slug = getattr(obj, self.slug_field, None)
if not slug:
raise ValidationError('Could not resolve URL for field using view name "%s"' % view_name)
kwargs = {self.slug_url_kwarg: slug}
try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format)
except:
pass
kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug}
try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format)
except:
pass
raise ValidationError('Could not resolve URL for field using view name "%s"', view_name)
##### Typed Fields #####
class BooleanField(WritableField):
type_name = 'BooleanField'
widget = widgets.CheckboxInput
default_error_messages = {
'invalid': _(u"'%s' value must be either True or False."),
}
empty = False
# Note: we set default to `False` in order to fill in missing value not
# supplied by html form. TODO: Fix so that only html form input gets
# this behavior.
default = False
def from_native(self, value):
if value in ('t', 'True', '1'):
return True
if value in ('f', 'False', '0'):
return False
return bool(value)
class CharField(WritableField):
type_name = 'CharField'
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
self.max_length, self.min_length = max_length, min_length
super(CharField, self).__init__(*args, **kwargs)
if min_length is not None:
self.validators.append(validators.MinLengthValidator(min_length))
if max_length is not None:
self.validators.append(validators.MaxLengthValidator(max_length))
def validate(self, value):
"""
Validates that the value is supplied (if required).
"""
# if empty string and allow blank
if self.blank and not value:
return
else:
super(CharField, self).validate(value)
def from_native(self, value):
if isinstance(value, basestring) or value is None:
return value
return smart_unicode(value)
class URLField(CharField):
type_name = 'URLField'
def __init__(self, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 200)
kwargs['validators'] = [validators.URLValidator()]
super(URLField, self).__init__(**kwargs)
class SlugField(CharField):
type_name = 'SlugField'
def __init__(self, *args, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 50)
super(SlugField, self).__init__(*args, **kwargs)
class ChoiceField(WritableField):
type_name = 'ChoiceField'
widget = widgets.Select
default_error_messages = {
'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
}
def __init__(self, choices=(), *args, **kwargs):
super(ChoiceField, self).__init__(*args, **kwargs)
self.choices = choices
def _get_choices(self):
return self._choices
def _set_choices(self, value):
# Setting choices also sets the choices on the widget.
# choices can be any iterable, but we call list() on it because
# it will be consumed more than once.
self._choices = self.widget.choices = list(value)
choices = property(_get_choices, _set_choices)
def validate(self, value):
"""
Validates that the input is in self.choices.
"""
super(ChoiceField, self).validate(value)
if value and not self.valid_value(value):
raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
def valid_value(self, value):
"""
Check to see if the provided value is a valid choice.
"""
for k, v in self.choices:
if isinstance(v, (list, tuple)):
# This is an optgroup, so look inside the group for options
for k2, v2 in v:
if value == smart_unicode(k2):
return True
else:
if value == smart_unicode(k):
return True
return False
class EmailField(CharField):
type_name = 'EmailField'
default_error_messages = {
'invalid': _('Enter a valid e-mail address.'),
}
default_validators = [validators.validate_email]
def from_native(self, value):
ret = super(EmailField, self).from_native(value)
if ret is None:
return None
return ret.strip()
def __deepcopy__(self, memo):
result = copy.copy(self)
memo[id(self)] = result
#result.widget = copy.deepcopy(self.widget, memo)
result.validators = self.validators[:]
return result
class RegexField(CharField):
type_name = 'RegexField'
def __init__(self, regex, max_length=None, min_length=None, *args, **kwargs):
super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
self.regex = regex
def _get_regex(self):
return self._regex
def _set_regex(self, regex):
if isinstance(regex, basestring):
regex = re.compile(regex)
self._regex = regex
if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
self.validators.remove(self._regex_validator)
self._regex_validator = validators.RegexValidator(regex=regex)
self.validators.append(self._regex_validator)
regex = property(_get_regex, _set_regex)
def __deepcopy__(self, memo):
result = copy.copy(self)
memo[id(self)] = result
result.validators = self.validators[:]
return result
class DateField(WritableField):
type_name = 'DateField'
widget = widgets.DateInput
default_error_messages = {
'invalid': _(u"'%s' value has an invalid date format. It must be "
u"in YYYY-MM-DD format."),
'invalid_date': _(u"'%s' value has the correct format (YYYY-MM-DD) "
u"but it is an invalid date."),
}
empty = None
def from_native(self, value):
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
if timezone and settings.USE_TZ and timezone.is_aware(value):
# Convert aware datetimes to the default time zone
# before casting them to dates (#17742).
default_timezone = timezone.get_default_timezone()
value = timezone.make_naive(value, default_timezone)
return value.date()
if isinstance(value, datetime.date):
return value
try:
parsed = parse_date(value)
if parsed is not None:
return parsed
except ValueError:
msg = self.error_messages['invalid_date'] % value
raise ValidationError(msg)
msg = self.error_messages['invalid'] % value
raise ValidationError(msg)
class DateTimeField(WritableField):
type_name = 'DateTimeField'
widget = widgets.DateTimeInput
default_error_messages = {
'invalid': _(u"'%s' value has an invalid format. It must be in "
u"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."),
'invalid_date': _(u"'%s' value has the correct format "
u"(YYYY-MM-DD) but it is an invalid date."),
'invalid_datetime': _(u"'%s' value has the correct format "
u"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
u"but it is an invalid date/time."),
}
empty = None
def from_native(self, value):
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
value = datetime.datetime(value.year, value.month, value.day)
if settings.USE_TZ:
# For backwards compatibility, interpret naive datetimes in
# local time. This won't work during DST change, but we can't
# do much about it, so we let the exceptions percolate up the
# call stack.
warnings.warn(u"DateTimeField received a naive datetime (%s)"
u" while time zone support is active." % value,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
return value
try:
parsed = parse_datetime(value)
if parsed is not None:
return parsed
except ValueError:
msg = self.error_messages['invalid_datetime'] % value
raise ValidationError(msg)
try:
parsed = parse_date(value)
if parsed is not None:
return datetime.datetime(parsed.year, parsed.month, parsed.day)
except ValueError:
msg = self.error_messages['invalid_date'] % value
raise ValidationError(msg)
msg = self.error_messages['invalid'] % value
raise ValidationError(msg)
class IntegerField(WritableField):
type_name = 'IntegerField'
default_error_messages = {
'invalid': _('Enter a whole number.'),
'max_value': _('Ensure this value is less than or equal to %(limit_value)s.'),
'min_value': _('Ensure this value is greater than or equal to %(limit_value)s.'),
}
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
self.max_value, self.min_value = max_value, min_value
super(IntegerField, self).__init__(*args, **kwargs)
if max_value is not None:
self.validators.append(validators.MaxValueValidator(max_value))
if min_value is not None:
self.validators.append(validators.MinValueValidator(min_value))
def from_native(self, value):
if value in validators.EMPTY_VALUES:
return None
try:
value = int(str(value))
except (ValueError, TypeError):
raise ValidationError(self.error_messages['invalid'])
return value
class FloatField(WritableField):
type_name = 'FloatField'
default_error_messages = {
'invalid': _("'%s' value must be a float."),
}
def from_native(self, value):
if value in validators.EMPTY_VALUES:
return None
try:
return float(value)
except (TypeError, ValueError):
msg = self.error_messages['invalid'] % value
raise ValidationError(msg)
class FileField(WritableField):
_use_files = True
type_name = 'FileField'
widget = widgets.FileInput
default_error_messages = {
'invalid': _("No file was submitted. Check the encoding type on the form."),
'missing': _("No file was submitted."),
'empty': _("The submitted file is empty."),
'max_length': _('Ensure this filename has at most %(max)d characters (it has %(length)d).'),
'contradiction': _('Please either submit a file or check the clear checkbox, not both.')
}
def __init__(self, *args, **kwargs):
self.max_length = kwargs.pop('max_length', None)
self.allow_empty_file = kwargs.pop('allow_empty_file', False)
super(FileField, self).__init__(*args, **kwargs)
def from_native(self, data):
if data in validators.EMPTY_VALUES:
return None
# UploadedFile objects should have name and size attributes.
try:
file_name = data.name
file_size = data.size
except AttributeError:
raise ValidationError(self.error_messages['invalid'])
if self.max_length is not None and len(file_name) > self.max_length:
error_values = {'max': self.max_length, 'length': len(file_name)}
raise ValidationError(self.error_messages['max_length'] % error_values)
if not file_name:
raise ValidationError(self.error_messages['invalid'])
if not self.allow_empty_file and not file_size:
raise ValidationError(self.error_messages['empty'])
return data
def to_native(self, value):
return value.name
class ImageField(FileField):
_use_files = True
default_error_messages = {
'invalid_image': _("Upload a valid image. The file you uploaded was either not an image or a corrupted image."),
}
def from_native(self, data):
"""
Checks that the file-upload field data contains a valid image (GIF, JPG,
PNG, possibly others -- whatever the Python Imaging Library supports).
"""
f = super(ImageField, self).from_native(data)
if f is None:
return None
# Try to import PIL in either of the two ways it can end up installed.
try:
from PIL import Image
except ImportError:
import Image
# We need to get a file object for PIL. We might have a path or we might
# have to read the data into memory.
if hasattr(data, 'temporary_file_path'):
file = data.temporary_file_path()
else:
if hasattr(data, 'read'):
file = BytesIO(data.read())
else:
file = BytesIO(data['content'])
try:
# load() could spot a truncated JPEG, but it loads the entire
# image in memory, which is a DoS vector. See #3848 and #18520.
# verify() must be called immediately after the constructor.
Image.open(file).verify()
except ImportError:
# Under PyPy, it is possible to import PIL. However, the underlying
# _imaging C module isn't available, so an ImportError will be
# raised. Catch and re-raise.
raise
except Exception: # Python Imaging Library doesn't recognize it as an image
raise ValidationError(self.error_messages['invalid_image'])
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)
return f
class SerializerMethodField(Field):
"""
A field that gets its value by calling a method on the serializer it's attached to.
"""
def __init__(self, method_name):
self.method_name = method_name
super(SerializerMethodField, self).__init__()
def field_to_native(self, obj, field_name):
value = getattr(self.parent, self.method_name)(obj)
return self.to_native(value)
<file_sep>/seahub/utils/timeutils.py
import datetime
from django.conf import settings
from django.utils import six
from django.utils import timezone
def dt(value):
"""Convert 32/64 bits timestamp to datetime object.
"""
try:
return datetime.datetime.utcfromtimestamp(value)
except ValueError:
# TODO: need a better way to handle 64 bits timestamp.
return datetime.datetime.utcfromtimestamp(value/1000000)
def value_to_db_datetime(value):
if value is None:
return None
# MySQL doesn't support tz-aware datetimes
if timezone.is_aware(value):
if settings.USE_TZ:
value = value.astimezone(timezone.utc).replace(tzinfo=None)
else:
raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")
# MySQL doesn't support microseconds
return six.text_type(value.replace(microsecond=0))
def utc_to_local(dt):
# change from UTC timezone to current seahub timezone
tz = timezone.get_default_timezone()
utc = dt.replace(tzinfo=timezone.utc)
local = timezone.make_naive(utc, tz)
return local
<file_sep>/seahub/api2/endpoints/shared_upload_links.py
import json
import os
from django.http import HttpResponse
from django.utils.dateformat import DateFormat
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
from seaserv import seafile_api
from seahub.api2.authentication import TokenAuthentication
from seahub.share.models import UploadLinkShare
from seahub.utils import gen_shared_upload_link
json_content_type = 'application/json; charset=utf-8'
class SharedUploadLinksView(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication )
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def get(self, request, format=None):
username = request.user.username
uploadlinks = UploadLinkShare.objects.filter(username=username)
p_uploadlinks = []
for link in uploadlinks:
r = seafile_api.get_repo(link.repo_id)
if not r:
link.delete()
continue
if seafile_api.get_dir_id_by_path(r.id, link.path) is None:
link.delete()
continue
if link.path != '/':
link.dir_name = os.path.basename(link.path.rstrip('/'))
else:
link.dir_name = link.path
link.shared_link = gen_shared_upload_link(link.token)
link.repo = r
if link.expire_date:
expire_date = link.expire_date.strftime("%Y-%m-%dT%H:%M:%S") + DateFormat(link.expire_date).format('O')
else:
expire_date = ""
p_uploadlinks.append({
"username": link.username,
"repo_id": link.repo_id,
"path": link.path,
"token": link.token,
"ctime": link.ctime.strftime("%Y-%m-%dT%H:%M:%S") + DateFormat(link.ctime).format('O'),
"view_cnt": link.view_cnt,
"expire_date": expire_date,
})
return HttpResponse(json.dumps(p_uploadlinks),
status=200, content_type=json_content_type)
<file_sep>/tests/seahub/views/init/test_libraries.py
from django.core.urlresolvers import reverse
from constance import config
from seahub.options.models import UserOptions
from seahub.test_utils import BaseTestCase
class LibrariesTest(BaseTestCase):
def setUp(self):
self.url = reverse('libraries')
def test_user_guide(self):
self.login_as(self.user)
username = self.user.username
assert UserOptions.objects.get_default_repo(username) is None
assert UserOptions.objects.is_user_guide_enabled(username) is True
resp = self.client.get(self.url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'libraries.html')
assert resp.context['guide_enabled'] is True
resp = self.client.get(self.url)
assert resp.context['guide_enabled'] is False
assert UserOptions.objects.get_default_repo(username) is not None
assert UserOptions.objects.is_user_guide_enabled(username) is False
def test_pub_repo_creation_config(self):
# user
self.login_as(self.user)
config.ENABLE_USER_CREATE_ORG_REPO = 1
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is True
resp = self.client.get(self.url)
self.assertEqual(200, resp.status_code)
assert resp.context['can_add_pub_repo'] is True
config.ENABLE_USER_CREATE_ORG_REPO = 0
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is False
resp = self.client.get(self.url)
self.assertEqual(200, resp.status_code)
assert resp.context['can_add_pub_repo'] is False
# logout
self.client.logout()
# admin
self.login_as(self.admin)
config.ENABLE_USER_CREATE_ORG_REPO = 1
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is True
resp = self.client.get(self.url)
self.assertEqual(200, resp.status_code)
assert resp.context['can_add_pub_repo'] is True
config.ENABLE_USER_CREATE_ORG_REPO = 0
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is False
resp = self.client.get(self.url)
self.assertEqual(200, resp.status_code)
assert resp.context['can_add_pub_repo'] is True
<file_sep>/seahub/share/urls.py
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('',
url(r'^$', list_shared_repos, name='share_admin'),
url(r'^links/$', list_shared_links, name='list_shared_links'),
url(r'^folders/$', list_priv_shared_folders, name='list_priv_shared_folders'),
url(r'^add/$', share_repo, name='share_repo'),
url(r'^remove/$', repo_remove_share, name='repo_remove_share'),
url(r'^ajax/link/remove/$', ajax_remove_shared_link, name='ajax_remove_shared_link'),
url(r'^link/send/$', send_shared_link, name='send_shared_link'),
url(r'^link/save/$', save_shared_link, name='save_shared_link'),
url(r'^ajax/upload_link/remove/$', ajax_remove_shared_upload_link, name='ajax_remove_shared_upload_link'),
url(r'^upload_link/send/$', send_shared_upload_link, name='send_shared_upload_link'),
url(r'^permission_admin/$', share_permission_admin, name='share_permission_admin'),
# url('^remove/(?P<token>[^/]{24,24})/$', remove_anonymous_share, name='remove_anonymous_share'),
# url('^(?P<token>[^/]{24})/$', anonymous_share_confirm, name='anonymous_share_confirm'),
url(r'^ajax/repo_remove_share/$', ajax_repo_remove_share, name='ajax_repo_remove_share'),
url(r'^ajax/get-download-link/$', ajax_get_download_link, name='ajax_get_download_link'),
url(r'^ajax/get-upload-link/$', ajax_get_upload_link, name='ajax_get_upload_link'),
url(r'^ajax/private-share-dir/$', ajax_private_share_dir, name='ajax_private_share_dir'),
)
<file_sep>/seahub/templates/repo_basic_info.html
{% extends "myhome_base.html" %}
{% load i18n avatar_tags seahub_tags %}
{% block sub_title %}{{repo.name}} - {% endblock %}
{% block left_panel %}
<div class="side-textnav">
<h3 class="hd"><span class="op-target">{{ repo.name }}</span> {% trans "Settings" %}</h3>
<ul class="side-textnav-tabs">
<li class="tab tab-cur"><a href="{% url 'repo_basic_info' repo.id %}">{% trans "Basic Info" %}</a></li>
<li class="tab"><a href="{% url 'repo_transfer_owner' repo.id %}">{% trans "Transfer Ownership" %}</a></li>
{% if repo.encrypted and repo.enc_version == 2 %}
<li class="tab"><a href="{% url 'repo_change_password' repo.id %}">{% trans "Change Password" %}</a></li>
{% endif %}
{% if not repo.encrypted %}
<li class="tab"><a href="{% url 'repo_shared_link' repo.id %}">{% trans "Shared Links" %}</a></li>
{% endif %}
<li class="tab"><a href="{% url 'repo_share_manage' repo.id %}">{% trans "Sharing Permission" %}</a></li>
{% if ENABLE_FOLDER_PERM %}
<li class="tab"><a href="{% url 'repo_folder_perm' repo.id %}">{% trans "Folder Permission" %}</a></li>
{% endif %}
</ul>
</div>
{% endblock %}
{% block right_panel %}
<div class="lib-setting">
<h3 class="hd">{% trans "Basic Info" %}</h3>
<div id="basic-info" class="setting-item">
<form id="repo-basic-info-form" action="" method="post" class="form">{% csrf_token %}
<label>{% trans "Name" %}</label><br />
<input type="text" name="repo_name" value="{{ repo.name }}" class="input" /><br />
{% if not ENABLE_SUB_LIBRARY or not repo.is_virtual %}
<label>{% trans "History" %}</label><br />
<input type="radio" name="history" value="full_history" {% if full_history_checked %}checked="checked"{% endif %} class="vam" {% if not full_history_enabled %}disabled="disabled"{% endif %} /> <span class="vam">{% trans "Keep full history" %}</span><br />
<input type="radio" name="history" value="no_history" {% if no_history_checked %}checked="checked"{% endif %} class="vam" {% if not full_history_enabled %}disabled="disabled"{% endif %} /> <span class="vam">{% trans "Don't keep history" %}</span><br />
<input type="radio" name="history" value="partial_history" {% if partial_history_checked %}checked="checked"{% endif %} class="vam" {% if not full_history_enabled %}disabled="disabled"{% endif %} /> <span calss="vam">{% trans "Only keep a period of history:" %}
<input type="text" name="days" size="4" {% if not days_enabled %} disabled="disabled" class="input-disabled"{% endif %} value="{{history_limit}}" /> {% trans "days" %}</span><br />
{% endif %}
<p class="error hide"></p>
<input type="submit" value="{% trans "Submit" %}" class="submit" />
</form>
</div>
</div>
{% endblock %}
{% block extra_script %}
<script type="text/javascript">
$('#repo-basic-info-form input[name="history"]').change(function() {
var value = $(this).attr('value'),
days_input = $('#repo-basic-info-form input[name="days"]');
if (value == 'full_history' || value == 'no_history') {
days_input.attr('disabled', true).addClass('input-disabled');
} else {
days_input.attr('disabled', false).removeClass('input-disabled');
}
});
$('#repo-basic-info-form').submit(function() {
var form = $(this),
form_id = form.attr('id');
var repo_name = $('[name="repo_name"]', form).val();
if (!$.trim(repo_name)) {
apply_form_error(form_id, "{% trans "Name is required." %}");
return false;
}
var days;
var value = $(this).find('input[name="history"]:checked').val();
if (value == 'partial_history') {
days = $(this).find('input[name="days"]').val();
} else if (value == 'full_history') {
days = -1;
} else {
days = 0;
}
var submit_btn = $(this).children('input[type="submit"]');
disable(submit_btn);
$.ajax({
url: '{% url 'ajax_repo_change_basic_info' repo.id %}',
type: 'POST',
dataType: 'json',
beforeSend: prepareCSRFToken,
data: {
'repo_name': repo_name,
'days': days
},
success: function(data) {
location.reload(true);
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.responseText) {
apply_form_error(form_id, $.parseJSON(jqXHR.responseText).error);
} else {
apply_form_error(form_id, "{% trans "Failed. Please check the network." %}");
}
enable(submit_btn);
}
});
return false;
});
</script>
{% endblock %}
<file_sep>/tests/seahub/views/test_shared_file.py
# encoding: utf-8
import os
from django.core.urlresolvers import reverse
from django.test import TestCase
import requests
from seahub.share.models import FileShare
from seahub.test_utils import Fixtures
class SharedFileTest(TestCase, Fixtures):
def setUp(self):
share_file_info = {
'username': self.user,
'repo_id': self.repo.id,
'path': self.file,
'password': <PASSWORD>,
'expire_date': None,
}
self.fs = FileShare.objects.create_file_link(**share_file_info)
share_file_info.update({'password': '<PASSWORD>'})
self.enc_fs = FileShare.objects.create_file_link(**share_file_info)
share_file_info.update({'password': '<PASSWORD>'})
self.enc_fs2 = FileShare.objects.create_file_link(**share_file_info)
assert self.enc_fs.token != self.enc_fs2.token
def tearDown(self):
self.remove_repo()
def test_can_render(self):
resp = self.client.get(reverse('view_shared_file', args=[self.fs.token]))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'shared_file_view.html')
self.assertContains(resp, os.path.basename(self.file))
dl_url_tag = '<a href="?dl=1" class="obv-btn">'
self.assertContains(resp, dl_url_tag)
def test_can_download(self):
dl_url = reverse('view_shared_file', args=[self.fs.token]) + '?dl=1'
resp = self.client.get(dl_url)
self.assertEqual(302, resp.status_code)
assert '8082/files/' in resp.get('location')
def test_dl_link_can_use_more_times(self):
dl_url = reverse('view_shared_file', args=[self.fs.token]) + '?dl=1'
resp = self.client.get(dl_url)
self.assertEqual(302, resp.status_code)
dl_link = resp.get('location')
res = requests.get(dl_link)
self.assertEqual(200, res.status_code)
res = requests.get(dl_link)
self.assertEqual(200, res.status_code)
def test_can_view_raw(self):
dl_url = reverse('view_shared_file', args=[self.fs.token]) + '?raw=1'
resp = self.client.get(dl_url)
self.assertEqual(302, resp.status_code)
assert '8082/files/' in resp.get('location')
def test_view_count(self):
"""Issue https://github.com/haiwen/seahub/issues/742
"""
resp = self.client.get(reverse('view_shared_file', args=[self.fs.token]))
self.assertEqual(200, resp.status_code)
self.assertEqual(1, FileShare.objects.get(token=self.fs.token).view_cnt)
dl_url = reverse('view_shared_file', args=[self.fs.token]) + '?raw=1'
resp = self.client.get(dl_url)
self.assertEqual(302, resp.status_code)
self.assertEqual(2, FileShare.objects.get(token=self.fs.token).view_cnt)
dl_url = reverse('view_shared_file', args=[self.fs.token]) + '?dl=1'
resp = self.client.get(dl_url)
self.assertEqual(302, resp.status_code)
self.assertEqual(3, FileShare.objects.get(token=self.fs.token).view_cnt)
def test_can_render_when_remove_parent_dir(self):
"""Issue https://github.com/haiwen/seafile/issues/1283
"""
# create a file in a folder
self.create_file(repo_id=self.repo.id,
parent_dir=self.folder,
filename='file.txt',
username=self.user.username)
# share that file
share_file_info = {
'username': self.user.username,
'repo_id': self.repo.id,
'path': os.path.join(self.folder, 'file.txt'),
'password': <PASSWORD>,
'expire_date': None,
}
fs = FileShare.objects.create_file_link(**share_file_info)
resp = self.client.get(reverse('view_shared_file', args=[fs.token]))
self.assertEqual(200, resp.status_code)
# then delete parent folder, see whether it raises error
self.remove_folder()
resp = self.client.get(reverse('view_shared_file', args=[fs.token]))
self.assertEqual(200, resp.status_code)
def _assert_redirect_to_password_page(self, fs):
resp = self.client.get(reverse('view_shared_file', args=[fs.token]))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'share_access_validation.html')
def _assert_render_file_page_when_input_passwd(self, fs):
resp = self.client.post(reverse('view_shared_file', args=[fs.token]), {
'password': '<PASSWORD>',
})
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'shared_file_view.html')
self.assertContains(resp, os.path.basename(self.file))
dl_url_tag = '<a href="?dl=1" class="obv-btn">'
self.assertContains(resp, dl_url_tag)
def _assert_render_file_page_without_passwd(self, fs):
resp = self.client.get(reverse('view_shared_file', args=[fs.token]))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'shared_file_view.html')
def test_can_view_enc(self):
self._assert_redirect_to_password_page(self.enc_fs)
self._assert_render_file_page_when_input_passwd(self.enc_fs)
def test_can_view_enc_link_without_passwd(self):
self._assert_redirect_to_password_page(self.enc_fs)
self._assert_render_file_page_when_input_passwd(self.enc_fs)
self._assert_render_file_page_without_passwd(self.enc_fs)
def test_can_view_multiple_enc_links_without_passwd(self):
# first shared link
self._assert_redirect_to_password_page(self.enc_fs)
self._assert_render_file_page_when_input_passwd(self.enc_fs)
# second shared link
self._assert_redirect_to_password_page(self.enc_fs2)
self._assert_render_file_page_when_input_passwd(self.enc_fs2)
self._assert_render_file_page_without_passwd(self.enc_fs)
self._assert_render_file_page_without_passwd(self.enc_fs2)
class FileViaSharedDirTest(TestCase, Fixtures):
def setUp(self):
share_file_info = {
'username': '<EMAIL>',
'repo_id': self.repo.id,
'path': '/',
'password': <PASSWORD>,
'expire_date': None,
}
self.fs = FileShare.objects.create_dir_link(**share_file_info)
def tearDown(self):
self.remove_repo()
def test_can_render(self):
resp = self.client.get(
reverse('view_file_via_shared_dir', args=[self.fs.token]) + \
'?p=%s' % self.file
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'shared_file_view.html')
self.assertContains(resp, os.path.basename(self.file))
dl_url_tag = '<a href="?p=%s&dl=1" class="obv-btn">' % self.file
self.assertContains(resp, dl_url_tag)
def test_can_view_image_in_sub_dir(self):
"""View 3.jpg when share 'folder' will raise error.
Issue https://github.com/haiwen/seafile/issues/1248
.
├── 1.jpg
├── 2.jpc
└── folder
└── 3.jpg
"""
# setup
self.create_file(repo_id=self.repo.id,
parent_dir='/',
filename='1.jpg',
username='<EMAIL>')
self.create_file(repo_id=self.repo.id,
parent_dir='/',
filename='2.jpg',
username='<EMAIL>')
folder_path = self.folder
self.create_file(repo_id=self.repo.id,
parent_dir=folder_path,
filename='3.jpg',
username='<EMAIL>')
share_file_info = {
'username': '<EMAIL>',
'repo_id': self.repo.id,
'path': folder_path,
'password': <PASSWORD>,
'expire_date': None,
}
fs = FileShare.objects.create_dir_link(**share_file_info)
resp = self.client.get(
reverse('view_file_via_shared_dir', args=[fs.token]) + \
'?p=/3.jpg'
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'shared_file_view.html')
self.assertContains(resp, '3.jpg')
def test_can_download(self):
dl_url = reverse('view_file_via_shared_dir', args=[self.fs.token]) + \
'?p=%s&dl=1' % self.file
resp = self.client.get(dl_url)
self.assertEqual(302, resp.status_code)
assert '8082/files/' in resp.get('location')
# class PrivateSharedFileTest(TestCase, Fixtures):
# def setUp(self):
# self.user2 = self.create_user('<EMAIL>')
# share_file_info = {
# 'from_user': self.user.username,
# 'to_user': self.user2.username,
# 'repo_id': self.repo.id,
# 'path': self.file,
# }
# self.fs = PrivateFileDirShare.objects.add_read_only_priv_file_share(
# **share_file_info)
# def tearDown(self):
# self.remove_repo()
# self.remove_user(self.user.username)
# self.remove_user(self.user2.username)
# def test_can_render(self):
# self.client.post(
# reverse('auth_login'), {'username': self.user2.username,
# 'password': '<PASSWORD>'}
# )
# resp = self.client.get(
# reverse('view_priv_shared_file', args=[self.fs.token])
# )
# self.assertEqual(200, resp.status_code)
# self.assertTemplateUsed(resp, 'shared_file_view.html')
# self.assertContains(resp, os.path.basename(self.file))
# dl_url_tag = '<a href="?dl=1" class="obv-btn">'
# self.assertContains(resp, dl_url_tag)
# def test_can_download(self):
# self.client.post(
# reverse('auth_login'), {'username': self.user2.username,
# 'password': '<PASSWORD>'}
# )
# dl_url = reverse('view_priv_shared_file', args=[self.fs.token]) + \
# '?p=%s&dl=1' % self.file
# resp = self.client.get(dl_url)
# self.assertEqual(302, resp.status_code)
# assert '8082/files/' in resp.get('location')
<file_sep>/seahub/templates/snippets/search_form.html
{% load i18n %}
<form id="top-search-form" method="get" action="{% url 'search' %}" class="search-form fleft">
{% if search_repo_id %}
<input class="search-input" name="q" placeholder="{% if search_wiki %}{% trans "Search files in this wiki" %}{% else %}{% trans "Search files in this library" %}{% endif %}" value="{{ keyword }}" />
<input type="hidden" name="search_repo" value="{{ search_repo_id }}" />
{% else %}
<input class="search-input" name="q" placeholder="{% trans 'Search Files' %}" value="{{ keyword }}" />
{% endif %}
<!--span class="icon-caret-down" title="{% trans "advanced" %}"></span--><button type="submit" class="search-submit"><span class="icon-search"></span></button>
</form>
<form id="advanced-search-form" method="get" action="{% url 'search' %}" class="search-form hide">
<input class="search-input" name="q" placeholder="{% trans 'Search Files' %}" value="{{ keyword }}" />
<div class="search-scales">
<div class="search-repos">
{% if search_repo_id %}
<label class="item"><input type="radio" name="search_repo" value="all" class="vam" /> <span class="vam">{% trans "In all libraries" %}</span></label>
<label class="item"><input type="radio" name="search_repo" checked="checked" value="{{ search_repo_id }}" class="vam" /> <span class="vam">{% if search_wiki %}{% trans "In this wiki" %}{% else %}{% trans "In this library" %}{% endif %}</span></label>
{% else %}
{% if search_repo and repo %}
<label class="item"><input type="radio" name="search_repo" value="all" class="vam" /> <span class="vam">{% trans "In all libraries" %}</span></label>
<label class="item"><input type="radio" name="search_repo" value="{{repo.id}}" checked="checked" class="vam" /> <span class="vam">{% blocktrans with name=repo.name %}in {{name }}{% endblocktrans %}</span></label>
{% else %}
<label class="item"><input type="radio" name="search_repo" value="all" checked="checked" class="vam" /> <span class="vam">{% trans "In all libraries" %}</span></label>
{% endif %}
{% endif %}
</div>
<div class="search-filetypes">
{% if search_ftypes != 'custom' %}
<label class="item"><input type="radio" name="search_ftypes" value="all" checked="checked" class="vam" /> <span class="vam">{% trans "All file types" %}</span></label>
<label class="item"><input type="radio" name="search_ftypes" value="custom" class="vam" id="custom-search-ftypes" /> <span class="vam">{% trans "Custom file types" %}</span></label>
{% else %}
<label class="item"><input type="radio" name="search_ftypes" value="all" class="vam" /> <span class="vam">{% trans "All file types" %}</span></label>
<label class="item"><input type="radio" name="search_ftypes" value="custom" checked="checked" class="vam" id="custom-search-ftypes" /> <span class="vam">{% trans "Custom file types" %}</span></label>
{% endif %}
</div>
{% if search_ftypes != 'custom' %}
<div class="custom-ftype-options hide">
{% else %}
<div class="custom-ftype-options">
{% endif %}
{# ftype value should be the same with utils/file_types.py #}
<label class="checkbox-label"><span class="checkbox"><input type="checkbox" name="ftype" value="Text" class="checkbox-orig" /></span><span class="checkbox-option">{% trans "Text files" %}</span></label>
<label class="checkbox-label"><span class="checkbox"><input type="checkbox" name="ftype" value="Document" class="checkbox-orig" /></span><span class="checkbox-option">{% trans "Documents" %}</span></label>
<label class="checkbox-label"><span class="checkbox"><input type="checkbox" name="ftype" value="Image" class="checkbox-orig" /></span><span class="checkbox-option">{% trans "Images" %}</span></label>
<label class="checkbox-label"><span class="checkbox"><input type="checkbox" name="ftype" value="Video" class="checkbox-orig" /></span><span class="checkbox-option">{% trans "Video" %}</span></label>
<label class="checkbox-label"><span class="checkbox"><input type="checkbox" name="ftype" value="Audio" class="checkbox-orig" /></span><span class="checkbox-option">{% trans "Audio" %}</span></label>
<label class="checkbox-label"><span class="checkbox"><input type="checkbox" name="ftype" value="SVG" class="checkbox-orig" /></span><span class="checkbox-option">{% trans "svg" %}</span></label>
<label class="checkbox-label"><span class="checkbox"><input type="checkbox" name="ftype" value="PDF" class="checkbox-orig" /></span><span class="checkbox-option">{% trans "pdf" %}</span></label>
<label class="checkbox-label"><span class="checkbox"><input type="checkbox" name="ftype" value="Sf" class="checkbox-orig" /></span><span class="checkbox-option">{% trans "seaf" %}</span></label>
<label class="checkbox-label"><span class="checkbox"><input type="checkbox" name="ftype" value="Markdown" class="checkbox-orig" /></span><span class="checkbox-option">{% trans "markdown" %}</span></label>
<br/>
<input type="text" value="{{ input_fileexts }}" name="input_fexts" placeholder="{% trans "Input file extensions here, separate with ','" %}" class="fileext-input" />
<p class="error hide">{% trans "Please select at least one file type or input at least one file extension" %}</p>
</div>
</div>
<input type="submit" value="{% trans "Submit" %}" class="submit" />
</form>
<file_sep>/seahub/group/urls.py
from django.conf.urls.defaults import *
from views import group_info, group_members, group_member_operations, group_add_admin, \
group_manage, msg_reply, msg_reply_new, group_recommend, \
create_group_repo, attention, group_message_remove, \
group_remove_admin, group_discuss, group_wiki, group_wiki_create, \
group_wiki_page_new, group_wiki_page_edit, group_wiki_pages, \
group_wiki_page_delete, group_wiki_use_lib, group_remove, group_dismiss, group_quit, \
group_make_public, group_revoke_public, group_transfer, group_toggle_modules, \
group_add_discussion, group_rename, group_add, ajax_add_group_member, \
batch_add_members
urlpatterns = patterns('',
url(r'^(?P<group_id>\d+)/$', group_info, name='group_info'),
url(r'^(?P<group_id>\d+)/discuss/$', group_discuss, name='group_discuss'),
url(r'^(?P<group_id>\d+)/wiki/$', group_wiki, name='group_wiki'),
url(r'^(?P<group_id>\d+)/wiki/(?P<page_name>[^/]+)$', group_wiki, name='group_wiki'),
url(r'^(?P<group_id>\d+)/wiki_pages/$', group_wiki_pages, name='group_wiki_pages'),
url(r'^(?P<group_id>\d+)/wiki_create/$', group_wiki_create, name='group_wiki_create'),
url(r'^(?P<group_id>\d+)/wiki_use_lib/$', group_wiki_use_lib, name='group_wiki_use_lib'),
url(r'^(?P<group_id>\d+)/wiki_page_new/$', group_wiki_page_new, name='group_wiki_page_new'),
url(r'^(?P<group_id>\d+)/wiki_page_edit/(?P<page_name>[^/]+)$', group_wiki_page_edit, name='group_wiki_page_edit'),
url(r'^(?P<group_id>\d+)/wiki_page_delete/(?P<page_name>[^/]+)$', group_wiki_page_delete, name='group_wiki_page_delete'),
url(r'^reply/(?P<msg_id>[\d]+)/$', msg_reply, name='msg_reply'),
url(r'^reply/new/$', msg_reply_new, name='msg_reply_new'),
url(r'^(?P<group_id>\d+)/manage/$', group_manage, name='group_manage'),
url(r'^(?P<group_id>\d+)/remove/$', group_remove, name='group_remove'),
url(r'^(?P<group_id>\d+)/dismiss/$', group_dismiss, name='group_dismiss'),
url(r'^(?P<group_id>\d+)/rename/$', group_rename, name='group_rename'),
url(r'^(?P<group_id>\d+)/transfer/$', group_transfer, name='group_transfer'),
url(r'^(?P<group_id>\d+)/make_pub/$', group_make_public, name='group_make_pub'),
url(r'^(?P<group_id>\d+)/revoke_pub/$', group_revoke_public, name='group_revoke_pub'),
url(r'^(?P<group_id>\d+)/quit/$', group_quit, name='group_quit'),
url(r'^(?P<group_id>[\d]+)/create-repo/$', create_group_repo, name='create_group_repo'),
url(r'^(?P<group_id>[\d]+)/members/$', group_members, name='group_members'),
(r'^(?P<group_id>[\d]+)/member/(?P<user_name>[^/]+)/$', group_member_operations),
url(r'^(?P<group_id>\d+)/msgdel/(?P<msg_id>\d+)/$', group_message_remove, name='group_message_remove'),
url(r'^(?P<group_id>\d+)/admin/add/$', group_add_admin, name='group_add_admin'),
url(r'^(?P<group_id>\d+)/admin/remove/$', group_remove_admin, name='group_remove_admin'),
url(r'^recommend/$', group_recommend, name='group_recommend'),
#url(r'^attention/$', attention, name='group_attention'),
url(r'^(?P<group_id>\d+)/modules/toggle/$', group_toggle_modules, name='group_toggle_modules'),
url(r'^(?P<group_id>\d+)/discussion/add/$', group_add_discussion, name='group_add_discussion'),
url(r'^add/$', group_add, name='group_add'),
url(r'^(?P<group_id>\d+)/batch-add-members/$', batch_add_members, name='batch_add_members'),
url(r'^ajax/(?P<group_id>\d+)/member/add/$', ajax_add_group_member, name='group_add_member'),
)
import seahub.settings as settings
if settings.ENABLE_PUBFILE:
from seahub_extra.pubfile.views import group_pubfiles, group_pubfile_add, group_pubfile_delete, group_pubfile_edit, group_pubfile_download
urlpatterns += patterns('',
url(r'^(?P<group_id>\d+)/files/$', group_pubfiles, name='group_pubfiles'),
url(r'^(?P<group_id>\d+)/file/add/$', group_pubfile_add, name='group_pubfile_add'),
url(r'^(?P<group_id>\d+)/file/(?P<file_id>\d+)/delete/$', group_pubfile_delete, name='group_pubfile_delete'),
url(r'^(?P<group_id>\d+)/file/(?P<file_id>\d+)/edit/$', group_pubfile_edit, name='group_pubfile_edit'),
url(r'^(?P<group_id>\d+)/file/d/(?P<file_name>.+)$', group_pubfile_download, name='group_pubfile_download'),
)
<file_sep>/seahub/api2/endpoints/groups.py
import logging
from django.utils.dateformat import DateFormat
from django.utils.translation import ugettext as _
from django.template.defaultfilters import filesizeformat
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import UserRateThrottle
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
import seaserv
from seaserv import seafile_api
from pysearpc import SearpcError
from seahub.api2.utils import api_error
from seahub.api2.authentication import TokenAuthentication
from seahub.avatar.settings import GROUP_AVATAR_DEFAULT_SIZE
from seahub.avatar.templatetags.group_avatar_tags import api_grp_avatar_url, \
get_default_group_avatar_url
from seahub.utils import is_org_context
from seahub.utils.timeutils import dt, utc_to_local
from seahub.group.utils import validate_group_name, check_group_name_conflict, get_group_domain
from seahub.base.templatetags.seahub_tags import email2nickname, \
translate_seahub_time
logger = logging.getLogger(__name__)
class Groups(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle, )
def _get_group_admins(self, group_id):
members = seaserv.get_group_members(group_id)
admin_members = filter(lambda m: m.is_staff, members)
admins = []
for u in admin_members:
admins.append(u.user_name)
return admins
def _can_add_group(self, request):
return request.user.permissions.can_add_group()
def get(self, request):
""" List all groups.
"""
org_id = None
username = request.user.username
group_domain = username.split('@')[1]
if is_org_context(request):
org_id = request.user.org.org_id
user_groups = seaserv.get_org_groups_by_user(org_id, username)
else:
user_groups = seaserv.get_personal_groups_by_user(username)
try:
size = int(request.GET.get('avatar_size', GROUP_AVATAR_DEFAULT_SIZE))
except ValueError:
size = GROUP_AVATAR_DEFAULT_SIZE
with_repos = request.GET.get('with_repos')
with_repos = True if with_repos == '1' else False
groups = []
for g in user_groups:
try:
avatar_url, is_default, date_uploaded = api_grp_avatar_url(g.id, size)
except Exception as e:
logger.error(e)
avatar_url = get_default_group_avatar_url()
if get_group_domain(g.id) != group_domain:
continue
val = utc_to_local(dt(g.timestamp))
group = {
"id": g.id,
"name": g.group_name,
"creator": g.creator_name,
"created_at": val.strftime("%Y-%m-%dT%H:%M:%S") + DateFormat(val).format('O'),
"avatar_url": request.build_absolute_uri(avatar_url),
"admins": self._get_group_admins(g.id),
}
if with_repos:
if org_id:
group_repos = seafile_api.get_org_group_repos(org_id, g.id)
else:
group_repos = seafile_api.get_repos_by_group(g.id)
repos = []
for r in group_repos:
repo = {
"id": r.id,
"name": r.name,
"desc": r.desc,
"size": r.size,
"size_formatted": filesizeformat(r.size),
"mtime": r.last_modified,
"mtime_relative": translate_seahub_time(r.last_modified),
"encrypted": r.encrypted,
"permission": r.permission,
"owner": r.user,
"owner_nickname": email2nickname(r.user),
"share_from_me": True if username == r.user else False,
}
repos.append(repo)
group['repos'] = repos
groups.append(group)
return Response(groups)
def post(self, request):
""" Create a group
"""
if not self._can_add_group(request):
error_msg = _(u'You do not have permission to create group.')
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
username = request.user.username
group_domain = username.split('@')[1]
group_name = request.DATA.get('group_name', '')
group_name = group_name.strip()
# Check whether group name is validate.
if not validate_group_name(group_name):
error_msg = _(u'Group name can only contain letters, numbers, blank, hyphen or underscore')
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
# Check whether group name is duplicated.
if check_group_name_conflict(request, group_name, group_domain):
error_msg = _(u'There is already a group with that name.')
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
# Group name is valid, create that group.
try:
if is_org_context(request):
org_id = request.user.org.org_id
group_id = seaserv.ccnet_threaded_rpc.create_org_group(org_id,
group_name,
username)
else:
group_id = seaserv.ccnet_threaded_rpc.create_group(group_name,
username)
except SearpcError as e:
logger.error(e)
error_msg = _(u'Failed')
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
try:
size = int(request.DATA.get('avatar_size', GROUP_AVATAR_DEFAULT_SIZE))
except ValueError:
size = GROUP_AVATAR_DEFAULT_SIZE
g = seaserv.get_group(group_id)
try:
avatar_url, is_default, date_uploaded = api_grp_avatar_url(g.id, size)
except Exception as e:
logger.error(e)
avatar_url = get_default_group_avatar_url()
val = utc_to_local(dt(g.timestamp))
new_group = {
"id": g.id,
"name": g.group_name,
"creator": g.creator_name,
"created_at": val.strftime("%Y-%m-%dT%H:%M:%S") + DateFormat(val).format('O'),
"avatar_url": request.build_absolute_uri(avatar_url),
"admins": self._get_group_admins(g.id),
}
return Response(new_group, status=status.HTTP_201_CREATED)
<file_sep>/requirements.txt
python-dateutil
chardet
six
Pillow>=2.6.1,<3.0.0
Django>=1.5.8,<1.6
http://effbot.org/media/downloads/PIL-1.1.7.tar.gz
https://github.com/djblets/djblets/archive/release-0.6.14.zip#egg=Djblets
django-compressor==1.4
django-statici18n==1.1.2
git+git://github.com/haiwen/django-constance.git@<PASSWORD>#egg=django-constance[database]
openpyxl==2.3.0
<file_sep>/tests/seahub/options/test_models.py
from seahub.test_utils import BaseTestCase
from seahub.options.models import (UserOptions, KEY_USER_GUIDE,
VAL_USER_GUIDE_ON, VAL_USER_GUIDE_OFF)
class UserOptionsManagerTest(BaseTestCase):
def test_is_user_guide_enabled(self):
assert UserOptions.objects.is_user_guide_enabled(self.user.email) is True
UserOptions.objects.create(email=self.user.email,
option_key=KEY_USER_GUIDE,
option_val=VAL_USER_GUIDE_OFF)
assert UserOptions.objects.is_user_guide_enabled(self.user.email) is False
def test_is_user_guide_enabled_with_multiple_records(self):
UserOptions.objects.create(email=self.user.email,
option_key=KEY_USER_GUIDE,
option_val=VAL_USER_GUIDE_OFF)
UserOptions.objects.create(email=self.user.email,
option_key=KEY_USER_GUIDE,
option_val=VAL_USER_GUIDE_ON)
assert len(UserOptions.objects.filter(email=self.user.email,
option_key=KEY_USER_GUIDE)) == 2
assert UserOptions.objects.is_user_guide_enabled(self.user.email) is True
assert len(UserOptions.objects.filter(email=self.user.email,
option_key=KEY_USER_GUIDE)) == 1
<file_sep>/thirdpart/rest_framework/generics.py
"""
Generic views that provide commonly needed behaviour.
"""
from rest_framework import views, mixins
from rest_framework.settings import api_settings
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.list import MultipleObjectMixin
### Base classes for the generic views ###
class GenericAPIView(views.APIView):
"""
Base class for all other generic views.
"""
model = None
serializer_class = None
model_serializer_class = api_settings.DEFAULT_MODEL_SERIALIZER_CLASS
def get_serializer_context(self):
"""
Extra context provided to the serializer class.
"""
return {
'request': self.request,
'format': self.format_kwarg,
'view': self
}
def get_serializer_class(self):
"""
Return the class to use for the serializer.
Defaults to using `self.serializer_class`, falls back to constructing a
model serializer class using `self.model_serializer_class`, with
`self.model` as the model.
"""
serializer_class = self.serializer_class
if serializer_class is None:
class DefaultSerializer(self.model_serializer_class):
class Meta:
model = self.model
serializer_class = DefaultSerializer
return serializer_class
def get_serializer(self, instance=None, data=None, files=None):
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
"""
serializer_class = self.get_serializer_class()
context = self.get_serializer_context()
return serializer_class(instance, data=data, files=files, context=context)
class MultipleObjectAPIView(MultipleObjectMixin, GenericAPIView):
"""
Base class for generic views onto a queryset.
"""
paginate_by = api_settings.PAGINATE_BY
paginate_by_param = api_settings.PAGINATE_BY_PARAM
pagination_serializer_class = api_settings.DEFAULT_PAGINATION_SERIALIZER_CLASS
filter_backend = api_settings.FILTER_BACKEND
def filter_queryset(self, queryset):
"""
Given a queryset, filter it with whichever filter backend is in use.
"""
if not self.filter_backend:
return queryset
backend = self.filter_backend()
return backend.filter_queryset(self.request, queryset, self)
def get_pagination_serializer(self, page=None):
"""
Return a serializer instance to use with paginated data.
"""
class SerializerClass(self.pagination_serializer_class):
class Meta:
object_serializer_class = self.get_serializer_class()
pagination_serializer_class = SerializerClass
context = self.get_serializer_context()
return pagination_serializer_class(instance=page, context=context)
def get_paginate_by(self, queryset):
"""
Return the size of pages to use with pagination.
"""
if self.paginate_by_param:
query_params = self.request.QUERY_PARAMS
try:
return int(query_params[self.paginate_by_param])
except (KeyError, ValueError):
pass
return self.paginate_by
class SingleObjectAPIView(SingleObjectMixin, GenericAPIView):
"""
Base class for generic views onto a model instance.
"""
pk_url_kwarg = 'pk' # Not provided in Django 1.3
slug_url_kwarg = 'slug' # Not provided in Django 1.3
slug_field = 'slug'
def get_object(self, queryset=None):
"""
Override default to add support for object-level permissions.
"""
obj = super(SingleObjectAPIView, self).get_object(queryset)
if not self.has_permission(self.request, obj):
self.permission_denied(self.request)
return obj
### Concrete view classes that provide method handlers ###
### by composing the mixin classes with a base view. ###
class CreateAPIView(mixins.CreateModelMixin,
GenericAPIView):
"""
Concrete view for creating a model instance.
"""
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class ListAPIView(mixins.ListModelMixin,
MultipleObjectAPIView):
"""
Concrete view for listing a queryset.
"""
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class RetrieveAPIView(mixins.RetrieveModelMixin,
SingleObjectAPIView):
"""
Concrete view for retrieving a model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
class DestroyAPIView(mixins.DestroyModelMixin,
SingleObjectAPIView):
"""
Concrete view for deleting a model instance.
"""
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
class UpdateAPIView(mixins.UpdateModelMixin,
SingleObjectAPIView):
"""
Concrete view for updating a model instance.
"""
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
class ListCreateAPIView(mixins.ListModelMixin,
mixins.CreateModelMixin,
MultipleObjectAPIView):
"""
Concrete view for listing a queryset or creating a model instance.
"""
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class RetrieveDestroyAPIView(mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
SingleObjectAPIView):
"""
Concrete view for retrieving or deleting a model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
SingleObjectAPIView):
"""
Concrete view for retrieving, updating or deleting a model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
<file_sep>/seahub/share/tokens.py
import random
from datetime import date
from datetime import datetime as dt
from django.conf import settings
from django.utils.http import int_to_base36, base36_to_int
from settings import ANONYMOUS_SHARE_LINK_TIMEOUT
class AnonymousShareTokenGenerator(object):
"""
Strategy object used to generate and check tokens for the repo anonymous
share mechanism.
"""
def make_token(self):
"""
Returns a token that can be used once to do a anonymous share for repo.
"""
return self._make_token_with_timestamp(self._num_days(self._today()))
def check_token(self, token):
"""
Check that a anonymous share token is valid.
"""
# Parse the token
try:
ts_b36, hash = token.split("-")
except ValueError:
return False
try:
ts = base36_to_int(ts_b36)
except ValueError:
return False
# Check the timestamp is within limit
if (self._num_days(self._today()) - ts) > ANONYMOUS_SHARE_LINK_TIMEOUT:
return False
return True
def get_remain_time(self, token):
"""
Get token remain time.
"""
try:
ts_b36, hash = token.split("-")
except ValueError:
return None
try:
ts = base36_to_int(ts_b36)
except ValueError:
return None
days = ANONYMOUS_SHARE_LINK_TIMEOUT - (self._num_days(self._today()) - ts)
if days < 0:
return None
now = dt.now()
tomorrow = dt(now.year, now.month, now.day+1)
return (tomorrow - now).seconds + days * 24 * 60 * 60
def _make_token_with_timestamp(self, timestamp):
# timestamp is number of days since 2001-1-1. Converted to
# base 36, this gives us a 3 digit string until about 2121
ts_b36 = int_to_base36(timestamp)
# We limit the hash to 20 chars to keep URL short
import datetime
import hashlib
now = datetime.datetime.now()
hash = hashlib.sha1(settings.SECRET_KEY +
unicode(random.randint(0, 999999)) +
now.strftime('%Y-%m-%d %H:%M:%S') +
unicode(timestamp)).hexdigest()[::2]
return "%s-%s" % (ts_b36, hash)
def _num_days(self, dt):
return (dt - date(2001,1,1)).days
def _today(self):
# Used for mocking in tests
return date.today()
anon_share_token_generator = AnonymousShareTokenGenerator()
<file_sep>/static/scripts/app/views/activities.js
define([
'jquery',
'underscore',
'backbone',
'common',
'app/collections/activities',
'app/views/activity-item'
], function($, _, Backbone, Common, ActivityCollection, ActivityItemView) {
'use strict';
var ActivitiesView = Backbone.View.extend({
el: $('#activities'),
activityGroupHdTemplate: _.template($('#activity-group-hd-tmpl').html()),
activityGroupBdTemplate: _.template($('#activity-group-bd-tmpl').html()),
initialize: function () {
this.activities = new ActivityCollection();
this.$activitiesBody = this.$('#activities-body');
this.$activitiesMore = this.$('#activities-more');
this.$loadingTip = this.$('.loading-tip');
this.moreOffset = 0;
},
events: {
'click #activities-more': 'getMoreActivities'
},
getMoreActivities: function () {
var _this = this;
this.$loadingTip.show();
this.$activitiesMore.hide();
this.activities.fetch({
remove: false,
data: {'start': _this.moreOffset},
success: function() {
_this.render();
}
});
},
render: function () {
var activitiesJson = this.activities.toJSON(),
len = activitiesJson.length,
more = activitiesJson[len-1]['more'],
allActivities = [];
this.$loadingTip.hide();
this.$activitiesMore.hide();
this.moreOffset = activitiesJson[len-1]['more_offset'];
this.$activitiesBody.empty().show();
for (var i = 0; i < len; i++) {
allActivities = allActivities.concat(activitiesJson[i]['events']);
}
// return sth. like {2015-07-27: [{...},], 2015-06-04: [{...}] ...}
var groupedActivities = _.groupBy(allActivities, 'date');
var $groupDate, $groupActivities;
for (var date in groupedActivities) {
$groupDate = $(this.activityGroupHdTemplate({'date': date}));
$groupActivities = $(this.activityGroupBdTemplate());
_.each(groupedActivities[date], function(activity) {
var view = new ActivityItemView(activity);
$groupActivities.append(view.render().el);
});
this.$activitiesBody.append($groupDate).append($groupActivities);
}
if (more) {
this.$activitiesMore.show();
}
},
hide: function () {
this.$el.hide();
},
show: function () {
this.$el.show();
this.$activitiesBody.hide();
this.$activitiesMore.hide();
this.$loadingTip.show();
var _this = this;
this.activities.fetch({
data: {'start': 0},
success: function() {
_this.render();
}
});
}
});
return ActivitiesView;
});
<file_sep>/static/scripts/app/views/repo.js
define([
'jquery',
'underscore',
'backbone',
'common',
'app/views/share'
], function($, _, Backbone, Common, ShareView) {
'use strict';
var RepoView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#repo-tmpl').html()),
repoDelConfirmTemplate: _.template($('#repo-del-confirm-template').html()),
events: {
'mouseenter': 'highlight',
'mouseleave': 'rmHighlight',
'click .repo-delete-btn': 'del',
'click .repo-share-btn': 'share'
},
initialize: function() {
},
render: function() {
var template_variables = this.model.toJSON();
template_variables['sync_problem'] = Common.isFilenameProblematicForSyncing(template_variables['name']);
this.$el.html(this.template(template_variables));
return this;
},
// disable 'hover' when 'repo-del-confirm' popup is shown
highlight: function() {
if ($('#my-own-repos .repo-del-confirm').length == 0) {
this.$el.addClass('hl').find('.op-icon').removeClass('vh');
}
},
rmHighlight: function() {
if ($('#my-own-repos .repo-del-confirm').length == 0) {
this.$el.removeClass('hl').find('.op-icon').addClass('vh');
}
},
del: function() {
var del_icon = this.$('.repo-delete-btn');
var op_container = this.$('.op-container').css({'position': 'relative'});
var confirm_msg = gettext("Really want to delete {lib_name}?")
.replace('{lib_name}', '<span class="op-target">' + Common.HTMLescape(this.model.get('name')) + '</span>');
var confirm_popup = $(this.repoDelConfirmTemplate({
content: confirm_msg
}))
.appendTo(op_container)
.css({
'left': del_icon.position().left,
'top': del_icon.position().top + del_icon.height() + 2,
'width': 180
});
var _this = this;
$('.no', confirm_popup).click(function() {
confirm_popup.addClass('hide').remove(); // `addClass('hide')`: to rm cursor
_this.rmHighlight();
});
$('.yes', confirm_popup).click(function() {
$.ajax({
url: Common.getUrl({'name':'repo_del', 'repo_id': _this.model.get('id')}),
type: 'POST',
dataType: 'json',
beforeSend: Common.prepareCSRFToken,
success: function(data) {
_this.remove();
Common.feedback(gettext("Delete succeeded."), 'success');
},
error: function(xhr) {
confirm_popup.addClass('hide').remove();
_this.rmHighlight();
var err;
if (xhr.responseText) {
err = $.parseJSON(xhr.responseText).error;
} else {
err = gettext("Failed. Please check the network.");
}
Common.feedback(err, 'error');
}
});
});
},
share: function() {
var options = {
'is_repo_owner': true,
'is_virtual': this.model.get('virtual'),
'user_perm': 'rw',
'repo_id': this.model.get('id'),
'repo_encrypted': this.model.get('encrypted'),
'is_dir': true,
'dirent_path': '/',
'obj_name': this.model.get('name')
};
new ShareView(options);
}
});
return RepoView;
});
<file_sep>/seahub/base/registration_urls.py
from django.conf.urls.defaults import *
from django.views.generic import TemplateView
from django.conf import settings
from registration.views import activate
from registration.views import register
from seahub.base.accounts import RegistrationForm, DetailedRegistrationForm
from seahub.base.generic import DirectTemplateView
form_class = DetailedRegistrationForm if settings.REQUIRE_DETAIL_ON_REGISTRATION \
else RegistrationForm
reg_dict = { 'backend': 'seahub.base.accounts.RegistrationBackend',
'form_class': form_class,
}
urlpatterns = patterns('',
url(r'^activate/complete/$',
TemplateView.as_view(template_name='registration/activation_complete.html'),
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get to the view;
# that way it can return a sensible "invalid key" message instead of a
# confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
activate,
{ 'backend': 'seahub.base.accounts.RegistrationBackend', },
name='registration_activate'),
(r'', include('registration.auth_urls')),
)
try:
from seahub.settings import CLOUD_MODE
except ImportError:
CLOUD_MODE = False
urlpatterns += patterns('',
url(r'^register/$',
register,
reg_dict,
name='registration_register'),
url(r'^register/complete/$',
DirectTemplateView.as_view(template_name='registration/registration_complete.html'),
name='registration_complete'),
)
<file_sep>/seahub/base/models.py
import datetime
import logging
import json
from django.db import models, IntegrityError
from django.utils import timezone
from pysearpc import SearpcError
from seaserv import seafile_api
from seahub.auth.signals import user_logged_in
from seahub.group.models import GroupMessage
from seahub.utils import calc_file_path_hash, within_time_range
from fields import LowerCaseCharField
# Get an instance of a logger
logger = logging.getLogger(__name__)
class UuidObjidMap(models.Model):
"""
Model used for store crocdoc uuid and file object id mapping.
"""
uuid = models.CharField(max_length=40)
obj_id = models.CharField(max_length=40, unique=True)
class FileDiscuss(models.Model):
"""
Model used to represents the relationship between group message and file/dir.
"""
group_message = models.ForeignKey(GroupMessage)
repo_id = models.CharField(max_length=36)
path = models.TextField()
path_hash = models.CharField(max_length=12, db_index=True)
def save(self, *args, **kwargs):
if not self.path_hash:
self.path_hash = calc_file_path_hash(self.path)
super(FileDiscuss, self).save(*args, **kwargs)
########## starred files
class StarredFile(object):
def format_path(self):
if self.path == "/":
return self.path
# strip leading slash
path = self.path[1:]
if path[-1:] == '/':
path = path[:-1]
return path.replace('/', ' / ')
def __init__(self, org_id, repo, file_id, path, is_dir, size):
# always 0 for non-org repo
self.org_id = org_id
self.repo = repo
self.file_id = file_id
self.path = path
self.formatted_path = self.format_path()
self.is_dir = is_dir
self.size = size
self.last_modified = None
if not is_dir:
self.name = path.split('/')[-1]
class UserStarredFilesManager(models.Manager):
def get_starred_files_by_username(self, username):
"""Get a user's starred files.
Arguments:
- `self`:
- `username`:
"""
starred_files = super(UserStarredFilesManager, self).filter(
email=username, org_id=-1)
ret = []
repo_cache = {}
for sfile in starred_files:
# repo still exists?
if repo_cache.has_key(sfile.repo_id):
repo = repo_cache[sfile.repo_id]
else:
try:
repo = seafile_api.get_repo(sfile.repo_id)
except SearpcError:
continue
if repo is not None:
repo_cache[sfile.repo_id] = repo
else:
sfile.delete()
continue
# file still exists?
file_id = ''
size = -1
if sfile.path != "/":
try:
file_id = seafile_api.get_file_id_by_path(sfile.repo_id,
sfile.path)
# size = seafile_api.get_file_size(file_id)
except SearpcError:
continue
if not file_id:
sfile.delete()
continue
f = StarredFile(sfile.org_id, repo, file_id, sfile.path,
sfile.is_dir, 0) # TODO: remove ``size`` from StarredFile
ret.append(f)
'''Calculate files last modification time'''
for sfile in ret:
if sfile.is_dir:
continue
try:
# get real path for sub repo
real_path = sfile.repo.origin_path + sfile.path if sfile.repo.origin_path else sfile.path
dirent = seafile_api.get_dirent_by_path(sfile.repo.store_id,
real_path)
if dirent:
sfile.last_modified = dirent.mtime
else:
sfile.last_modified = 0
except SearpcError as e:
logger.error(e)
sfile.last_modified = 0
ret.sort(lambda x, y: cmp(y.last_modified, x.last_modified))
return ret
class UserStarredFiles(models.Model):
"""Starred files are marked by users to get quick access to it on user
home page.
"""
email = models.EmailField(db_index=True)
org_id = models.IntegerField()
repo_id = models.CharField(max_length=36, db_index=True)
path = models.TextField()
is_dir = models.BooleanField()
objects = UserStarredFilesManager()
########## user/group modules
class UserEnabledModule(models.Model):
username = models.CharField(max_length=255, db_index=True)
module_name = models.CharField(max_length=20)
class GroupEnabledModule(models.Model):
group_id = models.CharField(max_length=10, db_index=True)
module_name = models.CharField(max_length=20)
########## misc
class UserLastLoginManager(models.Manager):
def get_by_username(self, username):
"""Return last login record for a user, delete duplicates if there are
duplicated records.
"""
try:
return self.get(username=username)
except UserLastLogin.DoesNotExist:
return None
except UserLastLogin.MultipleObjectsReturned:
dups = self.filter(username=username)
ret = dups[0]
for dup in dups[1:]:
dup.delete()
logger.warn('Delete duplicate user last login record: %s' % username)
return ret
class UserLastLogin(models.Model):
username = models.CharField(max_length=255, db_index=True)
last_login = models.DateTimeField(default=timezone.now)
objects = UserLastLoginManager()
def update_last_login(sender, user, **kwargs):
"""
A signal receiver which updates the last_login date for
the user logging in.
"""
user_last_login = UserLastLogin.objects.get_by_username(user.username)
if user_last_login is None:
user_last_login = UserLastLogin(username=user.username)
user_last_login.last_login = timezone.now()
user_last_login.save()
user_logged_in.connect(update_last_login)
class CommandsLastCheck(models.Model):
"""Record last check time for Django/custom commands.
"""
command_type = models.CharField(max_length=100)
last_check = models.DateTimeField()
###### Deprecated
class InnerPubMsg(models.Model):
"""
Model used for leave message on inner pub page.
"""
from_email = models.EmailField()
message = models.CharField(max_length=500)
timestamp = models.DateTimeField(default=datetime.datetime.now)
class Meta:
ordering = ['-timestamp']
class InnerPubMsgReply(models.Model):
reply_to = models.ForeignKey(InnerPubMsg)
from_email = models.EmailField()
message = models.CharField(max_length=150)
timestamp = models.DateTimeField(default=datetime.datetime.now)
class DeviceToken(models.Model):
"""
The iOS device token model.
"""
token = models.CharField(max_length=80)
user = LowerCaseCharField(max_length=255)
platform = LowerCaseCharField(max_length=32)
version = LowerCaseCharField(max_length=16)
pversion = LowerCaseCharField(max_length=16)
class Meta:
unique_together = (("token", "user"),)
def __unicode__(self):
return "/".join(self.user, self.token)
_CLIENT_LOGIN_TOKEN_EXPIRATION_SECONDS = 30
class ClientLoginTokenManager(models.Manager):
def get_username(self, tokenstr):
try:
token = super(ClientLoginTokenManager, self).get(token=tokenstr)
except ClientLoginToken.DoesNotExist:
return None
username = token.username
token.delete()
if not within_time_range(token.timestamp, timezone.now(),
_CLIENT_LOGIN_TOKEN_EXPIRATION_SECONDS):
return None
return username
class ClientLoginToken(models.Model):
# TODO: update sql/mysql.sql and sql/sqlite3.sql
token = models.CharField(max_length=32, primary_key=True)
username = models.CharField(max_length=255, db_index=True)
timestamp = models.DateTimeField(default=timezone.now)
objects = ClientLoginTokenManager()
def __unicode__(self):
return "/".join(self.username, self.token)
<file_sep>/Makefile
PROJECT=seahub
develop: setup-git
setup-git:
cd .git/hooks && ln -sf ../../hooks/* ./
dist: locale uglify statici18n collectstatic
locale:
@echo "--> Compile locales"
django-admin.py compilemessages
@echo ""
uglify:
@echo "--> Uglify JS files to static/scripts/dist"
rm -rf static/scripts/dist 2> /dev/null
r.js -o static/scripts/build.js
statici18n:
@echo "--> Generate JS locale files in static/scripts/i18n"
python manage.py compilejsi18n
collectstatic:
@echo "--> Collect django static files to media/assets"
rm -rf media/assets 2> /dev/null
python manage.py collectstatic --noinput
compressstatic:
@echo "--> Compress static files(css) to media/CACHE"
rm -rf media/CACHE 2> /dev/null
python manage.py compress
clean:
@echo '--> Cleaning media/static cache & dist'
rm -rf media/CACHE 2> /dev/null
rm -rf media/assets 2> /dev/null
rm -rf static/scripts/dist 2> /dev/null
@echo ""
.PHONY: develop setup-git dist locale uglify statici18n collectstatic compressstatic clean
<file_sep>/static/scripts/app/views/groups.js
define([
'jquery',
'underscore',
'backbone',
'common',
'app/collections/groups',
'app/views/group-item'
], function($, _, Backbone, Common, Groups, GroupItemView) {
'use strict';
var GroupsView = Backbone.View.extend({
el: '#groups',
initialize: function(options) {
this.groups = new Groups();
this.listenTo(this.groups, 'add', this.addOne);
this.listenTo(this.groups, 'reset', this.reset);
this.$sideTips = $('#groups-side-tips');
this.$loadingTip = this.$('.loading-tip');
this.$groupList = $('#group-list');
this.$emptyTip = this.$('.empty-tips');
this.$error = this.$('.error');
},
events: {
'click #add-group': 'addGroup'
},
addOne: function(group, collection, options) {
var view = new GroupItemView({
model: group
});
if (options.prepend) {
this.$groupList.prepend(view.render().el);
} else {
this.$groupList.append(view.render().el);
}
},
reset: function() {
this.$error.hide();
this.$loadingTip.hide();
if (this.groups.length) {
this.$emptyTip.hide();
this.$groupList.empty();
this.groups.each(this.addOne, this);
this.$groupList.show();
} else {
this.$emptyTip.show();
this.$groupList.hide();
}
},
render: function() {
this.$groupList.hide();
this.$emptyTip.hide();
this.$loadingTip.show();
var _this = this;
this.groups.fetch({
cache: false,
data: {'with_repos': 1}, // list repos of every group
reset: true,
success: function (collection, response, opts) {
},
error: function (collection, response, opts) {
_this.$loadingTip.hide();
var err_msg;
if (response.responseText) {
if (response['status'] == 401 || response['status'] == 403) {
err_msg = gettext("Permission error");
} else {
err_msg = gettext("Error");
}
} else {
err_msg = gettext('Please check the network.');
}
_this.$error.html(err_msg).show();
}
});
},
show: function() {
this.$sideTips.show();
this.$el.show();
this.render();
},
hide: function() {
this.$sideTips.hide();
this.$el.hide();
},
addGroup: function () {
var $form = $('#group-add-form');
$form.modal();
$('#simplemodal-container').css({'height':'auto'});
var groups = this.groups;
var _this = this;
$form.submit(function() {
var group_name = $.trim($('[name="group_name"]', $form).val());
if (!group_name) {
return false;
}
Common.disableButton($('[type="submit"]', $form));
groups.create({'group_name': group_name, 'repos':[]}, {
wait: true,
validate: true,
prepend: true, // show newly created group at the top
success: function() {
if (groups.length == 1) {
_this.reset();
}
},
error: function(collection, response, options) {
var err_msg;
if (response.responseText) {
err_msg = response.responseJSON.error_msg;
} else {
err_msg = gettext('Please check the network.');
}
Common.feedback(err_msg, 'error', Common.ERROR_TIMEOUT);
},
complete: function() {
Common.closeModal();
}
});
return false;
});
}
});
return GroupsView;
});
<file_sep>/seahub/share/models.py
import datetime
import logging
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.hashers import make_password, check_password
from seahub.base.fields import LowerCaseCharField
from seahub.utils import normalize_file_path, normalize_dir_path, gen_token
# Get an instance of a logger
logger = logging.getLogger(__name__)
class AnonymousShare(models.Model):
"""
Model used for sharing repo to unregistered email.
"""
repo_owner = LowerCaseCharField(max_length=255)
repo_id = models.CharField(max_length=36)
anonymous_email = LowerCaseCharField(max_length=255)
token = models.CharField(max_length=25, unique=True)
def _get_link_key(token, is_upload_link=False):
return 'visited_ufs_' + token if is_upload_link else \
'visited_fs_' + token
def set_share_link_access(request, token, is_upload_link=False):
"""Remember which shared download/upload link user can access without
providing password.
"""
if request.session:
link_key = _get_link_key(token, is_upload_link)
request.session[link_key] = True
else:
# should never reach here in normal case
logger.warn('Failed to remember shared link password, request.session'
' is None when set shared link access.')
def check_share_link_access(request, token, is_upload_link=False):
"""Check whether user can access shared download/upload link without
providing password.
"""
link_key = _get_link_key(token, is_upload_link)
if request.session.get(link_key, False):
return True
else:
return False
def check_share_link_common(request, sharelink, is_upload_link=False):
"""Check if user can view a share link
"""
msg = ''
if not sharelink.is_encrypted():
return (True, msg)
# if CAN access shared download/upload link without providing password
# return True
if check_share_link_access(request, sharelink.token, is_upload_link):
return (True, msg)
if request.method != 'POST':
return (False, msg)
password = request.POST.get('password', None)
if not password:
msg = _("Password can\'t be empty")
return (False, msg)
if check_password(password, sharelink.password):
set_share_link_access(request, sharelink.token, is_upload_link)
return (True, msg)
else:
msg = _("Please enter a correct password.")
return (False, msg)
class FileShareManager(models.Manager):
def _add_file_share(self, username, repo_id, path, s_type,
password=None, expire_date=None):
if password is not None:
password_enc = make_password(password)
else:
password_enc = None
token = gen_token(max_length=10)
fs = super(FileShareManager, self).create(
username=username, repo_id=repo_id, path=path, token=token,
s_type=s_type, password=<PASSWORD>, expire_date=expire_date)
fs.save()
return fs
def _get_file_share_by_path(self, username, repo_id, path):
fs = list(super(FileShareManager, self).filter(repo_id=repo_id).filter(
username=username).filter(path=path))
if len(fs) > 0:
return fs[0]
else:
return None
def _get_valid_file_share_by_token(self, token):
"""Return share link that exists and not expire, otherwise none.
"""
try:
fs = self.get(token=token)
except self.model.DoesNotExist:
return None
if fs.expire_date is None:
return fs
else:
if timezone.now() > fs.expire_date:
return None
else:
return fs
########## public methods ##########
def create_file_link(self, username, repo_id, path, password=None,
expire_date=None):
"""Create download link for file.
"""
path = normalize_file_path(path)
return self._add_file_share(username, repo_id, path, 'f', password,
expire_date)
def get_file_link_by_path(self, username, repo_id, path):
path = normalize_file_path(path)
return self._get_file_share_by_path(username, repo_id, path)
def get_valid_file_link_by_token(self, token):
return self._get_valid_file_share_by_token(token)
def create_dir_link(self, username, repo_id, path, password=<PASSWORD>,
expire_date=None):
"""Create download link for directory.
"""
path = normalize_dir_path(path)
return self._add_file_share(username, repo_id, path, 'd', password,
expire_date)
def get_dir_link_by_path(self, username, repo_id, path):
path = normalize_dir_path(path)
return self._get_file_share_by_path(username, repo_id, path)
def get_valid_dir_link_by_token(self, token):
return self._get_valid_file_share_by_token(token)
class FileShare(models.Model):
"""
Model used for file or dir shared link.
"""
username = LowerCaseCharField(max_length=255, db_index=True)
repo_id = models.CharField(max_length=36, db_index=True)
path = models.TextField()
token = models.CharField(max_length=10, unique=True)
ctime = models.DateTimeField(default=datetime.datetime.now)
view_cnt = models.IntegerField(default=0)
s_type = models.CharField(max_length=2, db_index=True, default='f') # `f` or `d`
password = models.CharField(max_length=128, null=True)
expire_date = models.DateTimeField(null=True)
objects = FileShareManager()
def is_file_share_link(self):
return True if self.s_type == 'f' else False
def is_dir_share_link(self):
return False if self.is_file_share_link() else True
def is_encrypted(self):
return True if self.password is not None else False
def is_expired(self):
if self.expire_date is not None and timezone.now() > self.expire_date:
return True
else:
return False
def is_owner(self, owner):
return owner == self.username
class OrgFileShareManager(models.Manager):
def set_org_file_share(self, org_id, file_share):
"""Set a share link as org share link.
Arguments:
- `org_id`:
- `file_share`:
"""
ofs = self.model(org_id=org_id, file_share=file_share)
ofs.save(using=self._db)
return ofs
class OrgFileShare(models.Model):
"""
Model used for organization file or dir shared link.
"""
org_id = models.IntegerField(db_index=True)
file_share = models.OneToOneField(FileShare)
objects = OrgFileShareManager()
objects = OrgFileShareManager()
class UploadLinkShareManager(models.Manager):
def _get_upload_link_by_path(self, username, repo_id, path):
ufs = list(super(UploadLinkShareManager, self).filter(repo_id=repo_id).filter(
username=username).filter(path=path))
if len(ufs) > 0:
return ufs[0]
else:
return None
def get_upload_link_by_path(self, username, repo_id, path):
path = normalize_dir_path(path)
return self._get_upload_link_by_path(username, repo_id, path)
def create_upload_link_share(self, username, repo_id, path,
password=None, expire_date=None):
path = normalize_dir_path(path)
token = gen_token(max_length=10)
if password is not None:
password_enc = make_password(password)
else:
password_enc = None
uls = super(UploadLinkShareManager, self).create(
username=username, repo_id=repo_id, path=path, token=token,
password=password_enc, expire_date=expire_date)
uls.save()
return uls
def get_valid_upload_link_by_token(self, token):
"""Return upload link that exists and not expire, otherwise none.
"""
try:
fs = self.get(token=token)
except self.model.DoesNotExist:
return None
if fs.expire_date is None:
return fs
else:
if timezone.now() > fs.expire_date:
return None
else:
return fs
class UploadLinkShare(models.Model):
"""
Model used for shared upload link.
"""
username = LowerCaseCharField(max_length=255, db_index=True)
repo_id = models.CharField(max_length=36, db_index=True)
path = models.TextField()
token = models.CharField(max_length=10, unique=True)
ctime = models.DateTimeField(default=datetime.datetime.now)
view_cnt = models.IntegerField(default=0)
password = models.CharField(max_length=128, null=True)
expire_date = models.DateTimeField(null=True)
objects = UploadLinkShareManager()
def is_encrypted(self):
return True if self.password is not None else False
def is_owner(self, owner):
return owner == self.username
class PrivateFileDirShareManager(models.Manager):
def add_private_file_share(self, from_user, to_user, repo_id, path, perm):
"""
"""
path = normalize_file_path(path)
token = gen_token(max_length=10)
pfs = self.model(from_user=from_user, to_user=to_user, repo_id=repo_id,
path=path, s_type='f', token=token, permission=perm)
pfs.save(using=self._db)
return pfs
def add_read_only_priv_file_share(self, from_user, to_user, repo_id, path):
"""
"""
return self.add_private_file_share(from_user, to_user, repo_id,
path, 'r')
def get_private_share_in_file(self, username, repo_id, path):
"""Get a file that private shared to ``username``.
"""
path = normalize_file_path(path)
ret = super(PrivateFileDirShareManager, self).filter(
to_user=username, repo_id=repo_id, path=path, s_type='f')
return ret[0] if len(ret) > 0 else None
def add_private_dir_share(self, from_user, to_user, repo_id, path, perm):
"""
"""
path = normalize_dir_path(path)
token = gen_token(max_length=10)
pfs = self.model(from_user=from_user, to_user=to_user, repo_id=repo_id,
path=path, s_type='d', token=token, permission=perm)
pfs.save(using=self._db)
return pfs
def get_private_share_in_dir(self, username, repo_id, path):
"""Get a directory that private shared to ``username``.
"""
path = normalize_dir_path(path)
ret = super(PrivateFileDirShareManager, self).filter(
to_user=username, repo_id=repo_id, path=path, s_type='d')
return ret[0] if len(ret) > 0 else None
def get_priv_file_dir_share_by_token(self, token):
return super(PrivateFileDirShareManager, self).get(token=token)
def delete_private_file_dir_share(self, from_user, to_user, repo_id, path):
"""
"""
super(PrivateFileDirShareManager, self).filter(
from_user=from_user, to_user=to_user, repo_id=repo_id,
path=path).delete()
def list_private_share_out_by_user(self, from_user):
"""List files/directories private shared from ``from_user``.
"""
return super(PrivateFileDirShareManager, self).filter(
from_user=from_user)
def list_private_share_in_by_user(self, to_user):
"""List files/directories private shared to ``to_user``.
"""
return super(PrivateFileDirShareManager, self).filter(
to_user=to_user)
def list_private_share_in_dirs_by_user_and_repo(self, to_user, repo_id):
"""List directories private shared to ``to_user`` base on ``repo_id``.
"""
return super(PrivateFileDirShareManager, self).filter(
to_user=to_user, repo_id=repo_id, s_type='d')
class PrivateFileDirShare(models.Model):
from_user = LowerCaseCharField(max_length=255, db_index=True)
to_user = LowerCaseCharField(max_length=255, db_index=True)
repo_id = models.CharField(max_length=36, db_index=True)
path = models.TextField()
token = models.CharField(max_length=10, unique=True)
permission = models.CharField(max_length=5) # `r` or `rw`
s_type = models.CharField(max_length=5, default='f') # `f` or `d`
objects = PrivateFileDirShareManager()
###### signal handlers
from django.dispatch import receiver
from seahub.signals import repo_deleted
@receiver(repo_deleted)
def remove_share_links(sender, **kwargs):
repo_id = kwargs['repo_id']
FileShare.objects.filter(repo_id=repo_id).delete()
UploadLinkShare.objects.filter(repo_id=repo_id).delete()
<file_sep>/tests/api/test_repo.py
"""seahub/api2/views.py::Repo api tests.
"""
import json
from django.core.urlresolvers import reverse
from seahub.share.models import FileShare, UploadLinkShare
from seahub.test_utils import BaseTestCase
class RepoTest(BaseTestCase):
def test_can_fetch(self):
self.login_as(self.user)
resp = self.client.get(reverse("api2-repo", args=[self.repo.id]))
json_resp = json.loads(resp.content)
self.assertFalse(json_resp['encrypted'])
self.assertIsNotNone(json_resp['mtime'])
self.assertIsNotNone(json_resp['owner'])
self.assertIsNotNone(json_resp['id'])
self.assertIsNotNone(json_resp['size'])
self.assertIsNotNone(json_resp['name'])
self.assertIsNotNone(json_resp['root'])
self.assertIsNotNone(json_resp['desc'])
self.assertIsNotNone(json_resp['type'])
def test_can_delete(self):
self.login_as(self.user)
resp = self.client.delete(
reverse('api2-repo', args=[self.repo.id])
)
self.assertEqual(200, resp.status_code)
def test_cleaning_stuff_when_delete(self):
self.login_as(self.user)
# create download and upload links
FileShare.objects.create_dir_link(self.user.username,
self.repo.id, '/', None)
FileShare.objects.create_file_link(self.user.username,
self.repo.id, self.file)
UploadLinkShare.objects.create_upload_link_share(self.user.username,
self.repo.id, '/')
assert len(FileShare.objects.all()) == 2
assert len(UploadLinkShare.objects.all()) == 1
self.client.delete(
reverse('api2-repo', args=[self.repo.id])
)
assert len(FileShare.objects.all()) == 0
assert len(UploadLinkShare.objects.all()) == 0
<file_sep>/seahub/api2/utils.py
# encoding: utf-8
# Utility functions for api2
import os
import time
import json
import re
from collections import defaultdict
from functools import wraps
from seahub import settings
from django.core.paginator import EmptyPage, InvalidPage
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework import status, serializers
from seaserv import seafile_api, get_commits, server_repo_size, \
get_personal_groups_by_user, is_group_user, get_group, seafserv_threaded_rpc
from pysearpc import SearpcError
from seahub.base.accounts import User
from seahub.base.templatetags.seahub_tags import email2nickname, \
translate_seahub_time, file_icon_filter
from seahub.contacts.models import Contact
from seahub.group.models import GroupMessage, MessageReply, \
MessageAttachment, PublicGroup
from seahub.group.views import is_group_staff
from seahub.message.models import UserMessage, UserMsgAttachment
from seahub.notifications.models import UserNotification
from seahub.utils import api_convert_desc_link, get_file_type_and_ext, \
gen_file_get_url
from seahub.utils.paginator import Paginator
from seahub.utils.file_types import IMAGE
from seahub.api2.models import Token, TokenV2, DESKTOP_PLATFORMS
def api_error(code, msg):
err_resp = {'error_msg': msg}
return Response(err_resp, status=code)
def is_repo_writable(repo_id, username):
"""Check whether a user has write permission to a repo.
Arguments:
- `repo_id`:
- `username`:
"""
if seafile_api.check_repo_access_permission(repo_id, username) == 'rw':
return True
else:
return False
def is_repo_accessible(repo_id, username):
"""Check whether a user can read or write to a repo.
Arguments:
- `repo_id`:
- `username`:
"""
if seafile_api.check_repo_access_permission(repo_id, username) is None:
return False
else:
return True
def get_file_size(store_id, repo_version, file_id):
size = seafile_api.get_file_size(store_id, repo_version, file_id)
return size if size else 0
def prepare_starred_files(files):
array = []
for f in files:
sfile = {'org' : f.org_id,
'repo' : f.repo.id,
'repo_id' : f.repo.id,
'repo_name' : f.repo.name,
'path' : f.path,
'icon_path' : file_icon_filter(f.path),
'file_name' : os.path.basename(f.path),
'mtime' : f.last_modified,
'mtime_relative': translate_seahub_time(f.last_modified),
'dir' : f.is_dir
}
if not f.is_dir:
try:
file_id = seafile_api.get_file_id_by_path(f.repo.id, f.path)
sfile['oid'] = file_id
sfile['size'] = get_file_size(f.repo.store_id, f.repo.version, file_id)
except SearpcError, e:
pass
array.append(sfile)
return array
def get_groups(email):
group_json = []
joined_groups = get_personal_groups_by_user(email)
grpmsgs = {}
for g in joined_groups:
grpmsgs[g.id] = 0
notes = UserNotification.objects.get_user_notifications(email, seen=False)
replynum = 0
for n in notes:
if n.is_group_msg():
try:
gid = n.group_message_detail_to_dict().get('group_id')
except UserNotification.InvalidDetailError:
continue
if gid not in grpmsgs:
continue
grpmsgs[gid] = grpmsgs[gid] + 1
elif n.is_grpmsg_reply():
replynum = replynum + 1
for g in joined_groups:
msg = GroupMessage.objects.filter(group_id=g.id).order_by('-timestamp')[:1]
mtime = 0
if len(msg) >= 1:
mtime = get_timestamp(msg[0].timestamp)
group = {
"id":g.id,
"name":g.group_name,
"creator":g.creator_name,
"ctime":g.timestamp,
"mtime":mtime,
"msgnum":grpmsgs[g.id],
}
group_json.append(group)
return group_json, replynum
def get_msg_group_id(msg_id):
try:
msg = GroupMessage.objects.get(id=msg_id)
except GroupMessage.DoesNotExist:
return None
return msg.group_id
def get_msg_group_id_and_last_reply(msg_id):
lastreply = None
try:
msg = GroupMessage.objects.get(id=msg_id)
except GroupMessage.DoesNotExist:
return None, None
replies = MessageReply.objects.filter(reply_to=msg).order_by('-timestamp')[:1]
if len(replies) >= 1:
lastreply = replies[0].message
return msg.group_id, lastreply
def get_group_and_contacts(email):
group_json = []
contacts_json = []
replies_json = []
gmsgnums = {}
umsgnums = {}
replies = {}
gmsgnum = umsgnum = replynum = 0
contacts = [c.contact_email for c in Contact.objects.filter(user_email=email)]
joined_groups = get_personal_groups_by_user(email)
notes = UserNotification.objects.get_user_notifications(email, seen=False)
for n in notes:
if n.is_group_msg():
try:
gid = n.group_message_detail_to_dict().get('group_id')
except UserNotification.InvalidDetailError:
continue
gmsgnums[gid] = gmsgnums.get(gid, 0) + 1
elif n.is_grpmsg_reply():
d = n.grpmsg_reply_detail_to_dict()
msg_id = d['msg_id']
if replies.get(msg_id, None):
replies[msg_id] = replies[msg_id] + 1
else:
replies[msg_id] = 1
d['mtime'] = get_timestamp(n.timestamp)
d['name'] = email2nickname(d['reply_from'])
d['group_id'], d['lastmsg'] = get_msg_group_id_and_last_reply(msg_id)
replies_json.append(d)
replynum = replynum + 1
elif n.is_user_message():
msg_from = n.user_message_detail_to_dict()['msg_from']
if msg_from not in contacts:
contacts.append(msg_from)
umsgnums[n.detail] = umsgnums.get(msg_from, 0) + 1
for r in replies_json:
r['msgnum'] = replies[r['msg_id']]
for g in joined_groups:
msg = GroupMessage.objects.filter(group_id=g.id).order_by('-timestamp')[:1]
mtime = 0
lastmsg = None
if len(msg) >= 1:
mtime = get_timestamp(msg[0].timestamp)
lastmsg = msg[0].message
group = {
"id":g.id,
"name":g.group_name,
"creator":g.creator_name,
"ctime":g.timestamp,
"mtime":mtime,
"lastmsg":lastmsg,
"msgnum":gmsgnums.get(g.id, 0),
}
gmsgnum = gmsgnum + gmsgnums.get(g.id, 0)
group_json.append(group)
for contact in contacts:
msg = UserMessage.objects.get_messages_between_users(
contact, email).order_by('-timestamp')[:1]
mtime = 0
lastmsg = None
if len(msg) >= 1:
mtime = get_timestamp(msg[0].timestamp)
lastmsg = msg[0].message
c = {
'email' : contact,
'name' : email2nickname(contact),
"mtime" : mtime,
"lastmsg":lastmsg,
"msgnum" : umsgnums.get(contact, 0),
}
umsgnum = umsgnum + umsgnums.get(contact, 0)
contacts_json.append(c)
contacts_json.sort(key=lambda x: x["mtime"], reverse=True)
return contacts_json, umsgnum, group_json, gmsgnum, replies_json, replynum
def prepare_events(event_groups):
for g in event_groups:
for e in g["events"]:
if e.etype != "repo-delete":
e.link = "api://repos/%s" % e.repo_id
if e.etype == "repo-update":
api_convert_desc_link(e)
def get_group_msgs(groupid, page, username):
# Show 15 group messages per page.
paginator = Paginator(GroupMessage.objects.filter(
group_id=groupid).order_by('-timestamp'), 15)
# If page request (9999) is out of range, return None
try:
group_msgs = paginator.page(page)
except (EmptyPage, InvalidPage):
return None
# Force evaluate queryset to fix some database error for mysql.
group_msgs.object_list = list(group_msgs.object_list)
attachments = MessageAttachment.objects.filter(group_message__in=group_msgs.object_list)
msg_replies = MessageReply.objects.filter(reply_to__in=group_msgs.object_list)
reply_to_list = [ r.reply_to_id for r in msg_replies ]
for msg in group_msgs.object_list:
msg.reply_cnt = reply_to_list.count(msg.id)
msg.replies = []
for r in msg_replies:
if msg.id == r.reply_to_id:
msg.replies.append(r)
msg.replies = msg.replies[-3:]
for att in attachments:
if att.group_message_id != msg.id:
continue
# Attachment name is file name or directory name.
# If is top directory, use repo name instead.
path = att.path
if path == '/':
repo = seafile_api.get_repo(att.repo_id)
if not repo:
# TODO: what should we do here, tell user the repo
# is no longer exists?
continue
att.name = repo.name
else:
path = path.rstrip('/') # cut out last '/' if possible
att.name = os.path.basename(path)
# Load to discuss page if attachment is a image and from recommend.
if att.attach_type == 'file' and att.src == 'recommend':
att.filetype, att.fileext = get_file_type_and_ext(att.name)
if att.filetype == IMAGE:
att.obj_id = seafile_api.get_file_id_by_path(att.repo_id, path)
if not att.obj_id:
att.err = 'File does not exist'
else:
att.token = seafile_api.get_fileserver_access_token(
att.repo_id, att.obj_id, 'view', username)
att.img_url = gen_file_get_url(att.token, att.name)
msg.attachment = att
return group_msgs
def get_timestamp(msgtimestamp):
if not msgtimestamp:
return 0
timestamp = int(time.mktime(msgtimestamp.timetuple()))
return timestamp
def group_msg_to_json(msg, get_all_replies):
ret = {
'from_email': msg.from_email,
'nickname': email2nickname(msg.from_email),
'timestamp': get_timestamp(msg.timestamp),
'msg': msg.message,
'msgid': msg.id,
}
atts_json = []
atts = MessageAttachment.objects.filter(group_message_id=msg.id)
for att in atts:
att_json = {
'path': att.path,
'repo': att.repo_id,
'type': att.attach_type,
'src': att.src,
}
atts_json.append(att_json)
if len(atts_json) > 0:
ret['atts'] = atts_json
reply_list = MessageReply.objects.filter(reply_to=msg)
msg.reply_cnt = reply_list.count()
if not get_all_replies and msg.reply_cnt > 3:
msg.replies = reply_list[msg.reply_cnt - 3:]
else:
msg.replies = reply_list
replies = []
for reply in msg.replies:
r = {
'from_email' : reply.from_email,
'nickname' : email2nickname(reply.from_email),
'timestamp' : get_timestamp(reply.timestamp),
'msg' : reply.message,
'msgid' : reply.id,
}
replies.append(r)
ret['reply_cnt'] = msg.reply_cnt
ret['replies'] = replies
return ret
def get_group_msgs_json(groupid, page, username):
# Show 15 group messages per page.
paginator = Paginator(GroupMessage.objects.filter(
group_id=groupid).order_by('-timestamp'), 15)
# If page request (9999) is out of range, return None
try:
group_msgs = paginator.page(page)
except (EmptyPage, InvalidPage):
return None, -1
if group_msgs.has_next():
next_page = group_msgs.next_page_number()
else:
next_page = -1
group_msgs.object_list = list(group_msgs.object_list)
msgs = [ group_msg_to_json(msg, True) for msg in group_msgs.object_list ]
return msgs, next_page
def get_group_message_json(group_id, msg_id, get_all_replies):
try:
msg = GroupMessage.objects.get(id=msg_id)
except GroupMessage.DoesNotExist:
return None
if group_id and group_id != msg.group_id:
return None
return group_msg_to_json(msg, get_all_replies)
def get_person_msgs(to_email, page, username):
# Show 15 group messages per page.
paginator = Paginator(UserMessage.objects.get_messages_between_users(username, to_email).order_by('-timestamp'), 15)
# If page request (9999) is out of range, return None
try:
person_msgs = paginator.page(page)
except (EmptyPage, InvalidPage):
return None
# Force evaluate queryset to fix some database error for mysql.
person_msgs.object_list = list(person_msgs.object_list)
attachments = UserMsgAttachment.objects.list_attachments_by_user_msgs(person_msgs.object_list)
for msg in person_msgs.object_list:
msg.attachments = []
for att in attachments:
if att.user_msg != msg:
continue
pfds = att.priv_file_dir_share
if pfds is None: # in case that this attachment is unshared.
continue
att.repo_id = pfds.repo_id
att.path = pfds.path
att.name = os.path.basename(pfds.path.rstrip('/'))
att.token = pfds.token
msg.attachments.append(att)
return person_msgs
def get_email(id_or_email):
try:
uid = int(id_or_email)
try:
user = User.objects.get(id=uid)
except User.DoesNotExist:
user = None
if not user:
return None
to_email = user.email
except ValueError:
to_email = id_or_email
return to_email
def api_group_check(func):
"""
Decorator for initial group permission check tasks
un-login user & group not pub --> login page
un-login user & group pub --> view_perm = "pub"
login user & non group member & group not pub --> public info page
login user & non group member & group pub --> view_perm = "pub"
group member --> view_perm = "joined"
sys admin --> view_perm = "sys_admin"
"""
def _decorated(view, request, group_id, *args, **kwargs):
group_id_int = int(group_id) # Checked by URL Conf
group = get_group(group_id_int)
if not group:
return api_error(status.HTTP_404_NOT_FOUND, 'Group not found.')
group.is_staff = False
if PublicGroup.objects.filter(group_id=group.id):
group.is_pub = True
else:
group.is_pub = False
joined = is_group_user(group_id_int, request.user.username)
if joined:
group.view_perm = "joined"
group.is_staff = is_group_staff(group, request.user)
return func(view, request, group, *args, **kwargs)
if request.user.is_staff:
# viewed by system admin
group.view_perm = "sys_admin"
return func(view, request, group, *args, **kwargs)
if group.is_pub:
group.view_perm = "pub"
return func(view, request, group, *args, **kwargs)
# Return group public info page.
return api_error(status.HTTP_403_FORBIDDEN, 'Forbid to access this group.')
return _decorated
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR', '')
return ip
def get_diff_details(repo_id, commit1, commit2):
result = defaultdict(list)
diff_result = seafserv_threaded_rpc.get_diff(repo_id, commit1, commit2)
if not diff_result:
return result
for d in diff_result:
if d.status == 'add':
result['added_files'].append(d.name)
elif d.status == 'del':
result['deleted_files'].append(d.name)
elif d.status == 'mov':
result['renamed_files'].extend((d.name, d.new_name))
elif d.status == 'mod':
result['modified_files'].append(d.name)
elif d.status == 'newdir':
result['added_dirs'].append(d.name)
elif d.status == 'deldir':
result['deleted_dirs'].append(d.name)
return result
JSON_CONTENT_TYPE = 'application/json; charset=utf-8'
def json_response(func):
@wraps(func)
def wrapped(*a, **kw):
result = func(*a, **kw)
if isinstance(result, HttpResponse):
return result
else:
return HttpResponse(json.dumps(result), status=200,
content_type=JSON_CONTENT_TYPE)
return wrapped
def get_token_v1(username):
token, _ = Token.objects.get_or_create(user=username)
return token
_ANDROID_DEVICE_ID_PATTERN = re.compile('^[a-f0-9]{1,16}$')
def get_token_v2(request, username, platform, device_id, device_name,
client_version, platform_version):
if platform in DESKTOP_PLATFORMS:
# desktop device id is the peer id, so it must be 40 chars
if len(device_id) != 40:
raise serializers.ValidationError('invalid device id')
elif platform == 'android':
# See http://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID
# android device id is the 64bit secure id, so it must be 16 chars in hex representation
# but some user reports their device ids are 14 or 15 chars long. So we relax the validation.
if not _ANDROID_DEVICE_ID_PATTERN.match(device_id.lower()):
raise serializers.ValidationError('invalid device id')
elif platform == 'ios':
if len(device_id) != 36:
raise serializers.ValidationError('invalid device id')
else:
raise serializers.ValidationError('invalid platform')
return TokenV2.objects.get_or_create_token(
username, platform, device_id, device_name,
client_version, platform_version, get_client_ip(request))
def to_python_boolean(string):
"""Convert a string to boolean.
"""
string = string.lower()
if string in ('t', 'true', '1'):
return True
if string in ('f', 'false', '0'):
return False
raise ValueError("Invalid boolean value: '%s'" % string)
def is_seafile_pro():
return any(['seahub_extra' in app for app in settings.INSTALLED_APPS])
<file_sep>/sql/sqlite3.sql
PRAGMA foreign_keys=OFF;
CREATE TABLE "django_content_type" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(100) NOT NULL,
"app_label" varchar(100) NOT NULL,
"model" varchar(100) NOT NULL,
UNIQUE ("app_label", "model")
);
INSERT INTO "django_content_type" VALUES(1,'content type','contenttypes','contenttype');
INSERT INTO "django_content_type" VALUES(2,'session','sessions','session');
INSERT INTO "django_content_type" VALUES(3,'registration profile','registration','registrationprofile');
INSERT INTO "django_content_type" VALUES(4,'captcha store','captcha','captchastore');
INSERT INTO "django_content_type" VALUES(5,'constance','database','constance');
INSERT INTO "django_content_type" VALUES(6,'token','api2','token');
INSERT INTO "django_content_type" VALUES(7,'token v2','api2','tokenv2');
INSERT INTO "django_content_type" VALUES(8,'avatar','avatar','avatar');
INSERT INTO "django_content_type" VALUES(9,'group avatar','avatar','groupavatar');
INSERT INTO "django_content_type" VALUES(10,'group enabled module','base','groupenabledmodule');
INSERT INTO "django_content_type" VALUES(11,'client login token','base','clientlogintoken');
INSERT INTO "django_content_type" VALUES(12,'uuid objid map','base','uuidobjidmap');
INSERT INTO "django_content_type" VALUES(13,'user enabled module','base','userenabledmodule');
INSERT INTO "django_content_type" VALUES(14,'file discuss','base','filediscuss');
INSERT INTO "django_content_type" VALUES(15,'device token','base','devicetoken');
INSERT INTO "django_content_type" VALUES(16,'commands last check','base','commandslastcheck');
INSERT INTO "django_content_type" VALUES(17,'inner pub msg','base','innerpubmsg');
INSERT INTO "django_content_type" VALUES(18,'inner pub msg reply','base','innerpubmsgreply');
INSERT INTO "django_content_type" VALUES(19,'user last login','base','userlastlogin');
INSERT INTO "django_content_type" VALUES(20,'user starred files','base','userstarredfiles');
INSERT INTO "django_content_type" VALUES(21,'contact','contacts','contact');
INSERT INTO "django_content_type" VALUES(22,'personal wiki','wiki','personalwiki');
INSERT INTO "django_content_type" VALUES(23,'group wiki','wiki','groupwiki');
INSERT INTO "django_content_type" VALUES(24,'public group','group','publicgroup');
INSERT INTO "django_content_type" VALUES(25,'group message','group','groupmessage');
INSERT INTO "django_content_type" VALUES(26,'message attachment','group','messageattachment');
INSERT INTO "django_content_type" VALUES(27,'message reply','group','messagereply');
INSERT INTO "django_content_type" VALUES(28,'user msg attachment','message','usermsgattachment');
INSERT INTO "django_content_type" VALUES(29,'user msg last check','message','usermsglastcheck');
INSERT INTO "django_content_type" VALUES(30,'user message','message','usermessage');
INSERT INTO "django_content_type" VALUES(31,'notification','notifications','notification');
INSERT INTO "django_content_type" VALUES(32,'user notification','notifications','usernotification');
INSERT INTO "django_content_type" VALUES(33,'user options','options','useroptions');
INSERT INTO "django_content_type" VALUES(34,'profile','profile','profile');
INSERT INTO "django_content_type" VALUES(35,'detailed profile','profile','detailedprofile');
INSERT INTO "django_content_type" VALUES(36,'private file dir share','share','privatefiledirshare');
INSERT INTO "django_content_type" VALUES(37,'upload link share','share','uploadlinkshare');
INSERT INTO "django_content_type" VALUES(38,'file share','share','fileshare');
INSERT INTO "django_content_type" VALUES(39,'anonymous share','share','anonymousshare');
INSERT INTO "django_content_type" VALUES(40,'org file share','share','orgfileshare');
INSERT INTO "django_content_type" VALUES(41,'group public file','pubfile','grouppublicfile');
INSERT INTO "django_content_type" VALUES(42,'user login log','sysadmin_extra','userloginlog');
INSERT INTO "django_content_type" VALUES(43,'org member quota','organizations','orgmemberquota');
CREATE TABLE "django_session" (
"session_key" varchar(40) NOT NULL PRIMARY KEY,
"session_data" text NOT NULL,
"expire_date" datetime NOT NULL
);
CREATE TABLE "registration_registrationprofile" (
"id" integer NOT NULL PRIMARY KEY,
"emailuser_id" integer NOT NULL,
"activation_key" varchar(40) NOT NULL
);
CREATE TABLE "captcha_captchastore" (
"id" integer NOT NULL PRIMARY KEY,
"challenge" varchar(32) NOT NULL,
"response" varchar(32) NOT NULL,
"hashkey" varchar(40) NOT NULL UNIQUE,
"expiration" datetime NOT NULL
);
CREATE TABLE "constance_config" (
"id" integer NOT NULL PRIMARY KEY,
"key" varchar(255) NOT NULL UNIQUE,
"value" text NOT NULL
);
CREATE TABLE "api2_token" (
"key" varchar(40) NOT NULL PRIMARY KEY,
"user" varchar(255) NOT NULL UNIQUE,
"created" datetime NOT NULL
);
CREATE TABLE "api2_tokenv2" (
"key" varchar(40) NOT NULL PRIMARY KEY,
"user" varchar(255) NOT NULL,
"platform" varchar(32) NOT NULL,
"device_id" varchar(40) NOT NULL,
"device_name" varchar(40) NOT NULL,
"platform_version" varchar(16) NOT NULL,
"client_version" varchar(16) NOT NULL,
"last_accessed" datetime NOT NULL,
"last_login_ip" char(39),
UNIQUE ("user", "platform", "device_id")
);
CREATE TABLE "avatar_avatar" (
"id" integer NOT NULL PRIMARY KEY,
"emailuser" varchar(255) NOT NULL,
"primary" bool NOT NULL,
"avatar" varchar(1024) NOT NULL,
"date_uploaded" datetime NOT NULL
);
CREATE TABLE "avatar_groupavatar" (
"id" integer NOT NULL PRIMARY KEY,
"group_id" varchar(255) NOT NULL,
"avatar" varchar(1024) NOT NULL,
"date_uploaded" datetime NOT NULL
);
CREATE TABLE "base_uuidobjidmap" (
"id" integer NOT NULL PRIMARY KEY,
"uuid" varchar(40) NOT NULL,
"obj_id" varchar(40) NOT NULL UNIQUE
);
CREATE TABLE "base_filediscuss" (
"id" integer NOT NULL PRIMARY KEY,
"group_message_id" integer NOT NULL,
"repo_id" varchar(36) NOT NULL,
"path" text NOT NULL,
"path_hash" varchar(12) NOT NULL
);
CREATE TABLE "base_userstarredfiles" (
"id" integer NOT NULL PRIMARY KEY,
"email" varchar(75) NOT NULL,
"org_id" integer NOT NULL,
"repo_id" varchar(36) NOT NULL,
"path" text NOT NULL,
"is_dir" bool NOT NULL
);
CREATE TABLE "base_userenabledmodule" (
"id" integer NOT NULL PRIMARY KEY,
"username" varchar(255) NOT NULL,
"module_name" varchar(20) NOT NULL
);
CREATE TABLE "base_groupenabledmodule" (
"id" integer NOT NULL PRIMARY KEY,
"group_id" varchar(10) NOT NULL,
"module_name" varchar(20) NOT NULL
);
CREATE TABLE "base_userlastlogin" (
"id" integer NOT NULL PRIMARY KEY,
"username" varchar(255) NOT NULL,
"last_login" datetime NOT NULL
);
CREATE TABLE "base_commandslastcheck" (
"id" integer NOT NULL PRIMARY KEY,
"command_type" varchar(100) NOT NULL,
"last_check" datetime NOT NULL
);
CREATE TABLE "base_innerpubmsg" (
"id" integer NOT NULL PRIMARY KEY,
"from_email" varchar(75) NOT NULL,
"message" varchar(500) NOT NULL,
"timestamp" datetime NOT NULL
);
CREATE TABLE "base_innerpubmsgreply" (
"id" integer NOT NULL PRIMARY KEY,
"reply_to_id" integer NOT NULL REFERENCES "base_innerpubmsg" ("id"),
"from_email" varchar(75) NOT NULL,
"message" varchar(150) NOT NULL,
"timestamp" datetime NOT NULL
);
CREATE TABLE "base_devicetoken" (
"id" integer NOT NULL PRIMARY KEY,
"token" varchar(80) NOT NULL,
"user" varchar(255) NOT NULL,
"platform" varchar(32) NOT NULL,
"version" varchar(16) NOT NULL,
"pversion" varchar(16) NOT NULL,
UNIQUE ("token", "user")
);
CREATE TABLE "base_clientlogintoken" (
"token" varchar(32) NOT NULL PRIMARY KEY,
"username" varchar(255) NOT NULL,
"timestamp" datetime NOT NULL
);
CREATE TABLE "contacts_contact" (
"id" integer NOT NULL PRIMARY KEY,
"user_email" varchar(255) NOT NULL,
"contact_email" varchar(255) NOT NULL,
"contact_name" varchar(255),
"note" varchar(255)
);
CREATE TABLE "wiki_personalwiki" (
"id" integer NOT NULL PRIMARY KEY,
"username" varchar(255) NOT NULL UNIQUE,
"repo_id" varchar(36) NOT NULL
);
CREATE TABLE "wiki_groupwiki" (
"id" integer NOT NULL PRIMARY KEY,
"group_id" integer NOT NULL UNIQUE,
"repo_id" varchar(36) NOT NULL
);
CREATE TABLE "group_groupmessage" (
"id" integer NOT NULL PRIMARY KEY,
"group_id" integer NOT NULL,
"from_email" varchar(255) NOT NULL,
"message" varchar(2048) NOT NULL,
"timestamp" datetime NOT NULL
);
CREATE TABLE "group_messagereply" (
"id" integer NOT NULL PRIMARY KEY,
"reply_to_id" integer NOT NULL REFERENCES "group_groupmessage" ("id"),
"from_email" varchar(255) NOT NULL,
"message" varchar(2048) NOT NULL,
"timestamp" datetime NOT NULL
);
CREATE TABLE "group_messageattachment" (
"id" integer NOT NULL PRIMARY KEY,
"group_message_id" integer NOT NULL REFERENCES "group_groupmessage" ("id"),
"repo_id" varchar(40) NOT NULL,
"attach_type" varchar(5) NOT NULL,
"path" text NOT NULL,
"src" varchar(20) NOT NULL
);
CREATE TABLE "group_publicgroup" (
"id" integer NOT NULL PRIMARY KEY,
"group_id" integer NOT NULL
);
CREATE TABLE "message_usermessage" (
"message_id" integer NOT NULL PRIMARY KEY,
"message" varchar(512) NOT NULL,
"from_email" varchar(255) NOT NULL,
"to_email" varchar(255) NOT NULL,
"timestamp" datetime NOT NULL,
"ifread" bool NOT NULL,
"sender_deleted_at" datetime,
"recipient_deleted_at" datetime
);
CREATE TABLE "message_usermsglastcheck" (
"id" integer NOT NULL PRIMARY KEY,
"check_time" datetime NOT NULL
);
CREATE TABLE "message_usermsgattachment" (
"id" integer NOT NULL PRIMARY KEY,
"user_msg_id" integer NOT NULL REFERENCES "message_usermessage" ("message_id"),
"priv_file_dir_share_id" integer
);
CREATE TABLE "notifications_notification" (
"id" integer NOT NULL PRIMARY KEY,
"message" varchar(512) NOT NULL,
"primary" bool NOT NULL
);
CREATE TABLE "notifications_usernotification" (
"id" integer NOT NULL PRIMARY KEY,
"to_user" varchar(255) NOT NULL,
"msg_type" varchar(30) NOT NULL,
"detail" text NOT NULL,
"timestamp" datetime NOT NULL,
"seen" bool NOT NULL
);
CREATE TABLE "options_useroptions" (
"id" integer NOT NULL PRIMARY KEY,
"email" varchar(255) NOT NULL,
"option_key" varchar(50) NOT NULL,
"option_val" varchar(50) NOT NULL
);
CREATE TABLE "profile_profile" (
"id" integer NOT NULL PRIMARY KEY,
"user" varchar(75) NOT NULL UNIQUE,
"nickname" varchar(64) NOT NULL,
"intro" text NOT NULL,
"lang_code" text,
"login_id" varchar(225) UNIQUE,
"contact_email" varchar(225),
"institution" varchar(225)
);
CREATE TABLE "profile_detailedprofile" (
"id" integer NOT NULL PRIMARY KEY,
"user" varchar(255) NOT NULL,
"department" varchar(512) NOT NULL,
"telephone" varchar(100) NOT NULL
);
CREATE TABLE "share_anonymousshare" (
"id" integer NOT NULL PRIMARY KEY,
"repo_owner" varchar(255) NOT NULL,
"repo_id" varchar(36) NOT NULL,
"anonymous_email" varchar(255) NOT NULL,
"token" varchar(25) NOT NULL UNIQUE
);
CREATE TABLE "share_fileshare" (
"id" integer NOT NULL PRIMARY KEY,
"username" varchar(255) NOT NULL,
"repo_id" varchar(36) NOT NULL,
"path" text NOT NULL,
"token" varchar(10) NOT NULL UNIQUE,
"ctime" datetime NOT NULL,
"view_cnt" integer NOT NULL,
"s_type" varchar(2) NOT NULL,
"password" varchar(128),
"expire_date" datetime
);
CREATE TABLE "share_orgfileshare" (
"id" integer NOT NULL PRIMARY KEY,
"org_id" integer NOT NULL,
"file_share_id" integer NOT NULL UNIQUE REFERENCES "share_fileshare" ("id")
);
CREATE TABLE "share_uploadlinkshare" (
"id" integer NOT NULL PRIMARY KEY,
"username" varchar(255) NOT NULL,
"repo_id" varchar(36) NOT NULL,
"path" text NOT NULL,
"token" varchar(10) NOT NULL UNIQUE,
"ctime" datetime NOT NULL,
"view_cnt" integer NOT NULL,
"password" varchar(128),
"expire_date" datetime
);
CREATE TABLE "share_privatefiledirshare" (
"id" integer NOT NULL PRIMARY KEY,
"from_user" varchar(255) NOT NULL,
"to_user" varchar(255) NOT NULL,
"repo_id" varchar(36) NOT NULL,
"path" text NOT NULL,
"token" varchar(10) NOT NULL UNIQUE,
"permission" varchar(5) NOT NULL,
"s_type" varchar(5) NOT NULL
);
CREATE TABLE "pubfile_grouppublicfile" (
"id" integer NOT NULL PRIMARY KEY,
"group_id" integer NOT NULL,
"repo_id" varchar(36) NOT NULL,
"path" varchar(4096) NOT NULL,
"is_dir" bool NOT NULL,
"added_by" varchar(256) NOT NULL,
"description" varchar(1024) NOT NULL,
"download_count" integer NOT NULL
);
CREATE TABLE "sysadmin_extra_userloginlog" (
"id" integer NOT NULL PRIMARY KEY,
"username" varchar(255) NOT NULL,
"login_date" datetime NOT NULL,
"login_ip" varchar(20) NOT NULL
);
CREATE TABLE "organizations_orgmemberquota" (
"id" integer NOT NULL PRIMARY KEY,
"org_id" integer NOT NULL,
"quota" integer NOT NULL
);
CREATE INDEX "django_session_b7b81f0c" ON "django_session" ("expire_date");
CREATE INDEX "base_filediscuss_12d5396a" ON "base_filediscuss" ("group_message_id");
CREATE INDEX "base_filediscuss_656b4f4a" ON "base_filediscuss" ("path_hash");
CREATE INDEX "base_userstarredfiles_830a6ccb" ON "base_userstarredfiles" ("email");
CREATE INDEX "base_userstarredfiles_2059abe4" ON "base_userstarredfiles" ("repo_id");
CREATE INDEX "base_userenabledmodule_ee0cafa2" ON "base_userenabledmodule" ("username");
CREATE INDEX "base_groupenabledmodule_dc00373b" ON "base_groupenabledmodule" ("group_id");
CREATE INDEX "base_userlastlogin_ee0cafa2" ON "base_userlastlogin" ("username");
CREATE INDEX "base_innerpubmsgreply_3fde75e6" ON "base_innerpubmsgreply" ("reply_to_id");
CREATE INDEX "base_clientlogintoken_ee0cafa2" ON "base_clientlogintoken" ("username");
CREATE INDEX "contacts_contact_d3d8b136" ON "contacts_contact" ("user_email");
CREATE INDEX "group_groupmessage_dc00373b" ON "group_groupmessage" ("group_id");
CREATE INDEX "group_messagereply_3fde75e6" ON "group_messagereply" ("reply_to_id");
CREATE INDEX "group_messageattachment_12d5396a" ON "group_messageattachment" ("group_message_id");
CREATE INDEX "group_publicgroup_dc00373b" ON "group_publicgroup" ("group_id");
CREATE INDEX "message_usermessage_8b1dd4eb" ON "message_usermessage" ("from_email");
CREATE INDEX "message_usermessage_590d1560" ON "message_usermessage" ("to_email");
CREATE INDEX "message_usermsgattachment_72f290f5" ON "message_usermsgattachment" ("user_msg_id");
CREATE INDEX "message_usermsgattachment_cee41a9a" ON "message_usermsgattachment" ("priv_file_dir_share_id");
CREATE INDEX "notifications_usernotification_bc172800" ON "notifications_usernotification" ("to_user");
CREATE INDEX "notifications_usernotification_265e5521" ON "notifications_usernotification" ("msg_type");
CREATE INDEX "options_useroptions_830a6ccb" ON "options_useroptions" ("email");
CREATE INDEX "profile_profile_3b46cb17" ON "profile_profile" ("contact_email");
CREATE INDEX "profile_profile_71bbc151" ON "profile_profile" ("institution");
CREATE INDEX "profile_detailedprofile_6340c63c" ON "profile_detailedprofile" ("user");
CREATE INDEX "share_fileshare_ee0cafa2" ON "share_fileshare" ("username");
CREATE INDEX "share_fileshare_2059abe4" ON "share_fileshare" ("repo_id");
CREATE INDEX "share_fileshare_44096fd5" ON "share_fileshare" ("s_type");
CREATE INDEX "share_orgfileshare_944dadb6" ON "share_orgfileshare" ("org_id");
CREATE INDEX "share_uploadlinkshare_ee0cafa2" ON "share_uploadlinkshare" ("username");
CREATE INDEX "share_uploadlinkshare_2059abe4" ON "share_uploadlinkshare" ("repo_id");
CREATE INDEX "share_privatefiledirshare_0e7efed3" ON "share_privatefiledirshare" ("from_user");
CREATE INDEX "share_privatefiledirshare_bc172800" ON "share_privatefiledirshare" ("to_user");
CREATE INDEX "share_privatefiledirshare_2059abe4" ON "share_privatefiledirshare" ("repo_id");
CREATE INDEX "pubfile_grouppublicfile_dc00373b" ON "pubfile_grouppublicfile" ("group_id");
CREATE INDEX "sysadmin_extra_userloginlog_ee0cafa2" ON "sysadmin_extra_userloginlog" ("username");
CREATE INDEX "sysadmin_extra_userloginlog_c8db99ec" ON "sysadmin_extra_userloginlog" ("login_date");
CREATE INDEX "organizations_orgmemberquota_944dadb6" ON "organizations_orgmemberquota" ("org_id");
<file_sep>/seahub/signals.py
import django.dispatch
# Use org_id = -1 if it's not an org repo
repo_created = django.dispatch.Signal(providing_args=["org_id", "creator", "repo_id", "repo_name"])
repo_deleted = django.dispatch.Signal(providing_args=["org_id", "usernames", "repo_owner", "repo_id", "repo_name"])
share_file_to_user_successful = django.dispatch.Signal(providing_args=["priv_share_obj"])
upload_file_successful = django.dispatch.Signal(providing_args=["repo_id", "file_path", "owner"])
<file_sep>/seahub/base/utils.py
import re
import string
from django.utils.safestring import SafeData, mark_safe
from django.utils.encoding import force_unicode
from django.utils.functional import allow_lazy
from django.utils.http import urlquote
# Configuration for urlize() function.
LEADING_PUNCTUATION = ['(', '<', '<']
TRAILING_PUNCTUATION = ['.', ',', ')', '>', '\n', '>']
word_split_re = re.compile(r'(\s+)')
punctuation_re = re.compile('^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % \
('|'.join([re.escape(x) for x in LEADING_PUNCTUATION]),
'|'.join([re.escape(x) for x in TRAILING_PUNCTUATION])))
simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')
def escape(html):
"""
Returns the given HTML with ampersands, quotes and angle brackets encoded.
"""
return mark_safe(force_unicode(html).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", '''))
escape = allow_lazy(escape, unicode)
## modification of django's urlize, add '%' to safe:
## urlquote('http://%s' % middle, safe='/&=:;#?+*%')
## the origin is
## urlquote('http://%s' % middle, safe='/&=:;#?+*')
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
"""
Converts any URLs in text into clickable links.
Works on http://, https://, www. links and links ending in .org, .net or
.com. Links can have trailing punctuation (periods, commas, close-parens)
and leading punctuation (opening parens) and it'll still do the right
thing.
If trim_url_limit is not None, the URLs in link text longer than this limit
will truncated to trim_url_limit-3 characters and appended with an elipsis.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
If autoescape is True, the link text and URLs will get autoescaped.
"""
trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
safe_input = isinstance(text, SafeData)
words = word_split_re.split(force_unicode(text))
nofollow_attr = nofollow and ' rel="nofollow"' or ''
for i, word in enumerate(words):
match = None
if '.' in word or '@' in word or ':' in word:
match = punctuation_re.match(word)
if match:
lead, middle, trail = match.groups()
# Make URL we want to point to.
url = None
if middle.startswith('http://') or middle.startswith('https://'):
url = urlquote(middle, safe='/&=:;#?+*%')
elif middle.startswith('www.') or ('@' not in middle and \
middle and middle[0] in string.ascii_letters + string.digits and \
(middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))):
url = urlquote('http://%s' % middle, safe='/&=:;#?+*%')
# elif '@' in middle and not ':' in middle and simple_email_re.match(middle):
# url = 'mailto:%s' % middle
# nofollow_attr = ''
# Make link.
if url:
trimmed = trim_url(middle)
if autoescape and not safe_input:
lead, trail = escape(lead), escape(trail)
url, trimmed = escape(url), escape(trimmed)
middle = '<a target="_blank" href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed)
words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
else:
if safe_input:
words[i] = mark_safe(word)
elif autoescape:
words[i] = escape(word)
elif safe_input:
words[i] = mark_safe(word)
elif autoescape:
words[i] = escape(word)
return u''.join(words)
urlize = allow_lazy(urlize, unicode)
<file_sep>/media/custom/js/eyeos.js
/*
Copyright (c) 2016 eyeOS
This file is part of Open365.
Open365 is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function () {
console.log('starting Eyeos modifications');
var openInEyeosExtensions = {
'xls': 'calc',
'xlsx': 'calc',
'ods': 'calc',
'csv': 'calc',
'doc': 'writer',
'docx': 'writer',
'odt': 'writer',
'ppt': 'presentation',
'pptx': 'presentation',
'pps': 'presentation',
'ppsx': 'presentation',
'odp': 'presentation',
'xcf': 'gimp'
};
var desktopBusSubscriptions = [];
var onRouteChangeActions = [];
var currentLibraryName;
window.onunload = onUnload;
// Seafile pages that are *NOT* sharing: should be opened inside Open365
if (isSeafileStandalone()) {
$("BODY").css("display", "none"); // Will avoid showing content before redirection
var seafileUrl = window.location.pathname + window.location.hash;
if (window.location.search) {
seafileUrl += window.location.search;
}
seafileUrl = btoa(seafileUrl);
window.location.href="/?target="+ seafileUrl;
// External seafile (share) pages
} else if (!isSeafileIframe()) {
customizeNonIframePages();
}
hideWelcomePage();
modifyPage();
moveUserQuotaUnderLeftPanel();
listenChangePasswordEvent();
modifyUrlDownloadClient();
if ("onhashchange" in window) {
// does the browser support the hashchange event?
window.onhashchange = function () {
console.info('ROUTE CHANGED', window.location.hash);
$('.repo-file-list tbody *').remove();
onRouteChangeActions.forEach(function(action){action()});
onRouteChangeActions.length = 0;
modifyPage();
moveUserQuotaUnderLeftPanel();
};
} else {
console.error('Your browser does not support onhashchange. This code won\'t work.');
}
function customizeNonIframePages() {
// Manipulate base DOM and STYLES
var header = document.getElementById("header");
var mainDiv = document.getElementById("main");
var footer = document.getElementById("footer");
var footerHeight = footer.offsetHeight;
header.style.display = "block";
document.getElementById("logo").setAttribute("href", "https://open365.io/?source=shareByUrl");
document.getElementById("logo").setAttribute("target", "_blank");
mainDiv.style.width = "97%";
mainDiv.style.marginTop = 0;
mainDiv.style.marginTop = "30px";
window.addEventListener('resize', customizeFileSharePage);
if (locationIsResourceView()) {
createOpen365header();
}
customizeFileSharePage();
hideElementsNonIframe();
mainDiv.style.height = mainDiv.offsetHeight + footer.offsetHeight + "px";
}
function isSeafileIframe() {
return parent.document.getElementById('seahubIframe');
}
function locationIsResourceView() {
return window.top.location.pathname.indexOf('/sync/lib/') > -1;
}
function isSeafileStandalone() {
var result = false;
var seafileUrl = window.location.pathname + window.location.hash;
if (window.location.search) {
seafileUrl += window.location.search;
result = !/^\/sync\/repo\/[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}\/history\/files\/\?obj_id\=[0-9]*\&commit_id\=[0-9a-z]{40}\&p\=/.test(seafileUrl);
} else {
result = /^\/sync\/[#a-z]{1}(\/[a-z]{1})?\/[0-9a-z]{10}\/$/.test(seafileUrl);
}
// return TRUE if both conditions are FALSE
return !result && !isSeafileIframe();
}
function hideElementsNonIframe() {
$("#msg-count, #my-info").css({
display: 'none'
});
}
function getUrlVar(variable) {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars[variable];
}
// If there is NO div with 'wide-panel' class element, then we are being called from the
// file share page and thus we may do some hacks to the DOM
function customizeFileSharePage() {
if (!document.getElementsByClassName('wide-panel').length) {
var mainDiv = document.getElementById("main");
var logoElement = document.getElementById("logo");
var logoLeft = logoElement.offsetLeft;
var mainWidth = mainDiv.offsetWidth;
mainDiv.style.width = "calc(97% - "+ (logoLeft * 2) + "px)";
mainDiv.style.marginLeft = logoLeft + "px";
mainDiv.className += " share-wrapper";
}
}
// If there's no header, create one
function createOpen365header() {
// Only 'file-view' pages appear to dont have a header
if (document.getElementById("file-view")) {
var wrapper = document.getElementById("wrapper");
var headerDiv = document.createElement("DIV");
headerDiv.id = "header";
headerDiv.style.display = "block";
headerDiv.innerHTML = "<div id='header-inner'> <a href='https://open365.io/?source=shareByUrl' id='logo' class='fleft'></a> </div>";
wrapper.insertBefore(headerDiv, wrapper.firstChild);
}
}
// Adjust footer position
function adjustFooterPosition() {
var footer = document.getElementById("footer");
var bodyHeight = document.documentElement.scrollHeight;
var viewportHeight = window.innerHeight;
var footerHeight = footer.offsetHeight;
var headerHeight = header.offsetHeight;
var newFooterPos = 0;
var publicMessageHeight = document.getElementById("publicMessage").offsetHeight;
var minHeight = viewportHeight - headerHeight - publicMessageHeight - footerHeight - 50;
document.getElementById("main").style.minHeight = minHeight + "px";
}
function moveUserQuotaUnderLeftPanel() {
if(window.location.hash === "" || window.location.hash.indexOf('my-libs') !== -1) {
console.log('update user quota view');
var url = location.protocol+"//"+document.domain+':'+location.port + '/sync/ajax/space_and_traffic/';
$.ajax(url, {
success: function(data) {
var quota = $(data.html);
waitForElement('#left-panel a[href="/sync/share/links/"]', function (elem) {
$('#left-panel > .item').remove();
$('#left-panel').append(quota);
}, 200, -1);
}
});
} else {
$('#left-panel > .item').remove();
}
}
function removeQuotaLink() {
var anchor = document.getElementById("quota-usage");
if (anchor) {
anchor.parentNode.removeAttribute("href");
}
}
function encryptSwitchMod() {
waitForElement("#right-panel #repo-tabs DIV.hd", function() {
$("BUTTON.repo-create")[0].onclick = function() {
waitForElement("LABEL.checkbox-label", function() {
$("#encrypt-switch").click(function() {
var msgSpan;
if ( !(msgSpan = document.getElementById("encryptMessage")) ) {
msgSpan = document.createElement("SPAN");
msgSpan.innerHTML = " not supported in LibreOffice";
msgSpan.style.color = "red";
msgSpan.style.fontWeight = "normal";
msgSpan.setAttribute("id", "encryptMessage");
$("LABEL.checkbox-label")[0].appendChild(msgSpan);
} else {
$(msgSpan).remove();
}
});
}, 200, 3000);
};
}, 150, 5000);
}
function modifyPage () {
updateFileListOnClickBehaviour();
activateNotification();
encryptSwitchMod();
waitForElement('#right-panel UL LI *', function() {
if (window.location.href.indexOf('/wiki/') !== -1) {
$("a[href^='/sync/repo/history/']").removeAttr("target");
}
}, 300, 3000);
waitForElement('#quota-usage', removeQuotaLink, 300, 3000);
waitForElement('.dirent-name .normal:not(.dir-link)', function (elem) {
console.log(' - Going to modify links in current page');
var filesDomElements = elem.toArray();
filesDomElements.forEach(function (item){
openLinkInEyeosDesktop(item);
});
}, 500, 10000);
var observerStarredList = onDomChange('#starred-file > table > tbody' , function (elem) {
var filesDomElements = $(elem.children).toArray();
filesDomElements.forEach(function (item){
var aLink = item.children[1].children[0];
var libraryName = item.children[2].innerHTML;
openLinkInEyeosDesktop(aLink, libraryName);
});
});
onRouteChangeActions.push(function (){
observerStarredList.disconnect();
});
}
function updateFileListOnClickBehaviour () {
$('.repo-file-list tbody').hide();
var observer = onDomChange('.repo-file-list tbody', function (fileList){
getCurrentLibraryName(function (err, libraryName) {
if(err) {
console.warn('Could not get current library name');
return;
}
currentLibraryName = libraryName;
$(fileList)
.show()
.find('.dirent-name .normal:not(.dir-link)')
.toArray()
.forEach(function (item) {
openLinkInEyeosDesktop(item);
});
});
});
onRouteChangeActions.push(function (){
observer.disconnect();
});
}
function openLinkInEyeosDesktop(aLink, libraryName) {
libraryName = libraryName || currentLibraryName;
var filePath = getEyeosPathFromHref(aLink);
var ext = filePath.split('.').pop().toLowerCase();
if(!openInEyeosExtensions[ext]){
return;
}
aLink.onclick=function(e){
e.preventDefault();
e.stopPropagation();
sendOpenFileToDesktop(libraryName + filePath);
}
}
function sendOpenFileToDesktop(path) {
var desktopBus = getDesktopBus();
if (desktopBus) {
console.info('Send openFile event to desktop with path: ', path);
var event = {
name: 'eyeosCloud.fileOpened',
path: path
};
desktopBus.dispatch(event.name, event);
} else {
console.error('No desktopBus present in parent iframe');
}
}
function waitForElement(cssSelector, cb, retryIntervalTime, MAX_WAIT_TIME) {
var timeCounter = 0;
internalWaitForElement(cssSelector, cb);
function internalWaitForElement (cssSelector, cb) {
var elem = $(cssSelector);
if (elem.length > 0) {
cb(elem);
} else {
timeCounter += retryIntervalTime;
if (timeCounter > MAX_WAIT_TIME && MAX_WAIT_TIME > 0) {
console.log('stop waiting cssSelector: ', cssSelector);
return;
}
setTimeout(internalWaitForElement.bind(this, cssSelector, cb), retryIntervalTime);
}
}
}
function getEyeosPathFromHref (aHref) {
// detect first position of '/file' and return the rest of the url
var href = $(aHref).attr('href');
var pos;
if ((pos = href.indexOf('/file')) !== -1) {
// in the href the url is encoded, so decode it. decodeURI didn't
// decode adequately hash simbols (#), so we are using
// decodeURIComponent instead.
return decodeURIComponent(href.substr(pos + '/file'.length));
}
return '';
}
function getDesktopBus () {
return window.parent.DesktopBus;
}
function getCurrentLibraryId() {
var hashParts = location.hash.split('/');
var libIdIndex = hashParts.indexOf("lib") + 1;
return hashParts[libIdIndex];
}
function getCurrentLibraryName (cb) {
var repoId = getCurrentLibraryId();
return getLibraryName(repoId, cb);
}
function getLibraryName (repoId, callback) {
function _getLibraryNameFromListOfLibraries (libraries) {
for (var i = 0; i < libraries.length; i++) {
var library = libraries[i];
if (library.id === repoId) {
return library.name;
}
}
console.log("Couldn't find library name. How could that be possible?");
return false;
}
function _isLibraryNameRepeated (name, libraries) {
var num = 0;
for (var i = 0; i < libraries.length; i++) {
var library = libraries[i];
if (library.name === name) {
num++;
if (num > 1) {
return true;
}
}
}
return false;
}
var url = '/sync/api2/repos/';
$.ajax(url, {
success: function(libraries) {
if (libraries && libraries.length) {
var name = _getLibraryNameFromListOfLibraries(libraries);
if (!name) {
return callback(new Error('Can\'t get the name of the library'));
}
if (_isLibraryNameRepeated(name, libraries)) {
name += '-' + repoId.substr(0, 6);
}
return callback(null, name);
} else {
callback(new Error('Can\'t get the name of the library'));
}
},
error: function (err) {
callback(err);
}
});
}
function hideWelcomePage () {
var interv = setInterval(function () {
if (window.app && window.app.pageOptions) {
window.app.pageOptions.guide_enabled=false;
window.clearInterval(interv);
}
}, 10);
window.setTimeout(function () {
clearInterval(interv);
}, 2000);
}
function onDomChange (cssSelector, cb) {
var target = document.querySelector(cssSelector);
if(!target) {
return;
}
var observer = new MutationObserver(function(mutations) {
cb(target);
});
var config = { attributes: false, childList: true, characterData: true, subtree:true };
observer.observe(target, config);
return observer;
}
function listenChangePasswordEvent () {
var desktopBus = getDesktopBus();
if(!desktopBus) {
console.warn('Can\'t listen to desktop bus. Change password won\'t work');
return;
}
var subscription = desktopBus.subscribe('changePasswordSuccess', doLogoutAndGoToLogin);
desktopBusSubscriptions.push(subscription);
}
function doLogoutAndGoToLogin () {
function reloadSeahubIframe () {
console.info('Reloading seahub iframe');
document.location.href="/sync";
}
$.get('/sync/accounts/logout/', {success: reloadSeahubIframe});
}
function onUnload () {
desktopBusSubscriptions.forEach(function (sub) {
sub.unsubscribe();
});
desktopBusSubscriptions.length = 0;
}
function activateNotification() {
waitForElement('#msg-count', function (elem) {
console.log('Going to modify notifications');
$(elem).appendTo('body');
elem.removeClass('fleft');
}, 500, 10000);
}
function modifyUrlDownloadClient() {
var url = getUrlDownloadClient();
if (url) {
$('#footer a:first').attr("href", url);
}
}
function getUrlDownloadClient() {
var userLang = getUserLanguage();
var url = getValueLocalStorage('url_download_client');
if (userLang === 'es') {
var slashLast = url.lastIndexOf('/');
var pathname = url.substr(slashLast);
var host = url.substr(0, slashLast + 1);
url = host + userLang + pathname;
}
return url;
}
function getUserLanguage() {
var lang = "en";
var itemUserInfo = getValueLocalStorage('userInfo');
if (itemUserInfo) {
var jsonUserInfo = JSON.parse(itemUserInfo);
if ( jsonUserInfo && jsonUserInfo.hasOwnProperty("lang")) {
lang = jsonUserInfo.lang;
}
}
return lang;
}
function getValueLocalStorage(key) {
var resultLocalStorage = null;
var valueKey = window.localStorage.getItem(key);
if (valueKey) {
resultLocalStorage = valueKey
}
return resultLocalStorage;
}
})();
<file_sep>/seahub/templates/snippets/repo_dir_trash_tr.html
{% load seahub_tags i18n %}
{% for dirent in dir_entries %}
{% if dirent.is_dir %}
<tr>
<td class="alc"><img src="{{ MEDIA_URL }}img/folder-icon-24.png" alt="{% trans "Directory" %}" /></td>
{% if show_recycle_root %}
<td><a href="?commit_id={{ dirent.commit_id }}&base={{ dirent.basedir|urlencode }}&p=/{{ dirent.obj_name|urlencode }}&dir_path={{dir_path|urlencode}}">{{ dirent.obj_name }}</a></td>
<td>{{ dirent.delete_time|translate_seahub_time }}</td>
<td></td>
<td><a class="op restore-dir hide" href="#" data-url="{% url 'repo_revert_dir' repo.id %}?commit={{ dirent.commit_id }}&p={{ dirent.basedir|urlencode }}{{dirent.obj_name|urlencode}}">{% trans "Restore" %}</a></td>
{% else %}
<td><a href="?commit_id={{ commit_id }}&base={{ basedir|urlencode }}&p={{ path|urlencode }}{{ dirent.obj_name|urlencode }}&dir_path={{dir_path|urlencode}}">{{ dirent.obj_name }}</a></td>
<td></td>
<td></td>
<td></td>
{% endif %}
</tr>
{% else %}
<tr>
<td class="alc"><img src="{{ MEDIA_URL }}img/file/{{ dirent.obj_name|file_icon_filter }}" alt="{% trans "File" %}" /></td>
{% if show_recycle_root %}
<td><a class="normal" href="{% url 'view_trash_file' repo.id %}?obj_id={{ dirent.obj_id }}&commit_id={{ dirent.commit_id }}&base={{ dirent.basedir|urlencode }}&p=/{{ dirent.obj_name|urlencode }}" target="_blank">{{ dirent.obj_name }}</a></td>
<td>{{ dirent.delete_time|translate_seahub_time }}</td>
<td>{{ dirent.file_size|filesizeformat }}</td>
<td><a class="op restore-file hide" href="#" data-url="{% url 'repo_revert_file' repo.id %}?commit={{ dirent.commit_id }}&p={{ dirent.basedir|urlencode }}{{dirent.obj_name|urlencode}}">{% trans "Restore" %}</a></td>
{% else %}
<td><a class="normal" href="{% url 'view_trash_file' repo.id %}?obj_id={{ dirent.obj_id }}&commit_id={{ commit_id }}&base={{ basedir|urlencode }}&p={{ path|urlencode }}{{ dirent.obj_name|urlencode }}" target="_blank">{{ dirent.obj_name }}</a></td>
<td></td>
<td>{{ dirent.file_size|filesizeformat }}</td>
<td></td>
{% endif %}
</tr>
{% endif %}
{% endfor %}
<file_sep>/seahub/group/views.py
# -*- coding: utf-8 -*-
import logging
import os
import json
import urllib2
import csv
import chardet
import StringIO
from django.conf import settings
from django.core.paginator import EmptyPage, InvalidPage
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect, Http404, \
HttpResponseBadRequest
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.http import urlquote
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from seahub.auth.decorators import login_required, login_required_ajax
import seaserv
from seaserv import ccnet_threaded_rpc, seafserv_threaded_rpc, \
seafile_api, get_repo, get_group_repos, get_commits, \
is_group_user, get_group, get_group_members, create_repo, \
get_org_group_repos, check_permission, is_passwd_set, remove_repo, \
unshare_group_repo, get_file_id_by_path, post_empty_file, del_file
from pysearpc import SearpcError
from decorators import group_staff_required
from models import GroupMessage, MessageReply, MessageAttachment, PublicGroup
from forms import MessageForm, MessageReplyForm, GroupRecommendForm, \
GroupAddForm, GroupJoinMsgForm, WikiCreateForm, BatchAddMembersForm
from signals import grpmsg_added, grpmsg_reply_added, group_join_request
from seahub.auth import REDIRECT_FIELD_NAME
from seahub.base.decorators import sys_staff_required, require_POST
from seahub.base.models import FileDiscuss
from seahub.contacts.models import Contact
from seahub.contacts.signals import mail_sended
from seahub.group.signals import add_user_to_group
from seahub.group.utils import validate_group_name, BadGroupNameError, \
ConflictGroupNameError, get_group_domain
from seahub.notifications.models import UserNotification
from seahub.wiki import get_group_wiki_repo, get_group_wiki_page, convert_wiki_link,\
get_wiki_pages
from seahub.wiki.models import WikiDoesNotExist, WikiPageMissing, GroupWiki
from seahub.wiki.utils import clean_page_name, page_name_to_file_name
from seahub.settings import SITE_ROOT, SITE_NAME
from seahub.shortcuts import get_first_object_or_none
from seahub.utils import render_error, render_permission_error, string2list, \
gen_file_get_url, get_file_type_and_ext, \
calc_file_path_hash, is_valid_username, send_html_email, is_org_context
from seahub.utils.file_types import IMAGE
from seahub.utils.paginator import Paginator
from seahub.views import is_registered_user
from seahub.views.modules import get_enabled_mods_by_group, MOD_GROUP_WIKI, \
enable_mod_for_group, disable_mod_for_group, get_available_mods_by_group, \
get_wiki_enabled_group_list
from seahub.forms import SharedRepoCreateForm
from constance import config
# Get an instance of a logger
logger = logging.getLogger(__name__)
########## ccnet rpc wrapper
def create_group(group_name, username):
return seaserv.ccnet_threaded_rpc.create_group(group_name, username)
def create_org_group(org_id, group_name, username):
return seaserv.ccnet_threaded_rpc.create_org_group(org_id, group_name,
username)
def get_all_groups(start, limit):
return seaserv.ccnet_threaded_rpc.get_all_groups(start, limit)
def org_user_exists(org_id, username):
return seaserv.ccnet_threaded_rpc.org_user_exists(org_id, username)
########## helper functions
def is_group_staff(group, user):
if user.is_anonymous():
return False
return seaserv.check_group_staff(group.id, user.username)
def remove_group_common(group_id, username, org_id=None):
"""Common function to remove a group, and it's repos,
If ``org_id`` is provided, also remove org group.
Arguments:
- `group_id`:
"""
seaserv.ccnet_threaded_rpc.remove_group(group_id, username)
seaserv.seafserv_threaded_rpc.remove_repo_group(group_id)
if org_id is not None and org_id > 0:
seaserv.ccnet_threaded_rpc.remove_org_group(org_id, group_id)
def group_check(func):
"""
Decorator for initial group permission check tasks
un-login user & group not pub --> login page
un-login user & group pub --> view_perm = "pub"
login user & non group member & group not pub --> public info page
login user & non group member & group pub --> view_perm = "pub"
group member --> view_perm = "joined"
sys admin --> view_perm = "sys_admin"
"""
def _decorated(request, group_id, *args, **kwargs):
group_id_int = int(group_id) # Checked by URL Conf
group = get_group(group_id_int)
if not group:
return HttpResponseRedirect(reverse('group_list', args=[]))
group.is_staff = False
if PublicGroup.objects.filter(group_id=group.id):
group.is_pub = True
else:
group.is_pub = False
if not request.user.is_authenticated():
if not group.is_pub:
login_url = settings.LOGIN_URL
path = urlquote(request.get_full_path())
tup = login_url, REDIRECT_FIELD_NAME, path
return HttpResponseRedirect('%s?%s=%s' % tup)
else:
group.view_perm = "pub"
return func(request, group, *args, **kwargs)
joined = is_group_user(group_id_int, request.user.username)
if joined:
group.view_perm = "joined"
group.is_staff = is_group_staff(group, request.user)
return func(request, group, *args, **kwargs)
if request.user.is_staff:
# viewed by system admin
group.view_perm = "sys_admin"
return func(request, group, *args, **kwargs)
if group.is_pub:
group.view_perm = "pub"
return func(request, group, *args, **kwargs)
return render_to_response('error.html', {
'error_msg': _('Permission denied'),
}, context_instance=RequestContext(request))
return _decorated
########## views
@login_required_ajax
def group_add(request):
"""Add a new group"""
if request.method != 'POST':
raise Http404
username = request.user.username
result = {}
content_type = 'application/json; charset=utf-8'
user_can_add_group = request.user.permissions.can_add_group()
if not user_can_add_group:
result['error'] = _(u'You do not have permission to create group.')
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
# check plan
num_of_groups = getattr(request.user, 'num_of_groups', -1)
if num_of_groups > 0:
current_groups = len(request.user.joined_groups)
if current_groups > num_of_groups:
result['error'] = _(u'You can only create %d groups.<a href="http://seafile.com/">Upgrade account.</a>') % num_of_groups
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
form = GroupAddForm(request.POST)
if form.is_valid():
group_name = form.cleaned_data['group_name']
# Check whether group name is duplicated.
org_id = -1
if is_org_context(request):
org_id = request.user.org.org_id
checked_groups = seaserv.get_org_groups_by_user(org_id, username)
else:
if request.cloud_mode:
checked_groups = seaserv.get_personal_groups_by_user(username)
else:
checked_groups = get_all_groups(-1, -1)
for g in checked_groups:
if g.group_name == group_name:
result['error'] = _(u'There is already a group with that name.')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# Group name is valid, create that group.
try:
if org_id > 0:
create_org_group(org_id, group_name, username)
else:
create_group(group_name, username)
return HttpResponse(json.dumps({'success': True}),
content_type=content_type)
except SearpcError, e:
result['error'] = _(e.msg)
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
else:
return HttpResponseBadRequest(json.dumps(form.errors),
content_type=content_type)
@login_required
@sys_staff_required
@require_POST
def group_remove(request, group_id):
"""
Remove group from groupadmin page. Only system admin can perform this
operation.
"""
# Request header may missing HTTP_REFERER, we need to handle that case.
next = request.META.get('HTTP_REFERER', SITE_ROOT)
try:
group_id_int = int(group_id)
except ValueError:
return HttpResponseRedirect(next)
remove_group_common(group_id_int, request.user.username)
return HttpResponseRedirect(next)
@login_required
@group_staff_required
@require_POST
def group_dismiss(request, group_id):
"""
Dismiss a group, only group staff can perform this operation.
"""
try:
group_id_int = int(group_id)
except ValueError:
return HttpResponseRedirect(reverse('group_list', args=[]))
group = get_group(group_id_int)
if not group:
return HttpResponseRedirect(reverse('group_list', args=[]))
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
else:
org_id = None
try:
remove_group_common(group.id, username, org_id=org_id)
except SearpcError, e:
logger.error(e)
return HttpResponseRedirect(reverse('group_list'))
def rename_group_with_new_name(request, group_id, new_group_name):
"""Rename a group with new name.
Arguments:
- `request`:
- `group_id`:
- `new_group_name`:
Raises:
BadGroupNameError: New group name format is not valid.
ConflictGroupNameError: New group name confilicts with existing name.
"""
if not validate_group_name(new_group_name):
raise BadGroupNameError
# Check whether group name is duplicated.
username = request.user.username
org_id = -1
if is_org_context(request):
org_id = request.user.org.org_id
checked_groups = seaserv.get_org_groups_by_user(org_id, username)
else:
if request.cloud_mode:
checked_groups = seaserv.get_personal_groups_by_user(username)
else:
checked_groups = get_all_groups(-1, -1)
for g in checked_groups:
if g.group_name == new_group_name:
raise ConflictGroupNameError
ccnet_threaded_rpc.set_group_name(group_id, new_group_name)
@login_required
@group_staff_required
def group_rename(request, group_id):
"""Rename a group.
"""
if request.method != 'POST':
raise Http404
new_name = request.POST.get('new_name', '')
new_name = new_name.strip()
next = request.META.get('HTTP_REFERER', SITE_ROOT)
group_id = int(group_id)
try:
rename_group_with_new_name(request, group_id, new_name)
except BadGroupNameError:
messages.error(request, _('Failed to rename group, group name can only contain letters, numbers, blank, hyphen or underscore'))
except ConflictGroupNameError:
messages.error(request, _('There is already a group with that name.'))
else:
messages.success(request, _('Successfully renamed group to "%s".') %
new_name)
return HttpResponseRedirect(next)
@login_required
@group_staff_required
def group_transfer(request, group_id):
"""Change group creator.
"""
if request.method != 'POST':
raise Http404
group_id = int(group_id)
username = request.user.username
email = request.POST.get('email', '')
if not is_valid_username(email):
messages.error(request, _('Email %s is not valid.') % email)
next = reverse('group_manage', args=[group_id])
return HttpResponseRedirect(next)
if email != username:
if not is_group_user(group_id, email):
ccnet_threaded_rpc.group_add_member(group_id, username, email)
ccnet_threaded_rpc.set_group_creator(group_id, email)
next = reverse('group_list', args=[])
return HttpResponseRedirect(next)
@login_required
def group_make_public(request, group_id):
"""
Make a group public, only group staff can perform this operation.
"""
if not getattr(settings, 'ENABLE_MAKE_GROUP_PUBLIC', False):
raise Http404
try:
group_id_int = int(group_id)
except ValueError:
return HttpResponseRedirect(reverse('group_list', args=[]))
group = get_group(group_id_int)
if not group:
return HttpResponseRedirect(reverse('group_list', args=[]))
# Check whether user is group staff
if not is_group_staff(group, request.user):
return render_permission_error(request, _(u'Only administrators can make the group public'))
p = PublicGroup(group_id=group.id)
p.save()
return HttpResponseRedirect(reverse('group_manage', args=[group_id]))
@login_required
def group_revoke_public(request, group_id):
"""
Revoke a group from public, only group staff can perform this operation.
"""
try:
group_id_int = int(group_id)
except ValueError:
return HttpResponseRedirect(reverse('group_list', args=[]))
group = get_group(group_id_int)
if not group:
return HttpResponseRedirect(reverse('group_list', args=[]))
# Check whether user is group staff
if not is_group_staff(group, request.user):
return render_permission_error(request, _(u'Only administrators can make the group public'))
try:
p = PublicGroup.objects.get(group_id=group.id)
p.delete()
except:
pass
return HttpResponseRedirect(reverse('group_manage', args=[group_id]))
@login_required
@require_POST
def group_quit(request, group_id):
try:
group_id_int = int(group_id)
except ValueError:
return HttpResponseRedirect(reverse('group_list', args=[]))
try:
ccnet_threaded_rpc.quit_group(group_id_int, request.user.username)
seafserv_threaded_rpc.remove_repo_group(group_id_int,
request.user.username)
except SearpcError, e:
return render_error(request, _(e.msg))
return HttpResponseRedirect(reverse('group_list', args=[]))
@login_required
def group_message_remove(request, group_id, msg_id):
"""
Remove group message and all message replies and attachments.
"""
# Checked by URL Conf
group_id_int = int(group_id)
msg_id = int(msg_id)
group = get_group(group_id_int)
if not group:
raise Http404
# Test whether user is in the group
if not is_group_user(group_id_int, request.user.username):
raise Http404
try:
gm = GroupMessage.objects.get(id=msg_id)
except GroupMessage.DoesNotExist:
return HttpResponse(json.dumps({'success': False, 'err_msg':_(u"The message doesn't exist")}),
content_type='application/json; charset=utf-8')
else:
# Test whether user is group admin or message owner.
if seaserv.check_group_staff(group_id, request.user.username) or \
gm.from_email == request.user.username:
gm.delete()
return HttpResponse(json.dumps({'success': True}),
content_type='application/json; charset=utf-8')
else:
return HttpResponse(json.dumps({'success': False, 'err_msg': _(u"You don't have the permission.")}),
content_type='application/json; charset=utf-8')
def msg_reply(request, msg_id):
"""Show group message replies, and process message reply in ajax"""
if not request.is_ajax():
raise Http404
content_type = 'application/json; charset=utf-8'
ctx = {}
try:
group_msg = GroupMessage.objects.get(id=msg_id)
except GroupMessage.DoesNotExist:
return HttpResponseBadRequest(content_type=content_type)
if request.method == 'POST':
if not request.user.is_authenticated():
return HttpResponseBadRequest(json.dumps({
"error": "login required"}), content_type=content_type)
form = MessageReplyForm(request.POST)
r_status = request.GET.get('r_status')
# TODO: invalid form
if form.is_valid():
msg = form.cleaned_data['message']
msg_reply = MessageReply()
msg_reply.reply_to = group_msg
msg_reply.from_email = request.user.username
msg_reply.message = msg
msg_reply.save()
grpmsg_reply_added.send(sender=MessageReply,
msg_id=msg_id,
from_email=request.user.username,
grpmsg_topic=group_msg.message,
reply_msg=msg)
replies = MessageReply.objects.filter(reply_to=group_msg)
r_num = len(replies)
if r_num < 4 or r_status == 'show':
ctx['replies'] = replies
else:
ctx['replies'] = replies[r_num - 3:]
html = render_to_string("group/group_reply_list.html", ctx)
serialized_data = json.dumps({"r_num": r_num, "html": html})
return HttpResponse(serialized_data, content_type=content_type)
else:
replies = MessageReply.objects.filter(reply_to=group_msg)
r_num = len(replies)
ctx['replies'] = replies
html = render_to_string("group/group_reply_list.html", ctx)
serialized_data = json.dumps({"r_num": r_num, "html": html})
return HttpResponse(serialized_data, content_type=content_type)
@login_required
def msg_reply_new(request):
username = request.user.username
grpmsg_reply_list = [ x for x in UserNotification.objects.get_group_msg_reply_notices(username) ]
msg_ids = []
for e in grpmsg_reply_list:
try:
msg_id = e.grpmsg_reply_detail_to_dict().get('msg_id')
except UserNotification.InvalidDetailError:
continue
msg_ids.append(msg_id)
group_msgs = []
for msg_id in msg_ids:
try:
m = GroupMessage.objects.get(id=msg_id)
except GroupMessage.DoesNotExist:
continue
else:
if m in group_msgs:
continue
# get group name
group = get_group(m.group_id)
if not group:
continue
m.group_name = group.group_name
# get attachements
attachments = m.messageattachment_set.all()
for attachment in attachments:
path = attachment.path
if path == '/':
repo = get_repo(attachment.repo_id)
if not repo:
continue
attachment.name = repo.name
else:
attachment.name = os.path.basename(path)
m.attachments = attachments
# get message replies
reply_list = MessageReply.objects.filter(reply_to=m)
m.reply_cnt = reply_list.count()
if m.reply_cnt > 3:
m.replies = reply_list[m.reply_cnt - 3:]
else:
m.replies = reply_list
group_msgs.append(m)
# remove new group msg reply notification
UserNotification.objects.seen_group_msg_reply_notice(username)
return render_to_response("group/new_msg_reply.html", {
'group_msgs': group_msgs,
}, context_instance=RequestContext(request))
def group_info_for_pub(request, group):
# get available modules(wiki, etc)
mods_available = get_available_mods_by_group(group.id)
mods_enabled = get_enabled_mods_by_group(group.id)
return render_to_response("group/group_info_for_pub.html", {
"repos": [],
"group": group,
"mods_enabled": mods_enabled,
"mods_available": mods_available,
}, context_instance=RequestContext(request))
@group_check
def group_info(request, group):
if group.view_perm == "pub":
return group_info_for_pub(request, group)
# get available modules(wiki, etc)
mods_available = get_available_mods_by_group(group.id)
mods_enabled = get_enabled_mods_by_group(group.id)
return render_to_response("group/group_info.html", {
"group" : group,
"is_staff": group.is_staff,
"mods_enabled": mods_enabled,
"mods_available": mods_available,
'repo_password_min_length': config.REPO_PASSWORD_MIN_LENGTH,
}, context_instance=RequestContext(request))
@group_check
def group_members(request, group):
if group.view_perm == 'pub':
raise Http404
# Get all group members.
members = get_group_members(group.id)
# get available modules(wiki, etc)
mods_available = get_available_mods_by_group(group.id)
mods_enabled = get_enabled_mods_by_group(group.id)
return render_to_response("group/group_members.html", {
"members": members,
"group" : group,
"is_staff": group.is_staff,
"mods_enabled": mods_enabled,
"mods_available": mods_available,
}, context_instance=RequestContext(request))
def send_group_member_add_mail(request, group, from_user, to_user):
c = {
'email': from_user,
'to_email': to_user,
'group': group,
}
subject = _(u'You are invited to join a group on %s') % SITE_NAME
send_html_email(subject, 'group/add_member_email.html', c, None, [to_user])
@login_required_ajax
@group_staff_required
def ajax_add_group_member(request, group_id):
"""Add user to group in ajax.
"""
result = {}
content_type = 'application/json; charset=utf-8'
group = get_group(group_id)
if not group:
result['error'] = _(u'The group does not exist.')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
username = request.user.username
member_name_str = request.POST.get('user_name', '')
member_list = string2list(member_name_str)
member_list = [x.lower() for x in member_list]
# Add users to contacts.
for email in member_list:
if not is_valid_username(email):
continue
mail_sended.send(sender=None, user=username, email=email)
mail_sent_list = []
if is_org_context(request):
# Can only invite organization users to group
org_id = request.user.org.org_id
for email in member_list:
if not is_valid_username(email):
continue
if is_group_user(group.id, email):
continue
if not org_user_exists(org_id, email):
err_msg = _(u'Failed to add, %s is not in current organization.')
result['error'] = err_msg % email
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# Add user to group.
try:
ccnet_threaded_rpc.group_add_member(group.id,
username, email)
except SearpcError, e:
result['error'] = _(e.msg)
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
elif request.cloud_mode:
# check plan
group_members = getattr(request.user, 'group_members', -1)
if group_members > 0:
current_group_members = len(get_group_members(group.id))
if current_group_members > group_members:
result['error'] = _(u'You can only invite %d members.<a href="http://seafile.com/">Upgrade account.</a>') % group_members
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
# Can invite unregistered user to group.
for email in member_list:
if not is_valid_username(email):
continue
if is_group_user(group.id, email):
continue
# Add user to group, unregistered user will see the group
# when he logs in.
try:
ccnet_threaded_rpc.group_add_member(group.id,
username, email)
except SearpcError, e:
result['error'] = _(e.msg)
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
if not is_registered_user(email):
try:
send_group_member_add_mail(request, group, username, email)
mail_sent_list.append(email)
except Exception, e:
logger.warn(e)
else:
# Can only invite registered user to group if not in cloud mode.
for email in member_list:
if not is_valid_username(email):
continue
if is_group_user(group.id, email):
continue
if not is_registered_user(email):
err_msg = _(u'Failed to add, %s is not registerd.')
result['error'] = err_msg % email
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# Add user to group.
try:
ccnet_threaded_rpc.group_add_member(group.id,
username, email)
except SearpcError, e:
result['error'] = _(e.msg)
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
if mail_sent_list:
msg = ungettext(
'Successfully added. An email has been sent.',
'Successfully added. %(count)s emails have been sent.',
len(mail_sent_list)) % {
'count': len(mail_sent_list),
}
messages.success(request, msg)
else:
messages.success(request, _(u'Successfully added.'))
return HttpResponse(json.dumps('success'), status=200,
content_type=content_type)
@login_required
@group_staff_required
def batch_add_members(request, group_id):
"""Batch add users to group.
"""
group = get_group(group_id)
referer = request.META.get('HTTP_REFERER', None)
if not group:
next = SITE_ROOT if referer is None else referer
messages.error(request, _(u'The group does not exist.'))
return HttpResponseRedirect(next)
next = reverse('group_manage', args=[group_id]) \
if referer is None else referer
reader = []
form = BatchAddMembersForm(request.POST, request.FILES)
if form.is_valid():
uploaded_file = request.FILES['file']
if uploaded_file.size > 10 * 1024 * 1024:
messages.error(request, _(u'Failed, file is too large'))
return HttpResponseRedirect(next)
try:
content = uploaded_file.read()
encoding = chardet.detect(content)['encoding']
if encoding != 'utf-8':
content = content.decode(encoding, 'replace').encode('utf-8')
filestream = StringIO.StringIO(content)
reader = csv.reader(filestream)
except Exception as e:
logger.error(e)
messages.error(request, _(u'Failed'))
return HttpResponseRedirect(next)
user_domain = request.user.username.split('@')[1]
failed = []
success = []
member_list = []
for row in reader:
if not row:
continue
email = row[0].strip().lower()
if not is_valid_username(email):
failed.append(email)
continue
if is_group_user(group.id, email):
continue
email_domain = email.split('@')[1]
if email_domain != user_domain:
continue
member_list.append(email)
username = request.user.username
if is_org_context(request):
# Can only invite organization users to group
org_id = request.user.org.org_id
for email in member_list:
if not org_user_exists(org_id, email):
failed.append(email)
continue
# Add user to group.
try:
ccnet_threaded_rpc.group_add_member(group.id,
username,
email)
success.append(email)
except SearpcError, e:
failed.append(email)
logger.error(e)
continue
elif request.cloud_mode:
# check plan
group_members = getattr(request.user, 'group_members', -1)
if group_members > 0:
current_group_members = len(get_group_members(group.id))
if current_group_members > group_members:
messages.error(request, _(u'You can only invite %d members.<a href="http://seafile.com/">Upgrade account.</a>') % group_members)
return HttpResponseRedirect(next)
# Can invite unregistered user to group.
for email in member_list:
# Add user to group, unregistered user will see the group
# when he logs in.
try:
ccnet_threaded_rpc.group_add_member(group.id,
username,
email)
success.append(email)
except SearpcError as e:
failed.append(email)
logger.error(e)
continue
else:
# Can only invite registered user to group if not in cloud mode.
for email in member_list:
if not is_registered_user(email):
failed.append(email)
continue
# Add user to group.
try:
ccnet_threaded_rpc.group_add_member(group.id,
username,
email)
success.append(email)
except SearpcError, e:
failed.append(email)
logger.error(e)
continue
for email in success:
add_user_to_group.send(sender = None,
group_staff = username,
group_id = group_id,
added_user = email)
for email in failed:
messages.error(request, _(u'Failed to add %s to group.') % email)
return HttpResponseRedirect(next)
@login_required
@group_staff_required
def group_manage(request, group_id):
group = get_group(group_id)
if not group:
return HttpResponseRedirect(reverse('group_list', args=[]))
members_all = ccnet_threaded_rpc.get_group_members(group.id)
admins = [m for m in members_all if m.is_staff]
if PublicGroup.objects.filter(group_id=group.id):
group.is_pub = True
else:
group.is_pub = False
# get available modules(wiki, etc)
mods_available = get_available_mods_by_group(group.id)
mods_enabled = get_enabled_mods_by_group(group.id)
ENABLE_MAKE_GROUP_PUBLIC = getattr(settings,
'ENABLE_MAKE_GROUP_PUBLIC', False)
if ENABLE_MAKE_GROUP_PUBLIC and not request.user.org:
can_make_group_public = True
else:
can_make_group_public = False
return render_to_response('group/group_manage.html', {
'group': group,
'members': members_all,
'admins': admins,
'is_staff': True,
"mods_enabled": mods_enabled,
"mods_available": mods_available,
"can_make_group_public": can_make_group_public,
}, context_instance=RequestContext(request))
@login_required_ajax
@group_staff_required
def group_add_admin(request, group_id):
"""
Add group admin.
"""
group_id = int(group_id) # Checked by URL Conf
if request.method != 'POST':
raise Http404
result = {}
content_type = 'application/json; charset=utf-8'
member_name_str = request.POST.get('user_name', '')
member_list = string2list(member_name_str)
member_list = [x.lower() for x in member_list]
for member_name in member_list:
if not is_valid_username(member_name):
err_msg = _(u'Failed to add, %s is not a valid email.') % member_name
result['error'] = err_msg
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# Add user to contacts.
mail_sended.send(sender=None, user=request.user.username,
email=member_name)
if not is_registered_user(member_name):
err_msg = _(u'Failed to add, %s is not registrated.') % member_name
result['error'] = err_msg
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# Check whether user is in the group
if is_group_user(group_id, member_name):
try:
ccnet_threaded_rpc.group_set_admin(group_id, member_name)
except SearpcError, e:
result['error'] = _(e.msg)
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
else:
# check plan
group_members = getattr(request.user, 'group_members', -1)
if group_members > 0:
current_group_members = len(get_group_members(group_id))
if current_group_members > group_members:
result['error'] = _(u'You can only invite %d members.<a href="http://seafile.com/">Upgrade account.</a>') % group_members
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
try:
ccnet_threaded_rpc.group_add_member(group_id,
request.user.username,
member_name)
ccnet_threaded_rpc.group_set_admin(group_id, member_name)
except SearpcError, e:
result['error'] = _(e.msg)
return HttpResponse(json.dumps(result), status=500,
content_type=content_type)
messages.success(request, _(u'Operation succeeded.'))
result['success'] = True
return HttpResponse(json.dumps(result), status=200, content_type=content_type)
@login_required
@group_staff_required
@require_POST
def group_remove_admin(request, group_id):
"""
Remove group admin, and becomes normal group member.
"""
user = request.GET.get('u', '')
if not is_valid_username(user):
messages.error(request, _(u'%s is not a valid email.') % user)
return HttpResponseRedirect(reverse('group_manage', args=[group_id]))
try:
ccnet_threaded_rpc.group_unset_admin(int(group_id), user)
messages.success(request, _(u'Operation succeeded.'))
except SearpcError, e:
messages.error(request, _(e.msg))
return HttpResponseRedirect(reverse('group_manage', args=[group_id]))
@login_required
def group_member_operations(request, group_id, user_name):
if request.GET.get('op','') == 'delete':
return group_remove_member(request, group_id, user_name)
else:
return HttpResponseRedirect(reverse('group_manage', args=[group_id]))
def group_remove_member(request, group_id, user_name):
group_id_int = int(group_id) # Checked by URLConf
group = get_group(group_id_int)
if not group:
raise Http404
if not is_group_staff(group, request.user):
raise Http404
if not is_valid_username(user_name):
messages.error(request, _(u'%s is not a valid email.') % user_name)
return HttpResponseRedirect(reverse('group_manage', args=[group_id]))
try:
ccnet_threaded_rpc.group_remove_member(group.id,
request.user.username,
user_name)
seafserv_threaded_rpc.remove_repo_group(group.id, user_name)
messages.success(request, _(u'Operation succeeded.'))
except SearpcError, e:
messages.error(request, _(u'Failed:%s') % _(e.msg))
return HttpResponseRedirect(reverse('group_manage', args=[group_id]))
@login_required_ajax
def group_recommend(request):
"""
Get or post file/directory discussions to a group.
"""
content_type = 'application/json; charset=utf-8'
result = {}
if request.method == 'POST':
form = GroupRecommendForm(request.POST)
if form.is_valid():
repo_id = form.cleaned_data['repo_id']
attach_type = form.cleaned_data['attach_type']
path = form.cleaned_data['path']
message = form.cleaned_data['message']
# groups is a group_id list, e.g. [u'1', u'7']
groups = request.POST.getlist('groups')
username = request.user.username
groups_not_in = []
groups_posted_to = []
for group_id in groups:
# Check group id format
try:
group_id = int(group_id)
except ValueError:
result['error'] = _(u'Error: wrong group id')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
group = get_group(group_id)
if not group:
result['error'] = _(u'Error: the group does not exist.')
return HttpResponse(json.dumps(result), status=400,
content_type=content_type)
# TODO: Check whether repo is in the group and Im in the group
if not is_group_user(group_id, username):
groups_not_in.append(group.group_name)
continue
# save message to group
gm = GroupMessage(group_id=group_id, from_email=username,
message=message)
gm.save()
# send signal
grpmsg_added.send(sender=GroupMessage, group_id=group_id,
from_email=username, message=message)
# save attachment
ma = MessageAttachment(group_message=gm, repo_id=repo_id,
attach_type=attach_type, path=path,
src='recommend')
ma.save()
# save discussion
fd = FileDiscuss(group_message=gm, repo_id=repo_id, path=path)
fd.save()
group_url = reverse('group_discuss', args=[group_id])
groups_posted_to.append(u'<a href="%(url)s" target="_blank">%(name)s</a>' % \
{'url':group_url, 'name':group.group_name})
if len(groups_posted_to) > 0:
result['success'] = _(u'Successfully posted to %(groups)s.') % {'groups': ', '.join(groups_posted_to)}
if len(groups_not_in) > 0:
result['error'] = _(u'Error: you are not in group %s.') % (', '.join(groups_not_in))
else:
result['error'] = str(form.errors)
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
# request.method == 'GET'
else:
repo_id = request.GET.get('repo_id')
path = request.GET.get('path', None)
repo = get_repo(repo_id)
if not repo:
result['error'] = _(u'Error: the library does not exist.')
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
if path is None:
result['error'] = _(u'Error: no path.')
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
# get discussions & replies
path_hash = calc_file_path_hash(path)
discussions = FileDiscuss.objects.filter(path_hash=path_hash, repo_id=repo_id)
msg_ids = [ e.group_message_id for e in discussions ]
grp_msgs = GroupMessage.objects.filter(id__in=msg_ids).order_by('-timestamp')
msg_replies = MessageReply.objects.filter(reply_to__in=grp_msgs)
for msg in grp_msgs:
msg.replies = []
for reply in msg_replies:
if msg.id == reply.reply_to_id:
msg.replies.append(reply)
msg.reply_cnt = len(msg.replies)
msg.replies = msg.replies[-3:]
ctx = {}
ctx['messages'] = grp_msgs
html = render_to_string("group/discussion_list.html", ctx)
result['html'] = html
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
def create_group_repo(request, group_id):
"""Create a repo and share it to current group"""
content_type = 'application/json; charset=utf-8'
def json_error(err_msg):
result = {'error': err_msg}
return HttpResponseBadRequest(json.dumps(result),
content_type=content_type)
group_id = int(group_id)
group = get_group(group_id)
if not group:
return json_error(_(u'Failed to create: the group does not exist.'))
# Check whether user belongs to the group.
username = request.user.username
if not is_group_user(group_id, username):
return json_error(_(u'Failed to create: you are not in the group.'))
form = SharedRepoCreateForm(request.POST)
if not form.is_valid():
return json_error(str(form.errors.values()[0]))
# Form is valid, create group repo
repo_name = form.cleaned_data['repo_name']
repo_desc = form.cleaned_data['repo_desc']
permission = form.cleaned_data['permission']
encryption = int(form.cleaned_data['encryption'])
uuid = form.cleaned_data['uuid']
magic_str = form.cleaned_data['magic_str']
encrypted_file_key = form.cleaned_data['encrypted_file_key']
if is_org_context(request):
org_id = request.user.org.org_id
try:
if encryption:
repo_id = seafile_api.create_org_enc_repo(
uuid, repo_name, repo_desc, username, magic_str,
encrypted_file_key, enc_version=2, org_id=org_id)
else:
repo_id = seafile_api.create_org_repo(repo_name, repo_desc,
username, None, org_id)
except SearpcError, e:
logger.error(e)
return json_error(_(u'Failed to create'))
try:
seafile_api.add_org_group_repo(repo_id, org_id, group.id,
username, permission)
except SearpcError, e:
logger.error(e)
return json_error(_(u'Failed to create: internal error.'))
else:
return HttpResponse(json.dumps({'success': True}),
content_type=content_type)
else:
try:
if encryption:
repo_id = seafile_api.create_enc_repo(
uuid, repo_name, repo_desc, username, magic_str,
encrypted_file_key, enc_version=2)
else:
repo_id = seafile_api.create_repo(repo_name, repo_desc,
username, None)
except SearpcError, e:
logger.error(e)
return json_error(_(u'Failed to create'))
try:
seafile_api.set_group_repo(repo_id, group.id, username, permission)
except SearpcError, e:
logger.error(e)
return json_error(_(u'Failed to create: internal error.'))
else:
return HttpResponse(json.dumps({'success': True}),
content_type=content_type)
@login_required_ajax
def attention(request):
"""
Handle ajax request to query group members used in autocomplete.
"""
user = request.user.username
name_str = request.GET.get('name_startsWith')
gids = request.GET.get('gids', '')
result = []
members = []
for gid in gids.split('_'):
try:
gid = int(gid)
except ValueError:
continue
if not is_group_user(gid, user):
continue
# Get all group users
members += get_group_members(gid)
member_names = []
for m in members:
if len(result) == 10: # Return at most 10 results.
break
if m.user_name == user:
continue
if m.user_name in member_names:
# Remove duplicated member names
continue
else:
member_names.append(m.user_name)
from seahub.base.templatetags.seahub_tags import email2nickname, char2pinyin
nickname = email2nickname(m.user_name)
pinyin = char2pinyin(nickname)
if nickname.startswith(name_str) or pinyin.startswith(name_str):
result.append({'contact_name': nickname})
content_type = 'application/json; charset=utf-8'
return HttpResponse(json.dumps(result), content_type=content_type)
@group_check
def group_add_discussion(request, group):
if not request.is_ajax() or request.method != 'POST':
raise Http404
# only login user can post to public group
if group.view_perm == "pub" and not request.user.is_authenticated():
raise Http404
content_type = 'application/json; charset=utf-8'
result = {}
username = request.user.username
#form = MessageForm(request.POST)
msg = request.POST.get('message')
selected = request.POST.getlist('selected') # files selected as attachment
if not msg:
result['error'] = _(u'Discussion is required.')
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
gm = GroupMessage()
gm.group_id = group.id
gm.from_email = username
gm.message = msg
gm.save()
# send signal
grpmsg_added.send(sender=GroupMessage, group_id=group.id,
from_email=username, message=msg)
gm.attachments = []
if selected:
for item in selected:
if item[-1] == '/': # dir is not allowed, for now
continue
repo_id = item[0:36]
path = item[36:]
ma = MessageAttachment(group_message=gm, repo_id=repo_id,
attach_type='file', path=path, src='recommend')
ma.save()
ma.name = os.path.basename(path)
gm.attachments.append(ma)
ctx = { 'msg': gm }
msg_html = render_to_string("group/new_discussion_con.html", ctx,
context_instance=RequestContext(request))
return HttpResponse(json.dumps({'msg_id': gm.id, 'msg_con': msg_html}), content_type=content_type)
@group_check
def group_discuss(request, group):
if group.is_pub:
raise Http404
username = request.user.username
form = MessageForm()
# remove user notifications
UserNotification.objects.seen_group_msg_notices(username, group.id)
# Get all group members.
members = get_group_members(group.id)
"""group messages"""
# Show 15 group messages per page.
paginator = Paginator(GroupMessage.objects.filter(
group_id=group.id).order_by('-timestamp'), 15)
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
group_msgs = paginator.page(page)
except (EmptyPage, InvalidPage):
group_msgs = paginator.page(paginator.num_pages)
group_msgs.page_range = paginator.get_page_range(group_msgs.number)
# Force evaluate queryset to fix some database error for mysql.
group_msgs.object_list = list(group_msgs.object_list)
msg_attachments = MessageAttachment.objects.filter(group_message__in=group_msgs.object_list)
msg_replies = MessageReply.objects.filter(reply_to__in=group_msgs.object_list)
reply_to_list = [ r.reply_to_id for r in msg_replies ]
for msg in group_msgs.object_list:
msg.reply_cnt = reply_to_list.count(msg.id)
msg.replies = []
for r in msg_replies:
if msg.id == r.reply_to_id:
msg.replies.append(r)
msg.replies = msg.replies[-3:]
msg.attachments = []
for att in msg_attachments:
if att.group_message_id != msg.id:
continue
# Attachment name is file name or directory name.
# If is top directory, use repo name instead.
path = att.path
if path == '/':
repo = get_repo(att.repo_id)
if not repo:
# TODO: what should we do here, tell user the repo
# is no longer exists?
continue
att.name = repo.name
else:
path = path.rstrip('/') # cut out last '/' if possible
att.name = os.path.basename(path)
# Load to discuss page if attachment is a image and from recommend.
if att.attach_type == 'file' and att.src == 'recommend':
att.filetype, att.fileext = get_file_type_and_ext(att.name)
if att.filetype == IMAGE:
att.obj_id = get_file_id_by_path(att.repo_id, path)
if not att.obj_id:
att.err = _(u'File does not exist')
else:
att.token = seafile_api.get_fileserver_access_token(
att.repo_id, att.obj_id, 'view', username)
att.img_url = gen_file_get_url(att.token, att.name)
msg.attachments.append(att)
# get available modules(wiki, etc)
mods_available = get_available_mods_by_group(group.id)
mods_enabled = get_enabled_mods_by_group(group.id)
return render_to_response("group/group_discuss.html", {
"group" : group,
"is_staff": group.is_staff,
"group_msgs": group_msgs,
"form": form,
"mods_enabled": mods_enabled,
"mods_available": mods_available,
}, context_instance=RequestContext(request))
@group_staff_required
@group_check
def group_toggle_modules(request, group):
"""Enable or disable modules.
"""
if request.method != 'POST':
raise Http404
referer = request.META.get('HTTP_REFERER', None)
next = SITE_ROOT if referer is None else referer
username = request.user.username
group_wiki = request.POST.get('group_wiki', 'off')
if group_wiki == 'on':
enable_mod_for_group(group.id, MOD_GROUP_WIKI)
messages.success(request, _('Successfully enable "Wiki".'))
else:
disable_mod_for_group(group.id, MOD_GROUP_WIKI)
if referer.find('wiki') > 0:
next = reverse('group_info', args=[group.id])
messages.success(request, _('Successfully disable "Wiki".'))
return HttpResponseRedirect(next)
########## wiki
@group_check
def group_wiki(request, group, page_name="home"):
username = request.user.username
# get available modules(wiki, etc)
mods_available = get_available_mods_by_group(group.id)
mods_enabled = get_enabled_mods_by_group(group.id)
wiki_exists = True
try:
content, repo, dirent = get_group_wiki_page(username, group, page_name)
except WikiDoesNotExist:
wiki_exists = False
group_repos = get_group_repos(group.id, username)
group_repos = [r for r in group_repos if not r.encrypted]
return render_to_response("group/group_wiki.html", {
"group" : group,
"is_staff": group.is_staff,
"wiki_exists": wiki_exists,
"mods_enabled": mods_enabled,
"mods_available": mods_available,
"group_repos": group_repos,
}, context_instance=RequestContext(request))
except WikiPageMissing:
'''create that page for user if he/she is a group member'''
if not is_group_user(group.id, username):
raise Http404
repo = get_group_wiki_repo(group, username)
# No need to check whether repo is none, since repo is already created
filename = page_name_to_file_name(clean_page_name(page_name))
if not post_empty_file(repo.id, "/", filename, username):
return render_error(request, _("Failed to create wiki page. Please retry later."))
return HttpResponseRedirect(reverse('group_wiki', args=[group.id, page_name]))
else:
url_prefix = reverse('group_wiki', args=[group.id])
# fetch file modified time and modifier
path = '/' + dirent.obj_name
try:
dirent = seafile_api.get_dirent_by_path(repo.id, path)
if dirent:
latest_contributor, last_modified = dirent.modifier, dirent.mtime
else:
latest_contributor, last_modified = None, 0
except SearpcError as e:
logger.error(e)
latest_contributor, last_modified = None, 0
repo_perm = seafile_api.check_repo_access_permission(repo.id, username)
wiki_index_exists = True
index_pagename = 'index'
index_content = None
try:
index_content, index_repo, index_dirent = get_group_wiki_page(username, group, index_pagename)
except (WikiDoesNotExist, WikiPageMissing) as e:
wiki_index_exists = False
return render_to_response("group/group_wiki.html", {
"group" : group,
"is_staff": group.is_staff,
"wiki_exists": wiki_exists,
"content": content,
"page": os.path.splitext(dirent.obj_name)[0],
"last_modified": last_modified,
"latest_contributor": latest_contributor or _("Unknown"),
"path": path,
"repo_id": repo.id,
"search_repo_id": repo.id,
"search_wiki": True,
"mods_enabled": mods_enabled,
"mods_available": mods_available,
"repo_perm": repo_perm,
"wiki_index_exists": wiki_index_exists,
"index_content": index_content,
}, context_instance=RequestContext(request))
@group_check
def group_wiki_pages(request, group):
"""
List wiki pages in group.
"""
username = request.user.username
try:
repo = get_group_wiki_repo(group, username)
pages = get_wiki_pages(repo)
except SearpcError:
return render_error(request, _('Internal Server Error'))
except WikiDoesNotExist:
return render_error(request, _('Wiki does not exists.'))
repo_perm = seafile_api.check_repo_access_permission(repo.id, username)
mods_available = get_available_mods_by_group(group.id)
mods_enabled = get_enabled_mods_by_group(group.id)
return render_to_response("group/group_wiki_pages.html", {
"group": group,
"pages": pages,
"is_staff": group.is_staff,
"repo_id": repo.id,
"search_repo_id": repo.id,
"search_wiki": True,
"repo_perm": repo_perm,
"mods_enabled": mods_enabled,
"mods_available": mods_available,
}, context_instance=RequestContext(request))
@login_required_ajax
@group_check
def group_wiki_create(request, group):
if group.view_perm == "pub":
raise Http404
if request.method != 'POST':
raise Http404
content_type = 'application/json; charset=utf-8'
def json_error(err_msg, status=400):
result = {'error': err_msg}
return HttpResponse(json.dumps(result), status=status,
content_type=content_type)
form = WikiCreateForm(request.POST)
if not form.is_valid():
return json_error(str(form.errors.values()[0]))
# create group repo in user context
repo_name = form.cleaned_data['repo_name']
repo_desc = form.cleaned_data['repo_desc']
user = request.user.username
passwd = <PASSWORD>
permission = "rw"
repo_id = create_repo(repo_name, repo_desc, user, passwd)
if not repo_id:
return json_error(_(u'Failed to create'), 500)
try:
seafile_api.set_group_repo(repo_id, group.id, user, permission)
except SearpcError as e:
remove_repo(repo_id)
return json_error(_(u'Failed to create: internal error.'), 500)
GroupWiki.objects.save_group_wiki(group_id=group.id, repo_id=repo_id)
# create home page
page_name = "home.md"
if not post_empty_file(repo_id, "/", page_name, user):
return json_error(_(u'Failed to create home page. Please retry later'), 500)
next = reverse('group_wiki', args=[group.id])
return HttpResponse(json.dumps({'href': next}), content_type=content_type)
@group_check
def group_wiki_use_lib(request, group):
if group.view_perm == "pub":
raise Http404
if request.method != 'POST':
raise Http404
repo_id = request.POST.get('dst_repo', '')
username = request.user.username
next = reverse('group_wiki', args=[group.id])
repo = seafile_api.get_repo(repo_id)
if repo is None:
messages.error(request, _('Failed to set wiki library.'))
return HttpResponseRedirect(next)
GroupWiki.objects.save_group_wiki(group_id=group.id, repo_id=repo_id)
# create home page if not exist
page_name = "home.md"
if not seaserv.get_file_id_by_path(repo_id, "/" + page_name):
if not seaserv.post_empty_file(repo_id, "/", page_name, username):
messages.error(request, _('Failed to create home page. Please retry later'))
return HttpResponseRedirect(next)
@group_check
def group_wiki_page_new(request, group, page_name="home"):
if group.view_perm == "pub":
raise Http404
if request.method == 'POST':
form = MessageForm(request.POST)
page_name = request.POST.get('page_name', '')
if not page_name:
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
page_name = clean_page_name(page_name)
try:
repo = get_group_wiki_repo(group, request.user.username)
except WikiDoesNotExist:
return render_error(request, _('Wiki is not found.'))
filename = page_name + ".md"
filepath = "/" + page_name + ".md"
# check whether file exists
if get_file_id_by_path(repo.id, filepath):
return render_error(request, _('Page "%s" already exists.') % filename)
if not post_empty_file(repo.id, "/", filename, request.user.username):
return render_error(request, _('Failed to create wiki page. Please retry later.'))
url = "%s?p=%s&from=wiki_page_new&gid=%s" % (
reverse('file_edit', args=[repo.id]),
urllib2.quote(filepath.encode('utf-8')), group.id)
return HttpResponseRedirect(url)
@group_check
def group_wiki_page_edit(request, group, page_name="home"):
if group.view_perm == "pub":
raise Http404
try:
repo = get_group_wiki_repo(group, request.user.username)
except WikiDoesNotExist:
return render_error(request, _('Wiki is not found.'))
filepath = "/" + page_name + ".md"
url = "%s?p=%s&from=wiki_page_edit&gid=%s" % (
reverse('file_edit', args=[repo.id]),
urllib2.quote(filepath.encode('utf-8')), group.id)
return HttpResponseRedirect(url)
@group_check
def group_wiki_page_delete(request, group, page_name):
if group.view_perm == "pub":
raise Http404
try:
repo = get_group_wiki_repo(group, request.user.username)
except WikiDoesNotExist:
return render_error(request, _('Wiki is not found.'))
file_name = page_name + '.md'
user = request.user.username
if del_file(repo.id, '/', file_name, user):
messages.success(request, _('Successfully deleted "%s".') % page_name)
else:
messages.error(request, _('Failed to delete "%s". Please retry later.') % page_name)
return HttpResponseRedirect(reverse('group_wiki', args=[group.id]))
<file_sep>/seahub/notifications/models.py
# -*- coding: utf-8 -*-
import datetime
import os
import json
import logging
from django.db import models
from django.db.models.signals import post_save
from django.forms import ModelForm, Textarea
from django.utils.http import urlquote
from django.utils.html import escape
from django.utils.translation import ugettext as _
import seaserv
from seaserv import seafile_api
from seahub.base.fields import LowerCaseCharField
from seahub.base.templatetags.seahub_tags import email2nickname
# Get an instance of a logger
logger = logging.getLogger(__name__)
########## system notification
class Notification(models.Model):
message = models.CharField(max_length=512)
primary = models.BooleanField(default=False)
class NotificationForm(ModelForm):
"""
Form for adding notification.
"""
class Meta:
model = Notification
fields = ('message', 'primary')
widgets = {
'message': Textarea(),
}
########## user notification
MSG_TYPE_GROUP_MSG = 'group_msg'
MSG_TYPE_GROUP_JOIN_REQUEST = 'group_join_request'
MSG_TYPE_ADD_USER_TO_GROUP = 'add_user_to_group'
MSG_TYPE_GRPMSG_REPLY = 'grpmsg_reply'
MSG_TYPE_FILE_UPLOADED = 'file_uploaded'
MSG_TYPE_REPO_SHARE = 'repo_share'
MSG_TYPE_PRIV_FILE_SHARE = 'priv_file_share'
MSG_TYPE_USER_MESSAGE = 'user_message'
def file_uploaded_msg_to_json(file_name, repo_id, uploaded_to):
"""Encode file uploaded message to json string.
"""
return json.dumps({'file_name': file_name, 'repo_id': repo_id,
'uploaded_to': uploaded_to})
def repo_share_msg_to_json(share_from, repo_id):
return json.dumps({'share_from': share_from, 'repo_id': repo_id})
def priv_file_share_msg_to_json(share_from, file_name, priv_share_token):
return json.dumps({'share_from': share_from, 'file_name': file_name,
'priv_share_token': priv_share_token})
def group_msg_to_json(group_id, msg_from, message):
return json.dumps({'group_id': group_id, 'msg_from': msg_from,
'message': message})
def grpmsg_reply_to_json(msg_id, reply_from, grpmsg_topic, reply_msg):
return json.dumps({'msg_id': msg_id, 'reply_from': reply_from,
'grpmsg_topic': grpmsg_topic, 'reply_msg': reply_msg})
def user_msg_to_json(message, msg_from):
return json.dumps({'message': message, 'msg_from': msg_from})
def group_join_request_to_json(username, group_id, join_request_msg):
return json.dumps({'username': username, 'group_id': group_id,
'join_request_msg': join_request_msg})
def add_user_to_group_to_json(group_staff, group_id):
return json.dumps({'group_staff': group_staff,
'group_id': group_id})
class UserNotificationManager(models.Manager):
def _add_user_notification(self, to_user, msg_type, detail):
"""Add generic user notification.
Arguments:
- `self`:
- `username`:
- `detail`:
"""
n = super(UserNotificationManager, self).create(
to_user=to_user, msg_type=msg_type, detail=detail)
n.save()
return n
def get_all_notifications(self, seen=None, time_since=None):
"""Get all notifications of all users.
Arguments:
- `self`:
- `seen`:
- `time_since`:
"""
qs = super(UserNotificationManager, self).all()
if seen is not None:
qs = qs.filter(seen=seen)
if time_since is not None:
qs = qs.filter(timestamp__gt=time_since)
return qs
def get_user_notifications(self, username, seen=None):
"""Get all notifications(group_msg, grpmsg_reply, etc) of a user.
Arguments:
- `self`:
- `username`:
"""
qs = super(UserNotificationManager, self).filter(to_user=username)
if seen is not None:
qs = qs.filter(seen=seen)
return qs
def remove_user_notifications(self, username):
"""Remove all user notifications.
Arguments:
- `self`:
- `username`:
"""
self.get_user_notifications(username).delete()
def count_unseen_user_notifications(self, username):
"""
Arguments:
- `self`:
- `username`:
"""
return super(UserNotificationManager, self).filter(
to_user=username, seen=False).count()
def bulk_add_group_msg_notices(self, to_users, detail):
"""Efficiently add group message notices.
NOTE: ``pre_save`` and ``post_save`` signals will not be sent.
Arguments:
- `self`:
- `to_users`:
- `detail`:
"""
user_notices = [ UserNotification(to_user=m,
msg_type=MSG_TYPE_GROUP_MSG,
detail=detail
) for m in to_users ]
UserNotification.objects.bulk_create(user_notices)
def seen_group_msg_notices(self, to_user, group_id):
"""Mark group message notices of a user as seen.
"""
user_notices = super(UserNotificationManager, self).filter(
to_user=to_user, msg_type=MSG_TYPE_GROUP_MSG)
for notice in user_notices:
try:
gid = notice.group_message_detail_to_dict().get('group_id')
if gid == group_id:
if notice.seen is False:
notice.seen = True
notice.save()
except UserNotification.InvalidDetailError:
continue
def seen_group_msg_reply_notice(self, to_user, msg_id=None):
"""Mark all group message replies of a user as seen.
Arguments:
- `self`:
- `to_user`:
- `msg_id`:
"""
if not msg_id:
super(UserNotificationManager, self).filter(
to_user=to_user, msg_type=MSG_TYPE_GRPMSG_REPLY,
seen=False).update(seen=True)
else:
notifs = super(UserNotificationManager, self).filter(
to_user=to_user, msg_type=MSG_TYPE_GRPMSG_REPLY,
seen=False)
for n in notifs:
d = n.grpmsg_reply_detail_to_dict()
if msg_id == d['msg_id']:
n.seen = True
n.save()
def seen_user_msg_notices(self, to_user, from_user):
"""Mark priv message notices of a user as seen.
"""
user_notices = super(UserNotificationManager, self).filter(
to_user=to_user, seen=False, msg_type=MSG_TYPE_USER_MESSAGE)
for notice in user_notices:
notice_from_user = notice.user_message_detail_to_dict().get('msg_from')
if from_user == notice_from_user:
if notice.seen is False:
notice.seen = True
notice.save()
def remove_group_msg_notices(self, to_user, group_id):
"""Remove group message notices of a user.
"""
super(UserNotificationManager, self).filter(
to_user=to_user, msg_type=MSG_TYPE_GROUP_MSG,
detail=str(group_id)).delete()
def add_group_msg_reply_notice(self, to_user, detail):
"""Added group message reply notice for user.
Arguments:
- `self`:
- `to_user`:
- `msg_id`:
"""
return self._add_user_notification(to_user,
MSG_TYPE_GRPMSG_REPLY, detail)
def get_group_msg_reply_notices(self, to_user, seen=None):
"""Get all group message replies of a user.
Arguments:
- `self`:
- `to_user`:
- `msg_id`:
"""
qs = super(UserNotificationManager, self).filter(
to_user=to_user, msg_type=MSG_TYPE_GRPMSG_REPLY)
if seen is not None:
qs = qs.filter(seen=seen)
return qs
def remove_group_msg_reply_notice(self, to_user):
"""Mark all group message replies of a user as seen.
Arguments:
- `self`:
- `to_user`:
- `msg_id`:
"""
super(UserNotificationManager, self).filter(
to_user=to_user, msg_type=MSG_TYPE_GRPMSG_REPLY).delete()
def add_group_join_request_notice(self, to_user, detail):
"""
Arguments:
- `self`:
- `to_user`:
- `detail`:
"""
return self._add_user_notification(to_user,
MSG_TYPE_GROUP_JOIN_REQUEST, detail)
def set_add_user_to_group_notice(self, to_user, detail):
"""
Arguments:
- `self`:
- `to_user`:
- `detail`:
"""
return self._add_user_notification(to_user,
MSG_TYPE_ADD_USER_TO_GROUP,
detail)
def add_file_uploaded_msg(self, to_user, detail):
"""
Arguments:
- `self`:
- `to_user`:
- `file_name`:
- `upload_to`:
"""
return self._add_user_notification(to_user,
MSG_TYPE_FILE_UPLOADED, detail)
def add_repo_share_msg(self, to_user, detail):
"""Notify ``to_user`` that others shared a repo to him/her.
Arguments:
- `self`:
- `to_user`:
- `repo_id`:
"""
return self._add_user_notification(to_user,
MSG_TYPE_REPO_SHARE, detail)
def add_priv_file_share_msg(self, to_user, detail):
"""Notify ``to_user`` that others shared a file to him/her.
Arguments:
- `self`:
- `to_user`:
- `detail`:
"""
return self._add_user_notification(to_user,
MSG_TYPE_PRIV_FILE_SHARE, detail)
def add_user_message(self, to_user, detail):
"""Notify ``to_user`` that others sent a message to him/her.
Arguments:
- `self`:
- `to_user`:
- `detail`:
"""
return self._add_user_notification(to_user,
MSG_TYPE_USER_MESSAGE, detail)
class UserNotification(models.Model):
to_user = LowerCaseCharField(db_index=True, max_length=255)
msg_type = models.CharField(db_index=True, max_length=30)
detail = models.TextField()
timestamp = models.DateTimeField(default=datetime.datetime.now)
seen = models.BooleanField('seen', default=False)
objects = UserNotificationManager()
class InvalidDetailError(Exception):
pass
class Meta:
ordering = ["-timestamp"]
def __unicode__(self):
return '%s|%s|%s' % (self.to_user, self.msg_type, self.detail)
def is_seen(self):
"""Returns value of ``self.seen`` but also changes it to ``True``.
Use this in a template to mark an unseen notice differently the first
time it is shown.
Arguments:
- `self`:
"""
seen = self.seen
if seen is False:
self.seen = True
self.save()
return seen
def is_group_msg(self):
"""Check whether is a group message notification.
Arguments:
- `self`:
"""
return self.msg_type == MSG_TYPE_GROUP_MSG
def is_grpmsg_reply(self):
"""Check whether is a group message reply notification.
Arguments:
- `self`:
"""
return self.msg_type == MSG_TYPE_GRPMSG_REPLY
def is_file_uploaded_msg(self):
"""
Arguments:
- `self`:
"""
return self.msg_type == MSG_TYPE_FILE_UPLOADED
def is_repo_share_msg(self):
"""
Arguments:
- `self`:
"""
return self.msg_type == MSG_TYPE_REPO_SHARE
def is_priv_file_share_msg(self):
"""
Arguments:
- `self`:
"""
return self.msg_type == MSG_TYPE_PRIV_FILE_SHARE
def is_user_message(self):
"""
Arguments:
- `self`:
"""
return self.msg_type == MSG_TYPE_USER_MESSAGE
def is_group_join_request(self):
"""
Arguments:
- `self`:
"""
return self.msg_type == MSG_TYPE_GROUP_JOIN_REQUEST
def is_add_user_to_group(self):
"""
Arguments:
- `self`:
"""
return self.msg_type == MSG_TYPE_ADD_USER_TO_GROUP
def group_message_detail_to_dict(self):
"""Parse group message detail, returns dict contains ``group_id`` and
``msg_from``.
NOTE: ``msg_from`` may be ``None``.
Arguments:
- `self`:
Raises ``InvalidDetailError`` if detail field can not be parsed.
"""
assert self.is_group_msg()
try:
detail = json.loads(self.detail)
except ValueError:
raise self.InvalidDetailError, 'Wrong detail format of group message'
else:
if isinstance(detail, int): # Compatible with existing records
group_id = detail
msg_from = None
return {'group_id': group_id, 'msg_from': msg_from}
elif isinstance(detail, dict):
group_id = detail['group_id']
msg_from = detail['msg_from']
if 'message' in detail:
message = detail['message']
return {'group_id': group_id, 'msg_from': msg_from, 'message': message}
else:
return {'group_id': group_id, 'msg_from': msg_from}
else:
raise self.InvalidDetailError, 'Wrong detail format of group message'
def grpmsg_reply_detail_to_dict(self):
"""Parse group message reply detail, returns dict contains
``msg_id``, ``reply_from`` and ``reply_msg``.
NOTE: ``reply_from`` and ``reply_msg`` may be ``None``.
Arguments:
- `self`:
Raises ``InvalidDetailError`` if detail field can not be parsed.
"""
assert self.is_grpmsg_reply()
try:
detail = json.loads(self.detail)
except ValueError:
raise self.InvalidDetailError, 'Wrong detail format of group message reply'
else:
if isinstance(detail, int): # Compatible with existing records
msg_id = detail
reply_from = None
reply_msg = None
return {'msg_id': msg_id, 'reply_from': reply_from,
'reply_msg': reply_msg}
elif isinstance(detail, dict):
msg_id = detail['msg_id']
reply_from = detail['reply_from']
reply_msg = detail.get('reply_msg')
grpmsg_topic = detail.get('grpmsg_topic')
return {'msg_id': msg_id, 'reply_from': reply_from,
'grpmsg_topic': grpmsg_topic, 'reply_msg': reply_msg}
else:
raise self.InvalidDetailError, 'Wrong detail format of group message reply'
def user_message_detail_to_dict(self):
"""Parse user message detail, returns dict contains ``message`` and
``msg_from``.
Arguments:
- `self`:
"""
assert self.is_user_message()
try:
detail = json.loads(self.detail)
except ValueError:
msg_from = self.detail
message = None
return {'message': message, 'msg_from': msg_from}
else:
message = detail['message']
msg_from = detail['msg_from']
return {'message': message, 'msg_from': msg_from}
########## functions used in templates
def format_file_uploaded_msg(self):
"""
Arguments:
- `self`:
"""
try:
d = json.loads(self.detail)
except Exception as e:
logger.error(e)
return _(u"Internal error")
filename = d['file_name']
repo_id = d['repo_id']
repo = seafile_api.get_repo(repo_id)
if repo:
if d['uploaded_to'] == '/':
# current upload path is '/'
file_path = '/' + filename
link = reverse('view_common_lib_dir', args=[repo_id, ''])
name = repo.name
else:
uploaded_to = d['uploaded_to'].rstrip('/')
file_path = uploaded_to + '/' + filename
link = reverse('view_common_lib_dir', args=[repo_id, urlquote(uploaded_to.lstrip('/'))])
name = os.path.basename(uploaded_to)
file_link = reverse('view_lib_file', args=[repo_id, urlquote(file_path)])
msg = _(u"A file named <a href='%(file_link)s'>%(file_name)s</a> is uploaded to <a href='%(link)s'>%(name)s</a>") % {
'file_link': file_link,
'file_name': escape(filename),
'link': link,
'name': escape(name),
}
else:
msg = _(u"A file named <strong>%(file_name)s</strong> is uploaded to <strong>Deleted Library</strong>") % {
'file_name': escape(filename),
}
return msg
def format_repo_share_msg(self):
"""
Arguments:
- `self`:
"""
try:
d = json.loads(self.detail)
except Exception as e:
logger.error(e)
return _(u"Internal error")
share_from = email2nickname(d['share_from'])
repo_id = d['repo_id']
repo = seafile_api.get_repo(repo_id)
if repo is None:
self.delete()
return None
msg = _(u"%(user)s has shared a library named <a href='%(href)s'>%(repo_name)s</a> to you.") % {
'user': escape(share_from),
'href': reverse('view_common_lib_dir', args=[repo.id, '']),
'repo_name': escape(repo.name),
}
return msg
def format_priv_file_share_msg(self):
"""
Arguments:
- `self`:
"""
try:
d = json.loads(self.detail)
except Exception as e:
logger.error(e)
return _(u"Internal error")
share_from = email2nickname(d['share_from'])
file_name = d['file_name']
priv_share_token = d['priv_share_token']
msg = _(u"%(user)s has shared a file named <a href='%(href)s'>%(file_name)s</a> to you.") % {
'user': escape(share_from),
'href': reverse('view_priv_shared_file', args=[priv_share_token]),
'file_name': escape(file_name),
}
return msg
def format_user_message_title(self):
"""
Arguments:
- `self`:
"""
try:
d = self.user_message_detail_to_dict()
except self.InvalidDetailError as e:
return _(u"Internal error")
msg_from = d.get('msg_from')
nickname = email2nickname(msg_from)
msg = _(u"You have received a <a href='%(href)s'>new message</a> from %(user)s.") % {
'user': escape(nickname),
'href': reverse('user_msg_list', args=[msg_from]),
}
return msg
def format_user_message_detail(self):
"""
Arguments:
- `self`:
"""
try:
d = self.user_message_detail_to_dict()
except self.InvalidDetailError as e:
return _(u"Internal error")
message = d.get('message')
if message is not None:
return message
else:
return None
def format_group_message_title(self):
"""
Arguments:
- `self`:
"""
try:
d = self.group_message_detail_to_dict()
except self.InvalidDetailError as e:
return _(u"Internal error")
group_id = d.get('group_id')
group = seaserv.get_group(group_id)
if group is None:
self.delete()
return None
msg_from = d.get('msg_from')
if msg_from is None:
msg = _(u"<a href='%(href)s'>%(group_name)s</a> has a new discussion.") % {
'href': reverse('group_discuss', args=[group.id]),
'group_name': group.group_name}
else:
msg = _(u"%(user)s posted a new discussion in <a href='%(href)s'>%(group_name)s</a>.") % {
'href': reverse('group_discuss', args=[group.id]),
'user': escape(email2nickname(msg_from)),
'group_name': group.group_name}
return msg
def format_group_message_detail(self):
"""
Arguments:
- `self`:
"""
try:
d = self.group_message_detail_to_dict()
except self.InvalidDetailError as e:
return _(u"Internal error")
message = d.get('message')
if message is not None:
return message
else:
return None
def format_grpmsg_reply_title(self):
"""
Arguments:
- `self`:
"""
try:
d = self.grpmsg_reply_detail_to_dict()
except self.InvalidDetailError as e:
return _(u"Internal error")
reply_from = d.get('reply_from')
if reply_from is None:
msg = _(u"One <a href='%(href)s'>group discussion</a> has a new reply.") % {
'href': reverse('msg_reply_new'),
}
else:
msg = _(u"%(user)s replied the <a href='%(href)s'>group discussion</a>.") % {
'user': escape(email2nickname(reply_from)),
'href': reverse('msg_reply_new'),
}
return msg
def format_grpmsg_reply_topic(self):
"""
Arguments:
- `self`:
"""
try:
d = self.grpmsg_reply_detail_to_dict()
except self.InvalidDetailError:
return _(u"Internal error")
grpmsg_topic = d.get('grpmsg_topic')
if grpmsg_topic is not None:
return grpmsg_topic
else:
return None
def format_grpmsg_reply_detail(self):
"""
Arguments:
- `self`:
"""
try:
d = self.grpmsg_reply_detail_to_dict()
except self.InvalidDetailError:
return _(u"Internal error")
reply_msg = d.get('reply_msg')
if reply_msg is not None:
return reply_msg
else:
return None
def format_group_join_request(self):
"""
Arguments:
- `self`:
"""
try:
d = json.loads(self.detail)
except Exception as e:
logger.error(e)
return _(u"Internal error")
username = d['username']
group_id = d['group_id']
join_request_msg = d['join_request_msg']
group = seaserv.get_group(group_id)
if group is None:
self.delete()
return None
msg = _(u"User <a href='%(user_profile)s'>%(username)s</a> has asked to join group <a href='%(href)s'>%(group_name)s</a>, verification message: %(join_request_msg)s") % {
'user_profile': reverse('user_profile', args=[username]),
'username': username,
'href': reverse('group_members', args=[group_id]),
'group_name': group.group_name,
'join_request_msg': escape(join_request_msg),
}
return msg
def format_add_user_to_group(self):
"""
Arguments:
- `self`:
"""
try:
d = json.loads(self.detail)
except Exception as e:
logger.error(e)
return _(u"Internal error")
group_staff = d['group_staff']
group_id = d['group_id']
group = seaserv.get_group(group_id)
if group is None:
self.delete()
return None
msg = _(u"User <a href='%(user_profile)s'>%(group_staff)s</a> has added you to group <a href='%(href)s'>%(group_name)s</a>") % {
'user_profile': reverse('user_profile', args=[group_staff]),
'group_staff': group_staff,
'href': reverse('view_group', args=[group_id]),
'group_name': group.group_name,
}
return msg
########## handle signals
from django.core.urlresolvers import reverse
from django.dispatch import receiver
from seahub.signals import share_file_to_user_successful, upload_file_successful
from seahub.group.models import GroupMessage, MessageReply
from seahub.group.signals import grpmsg_added, grpmsg_reply_added, \
group_join_request, add_user_to_group
from seahub.share.signals import share_repo_to_user_successful
from seahub.message.models import UserMessage
from seahub.message.signals import user_message_sent
@receiver(upload_file_successful)
def add_upload_file_msg_cb(sender, **kwargs):
"""Notify repo owner when others upload files to his/her folder from shared link.
"""
repo_id = kwargs.get('repo_id', None)
file_path = kwargs.get('file_path', None)
owner = kwargs.get('owner', None)
assert repo_id and file_path and owner is not None, 'Arguments error'
filename = os.path.basename(file_path)
folder_path = os.path.dirname(file_path)
folder_name = os.path.basename(folder_path)
detail = file_uploaded_msg_to_json(filename, repo_id, folder_path)
UserNotification.objects.add_file_uploaded_msg(owner, detail)
@receiver(upload_file_successful)
def add_upload_file_msg_cb(sender, **kwargs):
"""Notify repo owner when others upload files to his/her folder from shared link.
"""
repo_id = kwargs.get('repo_id', None)
file_path = kwargs.get('file_path', None)
owner = kwargs.get('owner', None)
assert repo_id and file_path and owner is not None, 'Arguments error'
filename = os.path.basename(file_path)
folder_path = os.path.dirname(file_path)
folder_name = os.path.basename(folder_path)
detail = file_uploaded_msg_to_json(filename, repo_id, folder_path)
UserNotification.objects.add_file_uploaded_msg(owner, detail)
@receiver(share_repo_to_user_successful)
def add_share_repo_msg_cb(sender, **kwargs):
"""Notify user when others share repos to him/her.
"""
from_user = kwargs.get('from_user', None)
to_user = kwargs.get('to_user', None)
repo = kwargs.get('repo', None)
assert from_user and to_user and repo is not None, 'Arguments error'
detail = repo_share_msg_to_json(from_user, repo.id)
UserNotification.objects.add_repo_share_msg(to_user, detail)
@receiver(share_file_to_user_successful)
def add_share_file_msg_cb(sender, **kwargs):
"""Notify user when others share files to him/her.
"""
priv_share = kwargs.get('priv_share_obj', None)
file_name = os.path.basename(priv_share.path)
assert priv_share is not None, 'Argument error'
detail = priv_file_share_msg_to_json(priv_share.from_user, file_name, priv_share.token)
UserNotification.objects.add_priv_file_share_msg(priv_share.to_user, detail)
@receiver(user_message_sent)
def add_user_message_cb(sender, **kwargs):
"""Notify user when he/she got a new mesaage.
"""
msg = kwargs.get('msg')
msg_from = msg.from_email
msg_to = msg.to_email
message = msg.message
detail = user_msg_to_json(message, msg_from)
UserNotification.objects.add_user_message(msg_to, detail=detail)
@receiver(grpmsg_added)
def grpmsg_added_cb(sender, **kwargs):
group_id = kwargs['group_id']
from_email = kwargs['from_email']
message = kwargs['message']
group_members = seaserv.get_group_members(int(group_id))
notify_members = [x.user_name for x in group_members if x.user_name != from_email]
detail = group_msg_to_json(group_id, from_email, message)
UserNotification.objects.bulk_add_group_msg_notices(notify_members, detail)
@receiver(grpmsg_reply_added)
def grpmsg_reply_added_cb(sender, **kwargs):
msg_id = kwargs['msg_id']
reply_from_email = kwargs['from_email']
reply_msg = kwargs['reply_msg']
grpmsg_topic = kwargs['grpmsg_topic']
try:
group_msg = GroupMessage.objects.get(id=msg_id)
except GroupMessage.DoesNotExist:
group_msg = None
if group_msg is None:
return
msg_replies = MessageReply.objects.filter(reply_to=group_msg)
# notify all people replied this group message
notice_users = set([ x.from_email for x in msg_replies \
if x.from_email != reply_from_email])
if group_msg.from_email != reply_from_email:
# also notify the person who posts the group message
notice_users.add(group_msg.from_email)
detail = grpmsg_reply_to_json(msg_id, reply_from_email,
grpmsg_topic, reply_msg)
for user in notice_users:
UserNotification.objects.add_group_msg_reply_notice(to_user=user,
detail=detail)
@receiver(group_join_request)
def group_join_request_cb(sender, **kwargs):
staffs = kwargs['staffs']
username = kwargs['username']
group_id = kwargs['group'].id
join_request_msg = kwargs['join_request_msg']
detail = group_join_request_to_json(username, group_id,
join_request_msg)
for staff in staffs:
UserNotification.objects.add_group_join_request_notice(to_user=staff,
detail=detail)
@receiver(add_user_to_group)
def add_user_to_group_cb(sender, **kwargs):
group_staff = kwargs['group_staff']
group_id = kwargs['group_id']
added_user = kwargs['added_user']
detail = add_user_to_group_to_json(group_staff,
group_id)
UserNotification.objects.set_add_user_to_group_notice(to_user=added_user,
detail=detail)
<file_sep>/README.markdown
[](http://travis-ci.org/haiwen/seahub)
Introduction
==========
Seahub is the web frontend for Seafile.
Preparation
==========
* Build and deploy Seafile server from source. See <https://github.com/haiwen/seafile/wiki/Build-and-deploy-seafile-server-from-source>
Getting it
==========
You can grab souce code from GitHub.
$ git clone git://github.com/haiwen/seahub.git
Install python libraries by pip:
pip install -r requirements.txt
Configuration
==========
Modify `CCNET_CONF_DIR`, `SEAFILE_CONF_DIR` and `PYTHONPATH` in `setenv.sh.template` to fit your path.
`CCNET_CONF_DIR` is the directory contains `ccnet.conf`.
`SEAFILE_CONF_DIR` is the directory contains `seafile.conf`.
Run and Verify
==========
Run as:
./run-seahub.sh.template
Then open your browser, and input `http://localhost:8000/`, there should be a Login page. You can create admin account using `seahub-admin.py` script under `tools/` directory.
Internationalization (I18n)
==========
Please refer to https://github.com/haiwen/seafile/wiki/Seahub-Translation
<file_sep>/tests/api/test_public_repo.py
import json
from constance import config
from seaserv import seafile_api, ccnet_threaded_rpc
from seahub.test_utils import BaseTestCase
class RepoPublicTest(BaseTestCase):
def setUp(self):
self.repo_id = self.create_repo(name='test-admin-repo', desc='',
username=self.admin.username,
passwd=None)
self.url = '/api2/repos/%s/public/' % self.repo_id
self.user_repo_url = '/api2/repos/%s/public/' % self.repo.id
config.ENABLE_USER_CREATE_ORG_REPO = 1
def tearDown(self):
self.remove_repo(self.repo_id)
def test_admin_can_set_pub_repo(self):
self.login_as(self.admin)
resp = self.client.post(self.url)
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['success'] is True
def test_admin_can_unset_pub_repo(self):
seafile_api.add_inner_pub_repo(self.repo_id, "r")
self.login_as(self.admin)
resp = self.client.delete(self.url)
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['success'] is True
def test_user_can_set_pub_repo(self):
self.login_as(self.user)
resp = self.client.post(self.user_repo_url)
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['success'] is True
def test_admin_can_set_pub_repo_when_setting_disalbed(self):
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is True
config.ENABLE_USER_CREATE_ORG_REPO = False
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is False
self.login_as(self.admin)
resp = self.client.post(self.url)
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['success'] is True
def test_user_can_not_set_pub_repo_when_setting_disalbed(self):
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is True
config.ENABLE_USER_CREATE_ORG_REPO = False
assert bool(config.ENABLE_USER_CREATE_ORG_REPO) is False
self.login_as(self.user)
resp = self.client.post(self.user_repo_url)
self.assertEqual(403, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['error_msg'] == 'Permission denied.'
<file_sep>/tests/api/test_obtain_auth_token.py
import json
from seahub.profile.models import Profile
from seahub.test_utils import BaseTestCase
from .urls import TOKEN_URL
class ObtainAuthTokenTest(BaseTestCase):
def setUp(self):
self.p = Profile.objects.add_or_update(self.user.username, '', '')
self.p.login_id = 'test_login_id'
self.p.save()
def test_correct_email_passwd(self):
resp = self.client.post(TOKEN_URL, {
'username': self.user.username,
'password': <PASSWORD>,
})
json_resp = json.loads(resp.content)
assert json_resp['token'] is not None
assert len(json_resp['token']) == 40
def test_correct_loginID_password(self):
resp = self.client.post(TOKEN_URL, {
'username': self.p.login_id,
'password': <PASSWORD>,
})
json_resp = json.loads(resp.content)
assert json_resp['token'] is not None
assert len(json_resp['token']) == 40
def test_invalid_password(self):
resp = self.client.post(TOKEN_URL, {
'username': self.user.username,
'password': '<PASSWORD>',
})
self.assertEqual(400, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['non_field_errors'] == ['Unable to login with provided credentials.']
def test_empty_login_id(self):
self.p.login_id = ""
self.p.save()
resp = self.client.post(TOKEN_URL, {
'username': self.p.login_id,
'password': <PASSWORD>,
})
self.assertEqual(400, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['non_field_errors'] == ['Must include "username" and "password"']
<file_sep>/seahub/share/settings.py
from django.conf import settings
ANONYMOUS_SHARE_COOKIE_TIMEOUT = getattr(settings, 'ANONYMOUS_SHARE_COOKIE_TIMEOUT', 24*60*60)
ANONYMOUS_SHARE_LINK_TIMEOUT = getattr(settings, 'ANONYMOUS_SHARE_LINK_TIMEOUT', 2)
<file_sep>/seahub/api2/throttling.py
"""
Copy from django restframework version 2.1.6, and apply patch from
https://github.com/tomchristie/django-rest-framework/commit/df957c8625c79e36c33f314c943a2c593f3a2701#diff-1
"""
from rest_framework.throttling import SimpleRateThrottle
class ScopedRateThrottle(SimpleRateThrottle):
"""
Limits the rate of API calls by different amounts for various parts of
the API. Any view that has the `throttle_scope` property set will be
throttled. The unique cache key will be generated by concatenating the
user id of the request, and the scope of the view being accessed.
"""
scope_attr = 'throttle_scope'
def __init__(self):
pass
def allow_request(self, request, view):
self.scope = getattr(view, self.scope_attr, None)
if not self.scope:
return True
self.rate = self.get_rate()
self.num_requests, self.duration = self.parse_rate(self.rate)
return super(ScopedRateThrottle, self).allow_request(request, view)
def get_cache_key(self, request, view):
"""
If `view.throttle_scope` is not set, don't apply this throttle.
Otherwise generate the unique cache key by concatenating the user id
with the '.throttle_scope` property of the view.
"""
scope = getattr(view, self.scope_attr, None)
if not scope:
# Only throttle views if `.throttle_scope` is set on the view.
return None
if request.user.is_authenticated():
ident = request.user.id
else:
ident = request.META.get('REMOTE_ADDR', None)
return self.cache_format % {
'scope': scope,
'ident': ident
}
<file_sep>/thirdpart/rest_framework/__init__.py
__version__ = '2.1.6'
VERSION = __version__ # synonym
<file_sep>/seahub/profile/templates/profile/user_profile.html
{% extends "profile/profile_base.html" %}
{% load avatar_tags i18n seahub_tags %}
{% block main_panel %}
<div id="user-profile">
{% if user %}
{% avatar user.username 290 %}
{% else %}
{% avatar "" 290 %}
{% endif %}
<p title="{{ nickname }}" class="nickname ellipsis">{{ nickname }}</p>
{% if intro %}
<p class="intro">{{ intro }}</p>
{% endif %}
{% if d_profile %}
{% if d_profile.department %}
<p title="{{ d_profile.department }}" class="info ellipsis">
<span class="icon-building fa-1x vam"></span>
<span class="info-detail vam">{{ d_profile.department }}</span>
</p>
{% endif %}
{% if d_profile.telephone %}
<p title="{{ d_profile.telephone }}" class="info ellipsis">
<span class="icon-phone fa-1x vam"></span>
<span class="info-detail vam">{{ d_profile.telephone }}</span>
</p>
{% endif %}
{% endif %}
</div>
{% endblock %}
<file_sep>/seahub/options/models.py
# -*- coding: utf-8 -*-
from django.db import models
from seahub.base.fields import LowerCaseCharField
from seahub.settings import FORCE_SERVER_CRYPTO
from seahub.utils import is_pro_version
KEY_SERVER_CRYPTO = "server_crypto"
VAL_SERVER_CRYPTO_ENABLED = "1"
VAL_SERVER_CRYPTO_DISABLED = "0"
KEY_USER_GUIDE = "user_guide"
VAL_USER_GUIDE_ON = "1"
VAL_USER_GUIDE_OFF = "0"
KEY_SUB_LIB = "sub_lib"
VAL_SUB_LIB_ENABLED = "1"
VAL_SUB_LIB_DISABLED = "0"
KEY_DEFAULT_REPO = "default_repo"
class CryptoOptionNotSetError(Exception):
pass
class UserOptionsManager(models.Manager):
def set_user_option(self, username, k, v):
"""
Arguments:
- `username`:
- `k`:
- `v`:
"""
try:
user_option = super(UserOptionsManager, self).get(email=username,
option_key=k)
user_option.option_val = v
except UserOptions.DoesNotExist:
user_option = self.model(email=username, option_key=k,
option_val=v)
user_option.save(using=self._db)
return user_option
def enable_server_crypto(self, username):
"""
Arguments:
- `username`:
"""
return self.set_user_option(username, KEY_SERVER_CRYPTO,
VAL_SERVER_CRYPTO_ENABLED)
def disable_server_crypto(self, username):
"""
Arguments:
- `username`:
"""
return self.set_user_option(username, KEY_SERVER_CRYPTO,
VAL_SERVER_CRYPTO_DISABLED)
def is_server_crypto(self, username):
"""Check whether user is set server crypto. Returns ``True`` if
server crypto is enabled, otherwise ``False``.
Raise ``CryptoOptionNotSetError`` if this option is not set.
NOTE: Always return ``True`` if ``FORCE_SERVER_CRYPTO`` is set to
``True``.
Arguments:
- `username`:
"""
if FORCE_SERVER_CRYPTO is True:
return True
try:
user_option = super(UserOptionsManager, self).get(
email=username, option_key=KEY_SERVER_CRYPTO)
return bool(int(user_option.option_val))
except UserOptions.DoesNotExist:
raise CryptoOptionNotSetError
def enable_user_guide(self, username):
"""
Arguments:
- `self`:
- `username`:
"""
return self.set_user_option(username, KEY_USER_GUIDE,
VAL_USER_GUIDE_ON)
def disable_user_guide(self, username):
"""
Arguments:
- `self`:
- `username`:
"""
return self.set_user_option(username, KEY_USER_GUIDE,
VAL_USER_GUIDE_OFF)
def is_user_guide_enabled(self, username):
"""Return ``True`` if user need guide, otherwise ``False``.
Arguments:
- `self`:
- `username`:
"""
rst = super(UserOptionsManager, self).filter(
email=username, option_key=KEY_USER_GUIDE)
rst_len = len(rst)
if rst_len <= 0:
# Assume ``user_guide`` is enabled if this optoin is not set.
return True
elif rst_len == 1:
return bool(int(rst[0].option_val))
else:
for i in range(rst_len - 1):
rst[i].delete()
return bool(int(rst[rst_len - 1].option_val))
def enable_sub_lib(self, username):
"""
Arguments:
- `self`:
- `username`:
"""
return self.set_user_option(username, KEY_SUB_LIB,
VAL_SUB_LIB_ENABLED)
def disable_sub_lib(self, username):
"""
Arguments:
- `self`:
- `username`:
"""
return self.set_user_option(username, KEY_SUB_LIB,
VAL_SUB_LIB_DISABLED)
def is_sub_lib_enabled(self, username):
"""Return ``True`` if is not pro version AND sub lib enabled, otherwise ``False``.
Arguments:
- `self`:
- `username`:
"""
if is_pro_version():
return False
try:
user_option = super(UserOptionsManager, self).get(
email=username, option_key=KEY_SUB_LIB)
return bool(int(user_option.option_val))
except UserOptions.DoesNotExist:
return False
def set_default_repo(self, username, repo_id):
"""Set a user's default library.
Arguments:
- `self`:
- `username`:
- `repo_id`:
"""
return self.set_user_option(username, KEY_DEFAULT_REPO, repo_id)
def get_default_repo(self, username):
"""Get a user's default library.
Returns repo_id if default library is found, otherwise ``None``.
Arguments:
- `self`:
- `username`:
"""
try:
user_option = super(UserOptionsManager, self).get(
email=username, option_key=KEY_DEFAULT_REPO)
return user_option.option_val
except UserOptions.DoesNotExist:
return None
class UserOptions(models.Model):
email = LowerCaseCharField(max_length=255, db_index=True)
option_key = models.CharField(max_length=50)
option_val = models.CharField(max_length=50)
objects = UserOptionsManager()
<file_sep>/seahub/views/file.py
# -*- coding: utf-8 -*-
"""
File related views, including view_file, view_history_file, view_trash_file,
view_snapshot_file, view_shared_file, file_edit, etc.
"""
import os
import hashlib
import json
import stat
import urllib2
import chardet
import logging
import posixpath
import re
import mimetypes
import urlparse
import datetime
from django.core import signing
from django.core.cache import cache
from django.contrib.sites.models import RequestSite
from django.contrib import messages
from django.contrib.auth.hashers import check_password
from django.core.urlresolvers import reverse
from django.db.models import F
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseBadRequest, HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.http import urlquote
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST
from django.template.defaultfilters import filesizeformat
from django.views.decorators.csrf import csrf_exempt
from seaserv import seafile_api
from seaserv import get_repo, send_message, \
get_commits, check_permission, get_shared_groups_by_repo,\
is_group_user, get_file_id_by_path, get_commit, get_file_size, \
get_org_groups_by_repo, seafserv_rpc, seafserv_threaded_rpc
from pysearpc import SearpcError
from seahub.avatar.templatetags.avatar_tags import avatar
from seahub.avatar.templatetags.group_avatar_tags import grp_avatar
from seahub.auth.decorators import login_required
from seahub.base.decorators import repo_passwd_set_required
from seahub.contacts.models import Contact
from seahub.share.models import FileShare, PrivateFileDirShare, \
check_share_link_common
from seahub.wiki.utils import get_wiki_dirent
from seahub.wiki.models import WikiDoesNotExist, WikiPageMissing
from seahub.utils import show_delete_days, render_error, is_org_context, \
get_file_type_and_ext, gen_file_get_url, gen_file_share_link, \
render_permission_error, is_pro_version, \
is_textual_file, mkstemp, EMPTY_SHA1, HtmlDiff, \
check_filename_with_rename, gen_inner_file_get_url, normalize_file_path, \
user_traffic_over_limit, do_md5, get_file_audit_events_by_path, \
generate_file_audit_event_type, FILE_AUDIT_ENABLED
from seahub.utils.ip import get_remote_ip
from seahub.utils.timeutils import utc_to_local
from seahub.utils.file_types import (IMAGE, PDF, DOCUMENT, SPREADSHEET, AUDIO,
MARKDOWN, TEXT, OPENDOCUMENT, VIDEO)
from seahub.utils.star import is_file_starred
from seahub.utils import HAS_OFFICE_CONVERTER, FILEEXT_TYPE_MAP
from seahub.utils.http import json_response, int_param, BadRequestException, RequestForbbiddenException
from seahub.views import check_folder_permission, check_file_lock
if HAS_OFFICE_CONVERTER:
from seahub.utils import (
query_office_convert_status, add_office_convert_task, office_convert_cluster_token,
prepare_converted_html, OFFICE_PREVIEW_MAX_SIZE, get_office_converted_page
)
import seahub.settings as settings
from seahub.settings import FILE_ENCODING_LIST, FILE_PREVIEW_MAX_SIZE, \
FILE_ENCODING_TRY_LIST, USE_PDFJS, MEDIA_URL, SITE_ROOT
try:
from seahub.settings import ENABLE_OFFICE_WEB_APP
except ImportError:
ENABLE_OFFICE_WEB_APP = False
try:
from seahub.settings import OFFICE_WEB_APP_FILE_EXTENSION
except ImportError:
OFFICE_WEB_APP_FILE_EXTENSION = ()
from seahub.views import is_registered_user, check_repo_access_permission, \
get_unencry_rw_repos_by_user, get_file_access_permission
# Get an instance of a logger
logger = logging.getLogger(__name__)
def gen_path_link(path, repo_name):
"""
Generate navigate paths and links in repo page.
"""
if path and path[-1] != '/':
path += '/'
paths = []
links = []
if path and path != '/':
paths = path[1:-1].split('/')
i = 1
for name in paths:
link = '/' + '/'.join(paths[:i])
i = i + 1
links.append(link)
if repo_name:
paths.insert(0, repo_name)
links.insert(0, '/')
zipped = zip(paths, links)
return zipped
def get_file_content(file_type, raw_path, file_enc):
"""Get textual file content, including txt/markdown/seaf.
"""
return repo_file_get(raw_path, file_enc) if is_textual_file(
file_type=file_type) else ('', '', '')
def repo_file_get(raw_path, file_enc):
"""
Get file content and encoding.
"""
err = ''
file_content = ''
encoding = None
if file_enc != 'auto':
encoding = file_enc
try:
file_response = urllib2.urlopen(raw_path)
content = file_response.read()
except urllib2.HTTPError, e:
logger.error(e)
err = _(u'HTTPError: failed to open file online')
return err, '', None
except urllib2.URLError as e:
logger.error(e)
err = _(u'URLError: failed to open file online')
return err, '', None
else:
if encoding:
try:
u_content = content.decode(encoding)
except UnicodeDecodeError:
err = _(u'The encoding you chose is not proper.')
return err, '', encoding
else:
for enc in FILE_ENCODING_TRY_LIST:
try:
u_content = content.decode(enc)
encoding = enc
break
except UnicodeDecodeError:
if enc != FILE_ENCODING_TRY_LIST[-1]:
continue
else:
encoding = chardet.detect(content)['encoding']
if encoding:
try:
u_content = content.decode(encoding)
except UnicodeDecodeError:
err = _(u'Unknown file encoding')
return err, '', ''
else:
err = _(u'Unknown file encoding')
return err, '', ''
file_content = u_content
return err, file_content, encoding
def get_file_view_path_and_perm(request, repo_id, obj_id, path, use_onetime=True):
""" Get path and the permission to view file.
Returns:
outer fileserver file url, inner fileserver file url, permission
"""
username = request.user.username
filename = os.path.basename(path)
# user_perm = get_file_access_permission(repo_id, path, username) or \
# get_repo_access_permission(repo_id, username)
user_perm = check_repo_access_permission(repo_id, request.user)
if user_perm is None:
return ('', '', user_perm)
else:
# Get a token to visit file
token = seafile_api.get_fileserver_access_token(repo_id, obj_id, 'view',
username, use_onetime=use_onetime)
outer_url = gen_file_get_url(token, filename)
inner_url = gen_inner_file_get_url(token, filename)
return (outer_url, inner_url, user_perm)
def handle_textual_file(request, filetype, raw_path, ret_dict):
# encoding option a user chose
file_enc = request.GET.get('file_enc', 'auto')
if not file_enc in FILE_ENCODING_LIST:
file_enc = 'auto'
err, file_content, encoding = get_file_content(filetype,
raw_path, file_enc)
file_encoding_list = FILE_ENCODING_LIST
if encoding and encoding not in FILE_ENCODING_LIST:
file_encoding_list.append(encoding)
# populate return value dict
ret_dict['err'] = err
ret_dict['file_content'] = file_content
ret_dict['encoding'] = encoding
ret_dict['file_enc'] = file_enc
ret_dict['file_encoding_list'] = file_encoding_list
def handle_document(raw_path, obj_id, fileext, ret_dict):
if HAS_OFFICE_CONVERTER:
err = prepare_converted_html(raw_path, obj_id, fileext, ret_dict)
# populate return value dict
ret_dict['err'] = err
else:
ret_dict['filetype'] = 'Unknown'
def handle_spreadsheet(raw_path, obj_id, fileext, ret_dict):
handle_document(raw_path, obj_id, fileext, ret_dict)
def handle_pdf(raw_path, obj_id, fileext, ret_dict):
if USE_PDFJS:
# use pdfjs to preview PDF
pass
elif HAS_OFFICE_CONVERTER:
# use pdf2htmlEX to prefiew PDF
err = prepare_converted_html(raw_path, obj_id, fileext, ret_dict)
# populate return value dict
ret_dict['err'] = err
else:
# can't preview PDF
ret_dict['filetype'] = 'Unknown'
def convert_md_link(file_content, repo_id, username):
def repl(matchobj):
if matchobj.group(2): # return origin string in backquotes
return matchobj.group(2)
link_alias = link_name = matchobj.group(1).strip()
if len(link_name.split('|')) > 1:
link_alias = link_name.split('|')[0]
link_name = link_name.split('|')[1]
filetype, fileext = get_file_type_and_ext(link_name)
if fileext == '':
# convert link_name that extension is missing to a markdown page
try:
dirent = get_wiki_dirent(repo_id, link_name)
path = "/" + dirent.obj_name
href = reverse('view_lib_file', args=[repo_id, urlquote(path)])
a_tag = '''<a href="%s">%s</a>'''
return a_tag % (href, link_alias)
except (WikiDoesNotExist, WikiPageMissing):
a_tag = '''<p class="wiki-page-missing">%s</p>'''
return a_tag % (link_alias)
elif filetype == IMAGE:
# load image to current page
path = "/" + link_name
filename = os.path.basename(path)
obj_id = get_file_id_by_path(repo_id, path)
if not obj_id:
return '''<p class="wiki-page-missing">%s</p>''' % link_name
token = seafile_api.get_fileserver_access_token(repo_id, obj_id,
'view', username)
return '<img class="wiki-image" src="%s" alt="%s" />' % (gen_file_get_url(token, filename), filename)
else:
from seahub.base.templatetags.seahub_tags import file_icon_filter
# convert other types of filelinks to clickable links
path = "/" + link_name
icon = file_icon_filter(link_name)
s = reverse('view_lib_file', args=[repo_id, urlquote(path)])
a_tag = '''<img src="%simg/file/%s" alt="%s" class="vam" /> <a href="%s" target="_blank" class="vam">%s</a>'''
return a_tag % (MEDIA_URL, icon, icon, s, link_name)
return re.sub(r'\[\[(.+?)\]\]|(`.+?`)', repl, file_content)
def file_size_exceeds_preview_limit(file_size, file_type):
"""Check whether file size exceeds the preview limit base on different
type of file.
"""
if file_type in (DOCUMENT, PDF) and HAS_OFFICE_CONVERTER:
if file_size > OFFICE_PREVIEW_MAX_SIZE:
err = _(u'File size surpasses %s, can not be opened online.') % \
filesizeformat(OFFICE_PREVIEW_MAX_SIZE)
return True, err
else:
return False, ''
else:
if file_size > FILE_PREVIEW_MAX_SIZE:
err = _(u'File size surpasses %s, can not be opened online.') % \
filesizeformat(FILE_PREVIEW_MAX_SIZE)
return True, err
else:
return False, ''
def can_preview_file(file_name, file_size, repo=None):
"""Check whether a file can be viewed online.
Returns (True, None) if file can be viewed online, otherwise
(False, erro_msg).
"""
file_type, file_ext = get_file_type_and_ext(file_name)
if repo and repo.encrypted and (file_type in (DOCUMENT, SPREADSHEET,
OPENDOCUMENT, PDF)):
return (False, _(u'The library is encrypted, can not open file online.'))
if file_ext in FILEEXT_TYPE_MAP: # check file extension
exceeds_limit, err_msg = file_size_exceeds_preview_limit(file_size,
file_type)
if exceeds_limit:
return (False, err_msg)
else:
return (True, None)
else:
# TODO: may need a better way instead of return string, and compare
# that string in templates
return (False, "invalid extension")
def send_file_access_msg_when_preview(request, repo, path, access_from):
""" send file access msg when user preview file from web
"""
filename = os.path.basename(path)
filetype, fileext = get_file_type_and_ext(filename)
if filetype in (TEXT, IMAGE, MARKDOWN, VIDEO, AUDIO):
send_file_access_msg(request, repo, path, access_from)
if filetype in (DOCUMENT, SPREADSHEET, OPENDOCUMENT, PDF) and \
HAS_OFFICE_CONVERTER:
send_file_access_msg(request, repo, path, access_from)
if filetype == PDF and USE_PDFJS:
send_file_access_msg(request, repo, path, access_from)
@login_required
@repo_passwd_set_required
def view_repo_file(request, repo_id):
"""
Old 'file view' that put path in parameter
"""
path = request.GET.get('p', '/').rstrip('/')
return _file_view(request, repo_id, path)
@login_required
@repo_passwd_set_required
def view_lib_file(request, repo_id, path):
"""
New 'file view' that not put path in parameter
"""
return _file_view(request, repo_id, path)
def _file_view(request, repo_id, path):
"""
Steps to view file:
1. Get repo id and file path.
2. Check user's permission.
3. Check whether this file can be viewed online.
4.1 Get file content if file is text file.
4.2 Prepare flash if file is document.
4.3 Prepare or use pdfjs if file is pdf.
4.4 Other file return it's raw path.
"""
username = request.user.username
# check arguments
repo = get_repo(repo_id)
if not repo:
raise Http404
obj_id = get_file_id_by_path(repo_id, path)
if not obj_id:
return render_error(request, _(u'File does not exist'))
# construct some varibles
u_filename = os.path.basename(path)
current_commit = get_commits(repo_id, 0, 1)[0]
# get file type and extension
filetype, fileext = get_file_type_and_ext(u_filename)
# Check whether user has permission to view file and get file raw path,
# render error page if permission deny.
file_perm = seafile_api.check_permission_by_path(repo_id, path, username)
if not file_perm:
return render_permission_error(request, _(u'Unable to view file'))
# Pass permission check, start download or render file.
if request.GET.get('dl', '0') == '1':
token = seafile_api.get_fileserver_access_token(repo_id, obj_id,
'download', username,
use_onetime=True)
dl_url = gen_file_get_url(token, u_filename)
# send stats message
send_file_access_msg(request, repo, path, 'web')
return HttpResponseRedirect(dl_url)
if request.GET.get('raw', '0') == '1':
token = seafile_api.get_fileserver_access_token(repo_id, obj_id,
'view', username,
use_onetime=True)
raw_url = gen_file_get_url(token, u_filename)
# send stats message
send_file_access_msg(request, repo, path, 'web')
return HttpResponseRedirect(raw_url)
# Get file view raw path, ``user_perm`` is not used anymore.
if filetype == VIDEO or filetype == AUDIO:
raw_path, inner_path, user_perm = get_file_view_path_and_perm(
request, repo_id, obj_id, path, use_onetime=False)
else:
raw_path, inner_path, user_perm = get_file_view_path_and_perm(
request, repo_id, obj_id, path)
# check if use wopi host page according to filetype
if not repo.encrypted and ENABLE_OFFICE_WEB_APP and \
fileext in OFFICE_WEB_APP_FILE_EXTENSION:
try:
from seahub_extra.wopi.utils import get_wopi_dict
except ImportError:
wopi_dict = None
else:
wopi_dict = get_wopi_dict(username, repo_id, path)
if wopi_dict:
send_file_access_msg(request, repo, path, 'web')
return render_to_response('view_wopi_file.html', wopi_dict,
context_instance=RequestContext(request))
# check if the user is the owner or not, for 'private share'
if is_org_context(request):
repo_owner = seafile_api.get_org_repo_owner(repo.id)
is_repo_owner = True if repo_owner == username else False
else:
is_repo_owner = seafile_api.is_repo_owner(username, repo.id)
img_prev = None
img_next = None
ret_dict = {'err': '', 'file_content': '', 'encoding': '', 'file_enc': '',
'file_encoding_list': [], 'filetype': filetype}
fsize = get_file_size(repo.store_id, repo.version, obj_id)
can_preview, err_msg = can_preview_file(u_filename, fsize, repo)
if can_preview:
send_file_access_msg_when_preview(request, repo, path, 'web')
"""Choose different approach when dealing with different type of file."""
if is_textual_file(file_type=filetype):
handle_textual_file(request, filetype, inner_path, ret_dict)
if filetype == MARKDOWN:
c = ret_dict['file_content']
ret_dict['file_content'] = convert_md_link(c, repo_id, username)
elif filetype == DOCUMENT:
handle_document(inner_path, obj_id, fileext, ret_dict)
elif filetype == SPREADSHEET:
handle_spreadsheet(inner_path, obj_id, fileext, ret_dict)
elif filetype == OPENDOCUMENT:
if fsize == 0:
ret_dict['err'] = _(u'Invalid file format.')
elif filetype == PDF:
handle_pdf(inner_path, obj_id, fileext, ret_dict)
elif filetype == IMAGE:
parent_dir = os.path.dirname(path)
dirs = seafile_api.list_dir_by_commit_and_path(current_commit.repo_id,
current_commit.id, parent_dir)
if not dirs:
raise Http404
img_list = []
for dirent in dirs:
if not stat.S_ISDIR(dirent.props.mode):
fltype, flext = get_file_type_and_ext(dirent.obj_name)
if fltype == 'Image':
img_list.append(dirent.obj_name)
if len(img_list) > 1:
img_list.sort(lambda x, y : cmp(x.lower(), y.lower()))
cur_img_index = img_list.index(u_filename)
if cur_img_index != 0:
img_prev = posixpath.join(parent_dir, img_list[cur_img_index - 1])
if cur_img_index != len(img_list) - 1:
img_next = posixpath.join(parent_dir, img_list[cur_img_index + 1])
template = 'view_file_%s.html' % ret_dict['filetype'].lower()
else:
ret_dict['err'] = err_msg
template = 'view_file_base.html'
# generate file path navigator
zipped = gen_path_link(path, repo.name)
# file shared link
l = FileShare.objects.filter(repo_id=repo_id).filter(
username=username).filter(path=path)
fileshare = l[0] if len(l) > 0 else None
http_or_https = request.is_secure() and 'https' or 'http'
domain = RequestSite(request).domain
if fileshare:
file_shared_link = gen_file_share_link(fileshare.token)
else:
file_shared_link = ''
for g in request.user.joined_groups:
g.avatar = grp_avatar(g.id, 20)
file_path_hash = hashlib.md5(urllib2.quote(path.encode('utf-8'))).hexdigest()[:12]
# fetch file contributors and latest contributor
try:
# get real path for sub repo
real_path = repo.origin_path + path if repo.origin_path else path
dirent = seafile_api.get_dirent_by_path(repo.store_id, real_path)
if dirent:
latest_contributor, last_modified = dirent.modifier, dirent.mtime
else:
latest_contributor, last_modified = None, 0
except SearpcError as e:
logger.error(e)
latest_contributor, last_modified = None, 0
# check whether file is starred
is_starred = False
org_id = -1
if request.user.org:
org_id = request.user.org.org_id
is_starred = is_file_starred(username, repo.id, path.encode('utf-8'), org_id)
is_locked, locked_by_me = check_file_lock(repo_id, path, username)
can_edit_file = True
if file_perm == 'r':
can_edit_file = False
elif is_locked and not locked_by_me:
can_edit_file = False
if is_pro_version() and file_perm == 'rw':
can_lock_unlock_file = True
else:
can_lock_unlock_file = False
return render_to_response(template, {
'repo': repo,
'is_repo_owner': is_repo_owner,
'obj_id': obj_id,
'filename': u_filename,
'path': path,
'zipped': zipped,
'current_commit': current_commit,
'fileext': fileext,
'raw_path': raw_path,
'fileshare': fileshare,
'protocol': http_or_https,
'domain': domain,
'file_shared_link': file_shared_link,
'err': ret_dict['err'],
'file_content': ret_dict['file_content'],
'file_enc': ret_dict['file_enc'],
'encoding': ret_dict['encoding'],
'file_encoding_list': ret_dict['file_encoding_list'],
'filetype': ret_dict['filetype'],
'use_pdfjs': USE_PDFJS,
'latest_contributor': latest_contributor,
'last_modified': last_modified,
'last_commit_id': repo.head_cmmt_id,
'is_starred': is_starred,
'user_perm': user_perm,
'file_perm': file_perm,
'file_locked': is_locked,
'is_pro': is_pro_version(),
'locked_by_me': locked_by_me,
'can_edit_file': can_edit_file,
'can_lock_unlock_file': can_lock_unlock_file,
'img_prev': img_prev,
'img_next': img_next,
'highlight_keyword': settings.HIGHLIGHT_KEYWORD,
}, context_instance=RequestContext(request))
def view_history_file_common(request, repo_id, ret_dict):
# check arguments
repo = get_repo(repo_id)
if not repo:
raise Http404
path = request.GET.get('p', '/')
commit_id = request.GET.get('commit_id', '')
if not commit_id:
raise Http404
obj_id = request.GET.get('obj_id', '')
if not obj_id:
raise Http404
# construct some varibles
u_filename = os.path.basename(path)
current_commit = get_commit(repo.id, repo.version, commit_id)
if not current_commit:
raise Http404
# get file type and extension
filetype, fileext = get_file_type_and_ext(u_filename)
# Check whether user has permission to view file and get file raw path,
# render error page if permission deny.
if filetype == VIDEO or filetype == AUDIO:
raw_path, inner_path, user_perm = get_file_view_path_and_perm(
request, repo_id, obj_id, path, use_onetime=False)
else:
raw_path, inner_path, user_perm = get_file_view_path_and_perm(
request, repo_id, obj_id, path)
request.user_perm = user_perm
if user_perm:
# Check if can preview file
fsize = get_file_size(repo.store_id, repo.version, obj_id)
can_preview, err_msg = can_preview_file(u_filename, fsize, repo)
if can_preview:
send_file_access_msg_when_preview(request, repo, path, 'web')
"""Choose different approach when dealing with different type of file."""
if is_textual_file(file_type=filetype):
handle_textual_file(request, filetype, inner_path, ret_dict)
elif filetype == DOCUMENT:
handle_document(inner_path, obj_id, fileext, ret_dict)
elif filetype == SPREADSHEET:
handle_spreadsheet(inner_path, obj_id, fileext, ret_dict)
elif filetype == OPENDOCUMENT:
if fsize == 0:
ret_dict['err'] = _(u'Invalid file format.')
elif filetype == PDF:
handle_pdf(inner_path, obj_id, fileext, ret_dict)
else:
pass
else:
ret_dict['err'] = err_msg
# populate return value dict
ret_dict['repo'] = repo
ret_dict['obj_id'] = obj_id
ret_dict['file_name'] = u_filename
ret_dict['path'] = path
ret_dict['current_commit'] = current_commit
ret_dict['fileext'] = fileext
ret_dict['raw_path'] = raw_path
if not ret_dict.has_key('filetype'):
ret_dict['filetype'] = filetype
ret_dict['use_pdfjs'] = USE_PDFJS
@repo_passwd_set_required
def view_history_file(request, repo_id):
ret_dict = {}
view_history_file_common(request, repo_id, ret_dict)
if not request.user_perm:
return render_permission_error(request, _(u'Unable to view file'))
# generate file path navigator
path = ret_dict['path']
repo = ret_dict['repo']
ret_dict['zipped'] = gen_path_link(path, repo.name)
return render_to_response('view_history_file.html', ret_dict,
context_instance=RequestContext(request))
@repo_passwd_set_required
def view_trash_file(request, repo_id):
ret_dict = {}
view_history_file_common(request, repo_id, ret_dict)
if not request.user_perm:
return render_permission_error(request, _(u'Unable to view file'))
basedir = request.GET.get('base', '')
if not basedir:
raise Http404
if basedir != '/':
tmp_path = posixpath.join(basedir.rstrip('/'), ret_dict['path'].lstrip('/'))
ret_dict['path'] = tmp_path
return render_to_response('view_trash_file.html', ret_dict,
context_instance=RequestContext(request), )
@repo_passwd_set_required
def view_snapshot_file(request, repo_id):
ret_dict = {}
view_history_file_common(request, repo_id, ret_dict)
if not request.user_perm:
return render_permission_error(request, _(u'Unable to view file'))
# generate file path navigator
path = ret_dict['path']
repo = ret_dict['repo']
ret_dict['zipped'] = gen_path_link(path, repo.name)
return render_to_response('view_snapshot_file.html', ret_dict,
context_instance=RequestContext(request), )
def _download_file_from_share_link(request, fileshare):
"""Download shared file or private shared file.
`path` need to be provided by frontend, if missing, use `fileshare.path`
"""
next = request.META.get('HTTP_REFERER', settings.SITE_ROOT)
username = request.user.username
if isinstance(fileshare, PrivateFileDirShare):
fileshare.username = fileshare.from_user
shared_by = fileshare.username
repo = get_repo(fileshare.repo_id)
if not repo:
raise Http404
# Construct real file path if download file in shared dir, otherwise, just
# use path in DB.
if isinstance(fileshare, FileShare) and fileshare.is_dir_share_link():
req_path = request.GET.get('p', '')
if not req_path:
messages.error(request, _(u'Unable to download file, invalid file path'))
return HttpResponseRedirect(next)
real_path = posixpath.join(fileshare.path, req_path.lstrip('/'))
else:
real_path = fileshare.path
filename = os.path.basename(real_path)
obj_id = seafile_api.get_file_id_by_path(repo.id, real_path)
if not obj_id:
messages.error(request, _(u'Unable to download file, wrong file path'))
return HttpResponseRedirect(next)
# check whether owner's traffic over the limit
if user_traffic_over_limit(fileshare.username):
messages.error(request, _(u'Unable to download file, share link traffic is used up.'))
return HttpResponseRedirect(next)
send_file_access_msg(request, repo, real_path, 'share-link')
try:
file_size = seafile_api.get_file_size(repo.store_id, repo.version,
obj_id)
send_message('seahub.stats', 'file-download\t%s\t%s\t%s\t%s' %
(repo.id, shared_by, obj_id, file_size))
except Exception as e:
logger.error('Error when sending file-download message: %s' % str(e))
dl_token = seafile_api.get_fileserver_access_token(repo.id, obj_id,
'download', username,
use_onetime=False)
return HttpResponseRedirect(gen_file_get_url(dl_token, filename))
def view_shared_file(request, token):
"""
View file via shared link.
Download share file if `dl` in request param.
View raw share file if `raw` in request param.
"""
assert token is not None # Checked by URLconf
fileshare = FileShare.objects.get_valid_file_link_by_token(token)
if fileshare is None:
raise Http404
password_check_passed, err_msg = check_share_link_common(request, fileshare)
if not password_check_passed:
d = {'token': token, 'view_name': 'view_shared_file', 'err_msg': err_msg}
return render_to_response('share_access_validation.html', d,
context_instance=RequestContext(request))
shared_by = fileshare.username
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
if not repo:
raise Http404
path = fileshare.path.rstrip('/') # Normalize file path
obj_id = seafile_api.get_file_id_by_path(repo_id, path)
if not obj_id:
return render_error(request, _(u'File does not exist'))
filename = os.path.basename(path)
filetype, fileext = get_file_type_and_ext(filename)
# Increase file shared link view_cnt, this operation should be atomic
fileshare.view_cnt = F('view_cnt') + 1
fileshare.save()
# send statistic messages
file_size = seafile_api.get_file_size(repo.store_id, repo.version, obj_id)
if request.GET.get('dl', '') == '1':
# download shared file
return _download_file_from_share_link(request, fileshare)
access_token = seafile_api.get_fileserver_access_token(repo.id, obj_id,
'view', '',
use_onetime=False)
raw_path = gen_file_get_url(access_token, filename)
if request.GET.get('raw', '') == '1':
# view raw shared file, directly show/download file depends on
# browsers
return HttpResponseRedirect(raw_path)
# get file content
ret_dict = {'err': '', 'file_content': '', 'encoding': '', 'file_enc': '',
'file_encoding_list': [], 'filetype': filetype}
fsize = get_file_size(repo.store_id, repo.version, obj_id)
can_preview, err_msg = can_preview_file(filename, fsize, repo)
if can_preview:
send_file_access_msg_when_preview(request, repo, path, 'share-link')
"""Choose different approach when dealing with different type of file."""
inner_path = gen_inner_file_get_url(access_token, filename)
if is_textual_file(file_type=filetype):
handle_textual_file(request, filetype, inner_path, ret_dict)
elif filetype == DOCUMENT:
handle_document(inner_path, obj_id, fileext, ret_dict)
elif filetype == SPREADSHEET:
handle_spreadsheet(inner_path, obj_id, fileext, ret_dict)
elif filetype == OPENDOCUMENT:
if file_size == 0:
ret_dict['err'] = _(u'Invalid file format.')
elif filetype == PDF:
handle_pdf(inner_path, obj_id, fileext, ret_dict)
else:
ret_dict['err'] = err_msg
accessible_repos = get_unencry_rw_repos_by_user(request)
save_to_link = reverse('save_shared_link') + '?t=' + token
traffic_over_limit = user_traffic_over_limit(shared_by)
return render_to_response('shared_file_view.html', {
'repo': repo,
'obj_id': obj_id,
'path': path,
'file_name': filename,
'file_size': file_size,
'shared_token': token,
'access_token': access_token,
'fileext': fileext,
'raw_path': raw_path,
'shared_by': shared_by,
'err': ret_dict['err'],
'file_content': ret_dict['file_content'],
'encoding': ret_dict['encoding'],
'file_encoding_list': ret_dict['file_encoding_list'],
'filetype': ret_dict['filetype'],
'use_pdfjs': USE_PDFJS,
'accessible_repos': accessible_repos,
'save_to_link': save_to_link,
'traffic_over_limit': traffic_over_limit,
}, context_instance=RequestContext(request))
def view_raw_shared_file(request, token, obj_id, file_name):
"""Returns raw content of a shared file.
Arguments:
- `request`:
- `token`:
- `obj_id`:
- `file_name`:
"""
fileshare = FileShare.objects.get_valid_file_link_by_token(token)
if fileshare is None:
raise Http404
password_check_passed, err_msg = check_share_link_common(request, fileshare)
if not password_check_passed:
d = {'token': token, 'err_msg': err_msg}
if fileshare.is_file_share_link():
d['view_name'] = 'view_shared_file'
else:
d['view_name'] = 'view_shared_dir'
return render_to_response('share_access_validation.html', d,
context_instance=RequestContext(request))
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
if not repo:
raise Http404
# Normalize file path based on file or dir share link
req_path = request.GET.get('p', '').rstrip('/')
if req_path:
file_path = posixpath.join(fileshare.path, req_path.lstrip('/'))
else:
if fileshare.is_file_share_link():
file_path = fileshare.path.rstrip('/')
else:
file_path = fileshare.path.rstrip('/') + '/' + file_name
real_obj_id = seafile_api.get_file_id_by_path(repo_id, file_path)
if not real_obj_id:
raise Http404
if real_obj_id != obj_id: # perm check
raise Http404
filename = os.path.basename(file_path)
username = request.user.username
token = seafile_api.get_fileserver_access_token(repo_id, real_obj_id, 'view',
username, use_onetime=False)
outer_url = gen_file_get_url(token, filename)
return HttpResponseRedirect(outer_url)
def view_file_via_shared_dir(request, token):
assert token is not None # Checked by URLconf
fileshare = FileShare.objects.get_valid_file_link_by_token(token)
if fileshare is None:
raise Http404
req_path = request.GET.get('p', '').rstrip('/')
if not req_path:
return HttpResponseRedirect(reverse('view_shared_dir', args=[token]))
password_check_passed, err_msg = check_share_link_common(request, fileshare)
if not password_check_passed:
d = {'token': token,
'view_name': 'view_file_via_shared_dir',
'path': req_path,
'err_msg': err_msg,
}
return render_to_response('share_access_validation.html', d,
context_instance=RequestContext(request))
if request.GET.get('dl', '') == '1':
# download shared file
return _download_file_from_share_link(request, fileshare)
shared_by = fileshare.username
repo_id = fileshare.repo_id
repo = get_repo(repo_id)
if not repo:
raise Http404
# Get file path from frontend, and construct request file path
# with fileshare.path to real path, used to fetch file content by RPC.
real_path = posixpath.join(fileshare.path, req_path.lstrip('/'))
# generate dir navigator
if fileshare.path == '/':
zipped = gen_path_link(req_path, repo.name)
else:
zipped = gen_path_link(req_path, os.path.basename(fileshare.path[:-1]))
obj_id = seafile_api.get_file_id_by_path(repo_id, real_path)
if not obj_id:
return render_error(request, _(u'File does not exist'))
file_size = seafile_api.get_file_size(repo.store_id, repo.version, obj_id)
filename = os.path.basename(req_path)
filetype, fileext = get_file_type_and_ext(filename)
access_token = seafile_api.get_fileserver_access_token(repo.id, obj_id,
'view', '', use_onetime=False)
raw_path = gen_file_get_url(access_token, filename)
inner_path = gen_inner_file_get_url(access_token, filename)
img_prev = None
img_next = None
# get file content
ret_dict = {'err': '', 'file_content': '', 'encoding': '', 'file_enc': '',
'file_encoding_list': [], 'filetype': filetype}
fsize = get_file_size(repo.store_id, repo.version, obj_id)
can_preview, err_msg = can_preview_file(filename, fsize, repo)
if can_preview:
send_file_access_msg_when_preview(request, repo, real_path, 'share-link')
"""Choose different approach when dealing with different type of file."""
if is_textual_file(file_type=filetype):
handle_textual_file(request, filetype, inner_path, ret_dict)
elif filetype == DOCUMENT:
handle_document(inner_path, obj_id, fileext, ret_dict)
elif filetype == SPREADSHEET:
handle_spreadsheet(inner_path, obj_id, fileext, ret_dict)
elif filetype == PDF:
handle_pdf(inner_path, obj_id, fileext, ret_dict)
elif filetype == IMAGE:
current_commit = get_commits(repo_id, 0, 1)[0]
real_parent_dir = os.path.dirname(real_path)
parent_dir = os.path.dirname(req_path)
dirs = seafile_api.list_dir_by_commit_and_path(current_commit.repo_id,
current_commit.id, real_parent_dir)
if not dirs:
raise Http404
img_list = []
for dirent in dirs:
if not stat.S_ISDIR(dirent.props.mode):
fltype, flext = get_file_type_and_ext(dirent.obj_name)
if fltype == 'Image':
img_list.append(dirent.obj_name)
if len(img_list) > 1:
img_list.sort(lambda x, y : cmp(x.lower(), y.lower()))
cur_img_index = img_list.index(filename)
if cur_img_index != 0:
img_prev = posixpath.join(parent_dir, img_list[cur_img_index - 1])
if cur_img_index != len(img_list) - 1:
img_next = posixpath.join(parent_dir, img_list[cur_img_index + 1])
else:
ret_dict['err'] = err_msg
traffic_over_limit = user_traffic_over_limit(shared_by)
return render_to_response('shared_file_view.html', {
'repo': repo,
'obj_id': obj_id,
'from_shared_dir': True,
'path': req_path,
'file_name': filename,
'file_size': file_size,
'shared_token': token,
'access_token': access_token,
'fileext': fileext,
'raw_path': raw_path,
'shared_by': shared_by,
'token': token,
'err': ret_dict['err'],
'file_content': ret_dict['file_content'],
'encoding': ret_dict['encoding'],
'file_encoding_list':ret_dict['file_encoding_list'],
'filetype': ret_dict['filetype'],
'use_pdfjs':USE_PDFJS,
'zipped': zipped,
'img_prev': img_prev,
'img_next': img_next,
'traffic_over_limit': traffic_over_limit,
}, context_instance=RequestContext(request))
def file_edit_submit(request, repo_id):
content_type = 'application/json; charset=utf-8'
def error_json(error_msg=_(u'Internal Error'), op=None):
return HttpResponse(json.dumps({'error': error_msg, 'op': op}),
status=400,
content_type=content_type)
path = request.GET.get('p')
username = request.user.username
parent_dir = os.path.dirname(path)
# edit file, so check parent_dir's permission
if check_folder_permission(request, repo_id, parent_dir) != 'rw':
return error_json(_(u'Permission denied'))
is_locked, locked_by_me = check_file_lock(repo_id, path, username)
if (is_locked, locked_by_me) == (None, None):
return error_json(_(u'Check file lock error'))
if is_locked and not locked_by_me:
return error_json(_(u'File is locked'))
repo = get_repo(repo_id)
if not repo:
return error_json(_(u'The library does not exist.'))
if repo.encrypted:
repo.password_set = seafile_api.is_password_set(repo_id, username)
if not repo.password_set:
return error_json(_(u'The library is encrypted.'), 'decrypt')
content = request.POST.get('content')
encoding = request.POST.get('encoding')
if content is None or not path or encoding not in ["gbk", "utf-8"]:
return error_json(_(u'Invalid arguments'))
head_id = request.GET.get('head', None)
content = content.encode(encoding)
# first dump the file content to a tmp file, then update the file
fd, tmpfile = mkstemp()
def remove_tmp_file():
try:
os.remove(tmpfile)
except:
pass
try:
bytesWritten = os.write(fd, content)
except:
bytesWritten = -1
finally:
os.close(fd)
if bytesWritten != len(content):
remove_tmp_file()
return error_json()
req_from = request.GET.get('from', '')
if req_from == 'wiki_page_edit' or req_from == 'wiki_page_new':
try:
gid = int(request.GET.get('gid', 0))
except ValueError:
gid = 0
wiki_name = os.path.splitext(os.path.basename(path))[0]
next = reverse('group_wiki', args=[gid, wiki_name])
elif req_from == 'personal_wiki_page_edit' or req_from == 'personal_wiki_page_new':
wiki_name = os.path.splitext(os.path.basename(path))[0]
next = reverse('personal_wiki', args=[wiki_name])
else:
next = reverse('view_lib_file', args=[repo_id, urlquote(path)])
parent_dir = os.path.dirname(path).encode('utf-8')
filename = os.path.basename(path).encode('utf-8')
try:
seafserv_threaded_rpc.put_file(repo_id, tmpfile, parent_dir,
filename, username, head_id)
remove_tmp_file()
return HttpResponse(json.dumps({'href': next}),
content_type=content_type)
except SearpcError, e:
remove_tmp_file()
return error_json(str(e))
@login_required
def file_edit(request, repo_id):
repo = get_repo(repo_id)
if not repo:
raise Http404
if request.method == 'POST':
return file_edit_submit(request, repo_id)
path = request.GET.get('p', '/')
if path[-1] == '/':
path = path[:-1]
u_filename = os.path.basename(path)
filename = urllib2.quote(u_filename.encode('utf-8'))
parent_dir = os.path.dirname(path)
if check_folder_permission(request, repo.id, parent_dir) != 'rw':
return render_permission_error(request, _(u'Unable to edit file'))
head_id = repo.head_cmmt_id
obj_id = get_file_id_by_path(repo_id, path)
if not obj_id:
return render_error(request, _(u'The file does not exist.'))
token = seafile_api.get_fileserver_access_token(repo_id, obj_id, 'view',
request.user.username)
# generate path and link
zipped = gen_path_link(path, repo.name)
filetype, fileext = get_file_type_and_ext(filename)
op = None
err = ''
file_content = None
encoding = None
file_encoding_list = FILE_ENCODING_LIST
if filetype == TEXT or filetype == MARKDOWN:
if repo.encrypted:
repo.password_set = seafile_api.is_password_set(repo_id, request.user.username)
if not repo.password_set:
op = 'decrypt'
if not op:
inner_path = gen_inner_file_get_url(token, filename)
file_enc = request.GET.get('file_enc', 'auto')
if not file_enc in FILE_ENCODING_LIST:
file_enc = 'auto'
err, file_content, encoding = repo_file_get(inner_path, file_enc)
if encoding and encoding not in FILE_ENCODING_LIST:
file_encoding_list.append(encoding)
else:
err = _(u'Edit online is not offered for this type of file.')
# Redirect to different place according to from page when user click
# cancel button on file edit page.
cancel_url = reverse('view_lib_file', args=[repo.id, urlquote(path)])
page_from = request.GET.get('from', '')
gid = request.GET.get('gid', '')
wiki_name = os.path.splitext(u_filename)[0]
if page_from == 'wiki_page_edit' or page_from == 'wiki_page_new':
cancel_url = reverse('group_wiki', args=[gid, wiki_name])
elif page_from == 'personal_wiki_page_edit' or page_from == 'personal_wiki_page_new':
cancel_url = reverse('personal_wiki', args=[wiki_name])
return render_to_response('file_edit.html', {
'repo':repo,
'u_filename':u_filename,
'wiki_name': wiki_name,
'path':path,
'zipped':zipped,
'filetype':filetype,
'fileext':fileext,
'op':op,
'err':err,
'file_content':file_content,
'encoding': encoding,
'file_encoding_list':file_encoding_list,
'head_id': head_id,
'from': page_from,
'gid': gid,
'cancel_url': cancel_url,
}, context_instance=RequestContext(request))
@login_required
def view_raw_file(request, repo_id, file_path):
"""Returns raw content of a file.
Used when use viewer.js to preview opendocument file.
Arguments:
- `request`:
- `repo_id`:
"""
repo = get_repo(repo_id)
if not repo:
raise Http404
file_path = file_path.rstrip('/')
if file_path[0] != '/':
file_path = '/' + file_path
obj_id = get_file_id_by_path(repo_id, file_path)
if not obj_id:
raise Http404
raw_path, inner_path, user_perm = get_file_view_path_and_perm(
request, repo.id, obj_id, file_path)
if user_perm is None:
raise Http404
return HttpResponseRedirect(raw_path)
def send_file_access_msg(request, repo, path, access_from):
"""Send file downlaod msg.
Arguments:
- `request`:
- `repo`:
- `obj_id`:
- `access_from`: web or api
"""
username = request.user.username
ip = get_remote_ip(request)
user_agent = request.META.get("HTTP_USER_AGENT")
msg = 'file-download-%s\t%s\t%s\t%s\t%s\t%s' % \
(access_from, username, ip, user_agent, repo.id, path)
msg_utf8 = msg.encode('utf-8')
try:
send_message('seahub.stats', msg_utf8)
except Exception as e:
logger.error("Error when sending file-download-%s message: %s" %
(access_from, str(e)))
@login_required
def download_file(request, repo_id, obj_id):
"""Download file in repo/file history page.
Arguments:
- `request`:
- `repo_id`:
- `obj_id`:
"""
username = request.user.username
repo = get_repo(repo_id)
if not repo:
raise Http404
if repo.encrypted and not seafile_api.is_password_set(repo_id, username):
return HttpResponseRedirect(reverse('view_common_lib_dir', args=[repo_id, '']))
# Permission check and generate download link
path = request.GET.get('p', '')
if check_repo_access_permission(repo_id, request.user) or \
get_file_access_permission(repo_id, path, username):
# Get a token to access file
token = seafile_api.get_fileserver_access_token(repo_id, obj_id,
'download', username)
else:
messages.error(request, _(u'Unable to download file'))
next = request.META.get('HTTP_REFERER', settings.SITE_ROOT)
return HttpResponseRedirect(next)
# send stats message
send_file_access_msg(request, repo, path, 'web')
file_name = os.path.basename(path.rstrip('/'))
redirect_url = gen_file_get_url(token, file_name)
return HttpResponseRedirect(redirect_url)
########## text diff
def get_file_content_by_commit_and_path(request, repo_id, commit_id, path, file_enc):
try:
obj_id = seafserv_threaded_rpc.get_file_id_by_commit_and_path( \
repo_id, commit_id, path)
except:
return None, 'bad path'
if not obj_id or obj_id == EMPTY_SHA1:
return '', None
else:
permission = check_repo_access_permission(repo_id, request.user)
if permission:
# Get a token to visit file
token = seafile_api.get_fileserver_access_token(repo_id, obj_id,
'view',
request.user.username)
else:
return None, 'permission denied'
filename = os.path.basename(path)
inner_path = gen_inner_file_get_url(token, filename)
try:
err, file_content, encoding = repo_file_get(inner_path, file_enc)
except Exception, e:
return None, 'error when read file from fileserver: %s' % e
return file_content, err
@login_required
def text_diff(request, repo_id):
commit_id = request.GET.get('commit', '')
path = request.GET.get('p', '')
u_filename = os.path.basename(path)
file_enc = request.GET.get('file_enc', 'auto')
if not file_enc in FILE_ENCODING_LIST:
file_enc = 'auto'
if not (commit_id and path):
return render_error(request, 'bad params')
repo = get_repo(repo_id)
if not repo:
return render_error(request, 'bad repo')
current_commit = seafserv_threaded_rpc.get_commit(repo.id, repo.version, commit_id)
if not current_commit:
return render_error(request, 'bad commit id')
prev_commit = seafserv_threaded_rpc.get_commit(repo.id, repo.version, current_commit.parent_id)
if not prev_commit:
return render_error('bad commit id')
path = path.encode('utf-8')
current_content, err = get_file_content_by_commit_and_path(request, \
repo_id, current_commit.id, path, file_enc)
if err:
return render_error(request, err)
prev_content, err = get_file_content_by_commit_and_path(request, \
repo_id, prev_commit.id, path, file_enc)
if err:
return render_error(request, err)
is_new_file = False
diff_result_table = ''
if prev_content == '' and current_content == '':
is_new_file = True
else:
diff = HtmlDiff()
diff_result_table = diff.make_table(prev_content.splitlines(),
current_content.splitlines(), True)
zipped = gen_path_link(path, repo.name)
return render_to_response('text_diff.html', {
'u_filename':u_filename,
'repo': repo,
'path': path,
'zipped': zipped,
'current_commit': current_commit,
'prev_commit': prev_commit,
'diff_result_table': diff_result_table,
'is_new_file': is_new_file,
}, context_instance=RequestContext(request))
########## office related
@require_POST
@csrf_exempt
@json_response
def office_convert_add_task(request):
try:
file_id = request.POST.get('file_id')
doctype = request.POST.get('doctype')
raw_path = request.POST.get('raw_path')
except KeyError:
return HttpResponseBadRequest('invalid params')
if not _check_cluster_internal_token(request, file_id):
return HttpResponseForbidden()
if len(file_id) != 40:
return HttpResponseBadRequest('invalid params')
return add_office_convert_task(file_id, doctype, raw_path, internal=True)
def _check_office_convert_perm(request, repo_id, path, ret):
token = request.GET.get('token', '')
if not token:
# Work around for the images embedded in excel files
referer = request.META.get('HTTP_REFERER', '')
if referer:
token = urlparse.parse_qs(
urlparse.urlparse(referer).query).get('token', [''])[0]
if token:
fileshare = FileShare.objects.get_valid_file_link_by_token(token)
if not fileshare or fileshare.repo_id != repo_id:
return False
if fileshare.is_file_share_link() and fileshare.path == path:
return True
if fileshare.is_dir_share_link():
ret['dir_share_path'] = fileshare.path
return True
return False
else:
return request.user.is_authenticated() and \
check_folder_permission(request, repo_id, '/') is not None
def _check_cluster_internal_token(request, file_id):
token = request.META.get('Seafile-Office-Preview-Token', '')
if not token:
return HttpResponseForbidden()
try:
s = '-'.join([file_id, datetime.datetime.now().strftime('%Y%m%d')])
return signing.Signer().unsign(token) == s
except signing.BadSignature:
return False
def _office_convert_get_file_id_internal(request):
file_id = request.GET.get('file_id', '')
if len(file_id) != 40:
raise BadRequestException()
if not _check_cluster_internal_token(request, file_id):
raise RequestForbbiddenException()
return file_id
def _office_convert_get_file_id(request, repo_id=None, commit_id=None, path=None):
repo_id = repo_id or request.GET.get('repo_id', '')
commit_id = commit_id or request.GET.get('commit_id', '')
path = path or request.GET.get('path', '')
if not (repo_id and path and commit_id):
raise BadRequestException()
if '../' in path:
raise BadRequestException()
ret = {'dir_share_path': None}
if not _check_office_convert_perm(request, repo_id, path, ret):
raise BadRequestException()
if ret['dir_share_path']:
path = posixpath.join(ret['dir_share_path'], path.lstrip('/'))
return seafserv_threaded_rpc.get_file_id_by_commit_and_path(repo_id, commit_id, path)
@json_response
def office_convert_query_status(request, cluster_internal=False):
if not cluster_internal and not request.is_ajax():
raise Http404
doctype = request.GET.get('doctype', None)
page = 0 if doctype == 'spreadsheet' else int_param(request, 'page')
if cluster_internal:
file_id = _office_convert_get_file_id_internal(request)
else:
file_id = _office_convert_get_file_id(request)
ret = {'success': False}
try:
ret = query_office_convert_status(file_id, page, cluster_internal=cluster_internal)
except Exception, e:
logging.exception('failed to call query_office_convert_status')
ret['error'] = str(e)
return ret
_OFFICE_PAGE_PATTERN = re.compile(r'^[\d]+\.page|file\.css|file\.outline|index.html|index_html_.*.png$')
def office_convert_get_page(request, repo_id, commit_id, path, filename, cluster_internal=False):
"""Valid static file path inclueds:
- "1.page" "2.page" for pdf/doc/ppt
- index.html for spreadsheets and index_html_xxx.png for images embedded in spreadsheets
"""
if not HAS_OFFICE_CONVERTER:
raise Http404
if not _OFFICE_PAGE_PATTERN.match(filename):
return HttpResponseForbidden()
path = u'/' + path
if cluster_internal:
file_id = _office_convert_get_file_id_internal(request)
else:
file_id = _office_convert_get_file_id(request, repo_id, commit_id, path)
resp = get_office_converted_page(
request, repo_id, commit_id, path, filename, file_id, cluster_internal=cluster_internal)
if filename.endswith('.page'):
content_type = 'text/html'
else:
content_type = mimetypes.guess_type(filename)[0] or 'text/html'
resp['Content-Type'] = content_type
return resp
###### private file/dir shares
@login_required
def view_priv_shared_file(request, token):
"""View private shared file.
"""
try:
pfs = PrivateFileDirShare.objects.get_priv_file_dir_share_by_token(token)
except PrivateFileDirShare.DoesNotExist:
raise Http404
repo_id = pfs.repo_id
repo = get_repo(repo_id)
if not repo:
raise Http404
username = request.user.username
if username != pfs.from_user and username != pfs.to_user:
raise Http404 # permission check
if request.GET.get('dl', '') == '1':
# download private shared file
return _download_file_from_share_link(request, pfs)
path = normalize_file_path(pfs.path)
obj_id = seafile_api.get_file_id_by_path(repo.id, path)
if not obj_id:
raise Http404
filename = os.path.basename(path)
filetype, fileext = get_file_type_and_ext(filename)
if filetype == VIDEO or filetype == AUDIO:
access_token = seafile_api.get_fileserver_access_token(repo.id, obj_id,
'view', username,
use_onetime=False)
else:
access_token = seafile_api.get_fileserver_access_token(repo.id, obj_id,
'view', username)
raw_path = gen_file_get_url(access_token, filename)
inner_path = gen_inner_file_get_url(access_token, filename)
# get file content
ret_dict = {'err': '', 'file_content': '', 'encoding': '', 'file_enc': '',
'file_encoding_list': [], 'filetype': filetype}
fsize = get_file_size(repo.store_id, repo.version, obj_id)
exceeds_limit, err_msg = file_size_exceeds_preview_limit(fsize, filetype)
if exceeds_limit:
ret_dict['err'] = err_msg
else:
"""Choose different approach when dealing with different type of file."""
if is_textual_file(file_type=filetype):
handle_textual_file(request, filetype, inner_path, ret_dict)
elif filetype == DOCUMENT:
handle_document(inner_path, obj_id, fileext, ret_dict)
elif filetype == SPREADSHEET:
handle_spreadsheet(inner_path, obj_id, fileext, ret_dict)
elif filetype == PDF:
handle_pdf(inner_path, obj_id, fileext, ret_dict)
accessible_repos = get_unencry_rw_repos_by_user(request)
save_to_link = reverse('save_private_file_share', args=[pfs.token])
return render_to_response('shared_file_view.html', {
'repo': repo,
'obj_id': obj_id,
'path': path,
'file_name': filename,
'file_size': fsize,
'access_token': access_token,
'fileext': fileext,
'raw_path': raw_path,
'shared_by': pfs.from_user,
'err': ret_dict['err'],
'file_content': ret_dict['file_content'],
'encoding': ret_dict['encoding'],
'file_encoding_list':ret_dict['file_encoding_list'],
'filetype': ret_dict['filetype'],
'use_pdfjs':USE_PDFJS,
'accessible_repos': accessible_repos,
'save_to_link': save_to_link,
}, context_instance=RequestContext(request))
@login_required
def file_access(request, repo_id):
"""List file access log.
"""
if not is_pro_version() or not FILE_AUDIT_ENABLED:
raise Http404
referer = request.META.get('HTTP_REFERER', None)
next = settings.SITE_ROOT if referer is None else referer
repo = get_repo(repo_id)
if not repo:
messages.error(request, _("Library does not exist"))
return HttpResponseRedirect(next)
path = request.GET.get('p', None)
if not path:
messages.error(request, _("Argument missing"))
return HttpResponseRedirect(next)
if not seafile_api.get_file_id_by_path(repo_id, path):
messages.error(request, _("File does not exist"))
return HttpResponseRedirect(next)
# perm check
if check_folder_permission(request, repo_id, path) != 'rw':
messages.error(request, _("Permission denied"))
return HttpResponseRedirect(next)
# Make sure page request is an int. If not, deliver first page.
try:
current_page = int(request.GET.get('page', '1'))
per_page = int(request.GET.get('per_page', '100'))
except ValueError:
current_page = 1
per_page = 100
start = per_page * (current_page - 1)
limit = per_page + 1
if is_org_context(request):
org_id = request.user.org.org_id
events = get_file_audit_events_by_path(None, org_id, repo_id, path, start, limit)
else:
events = get_file_audit_events_by_path(None, 0, repo_id, path, start, limit)
events = events if events else []
if len(events) == per_page + 1:
page_next = True
else:
page_next = False
events = events[:per_page]
for ev in events:
ev.repo = get_repo(ev.repo_id)
ev.filename = os.path.basename(ev.file_path)
ev.time = utc_to_local(ev.timestamp)
ev.event_type, ev.show_device = generate_file_audit_event_type(ev)
filename = os.path.basename(path)
zipped = gen_path_link(path, repo.name)
extra_href = "&p=%s" % urlquote(path)
return render_to_response('file_access.html', {
'repo': repo,
'path': path,
'filename': filename,
'zipped': zipped,
'events': events,
'extra_href': extra_href,
'current_page': current_page,
'prev_page': current_page-1,
'next_page': current_page+1,
'per_page': per_page,
'page_next': page_next,
}, context_instance=RequestContext(request))
<file_sep>/seahub/api2/models.py
import uuid
import hmac
from hashlib import sha1
from django.db import models
from seahub.base.fields import LowerCaseCharField
DESKTOP_PLATFORMS = ('windows', 'linux', 'mac')
class Token(models.Model):
"""
The default authorization token model.
"""
key = models.CharField(max_length=40, primary_key=True)
user = LowerCaseCharField(max_length=255, unique=True)
created = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(Token, self).save(*args, **kwargs)
def generate_key(self):
unique = str(uuid.uuid4())
return hmac.new(unique, digestmod=sha1).hexdigest()
def __unicode__(self):
return self.key
class TokenV2Manager(models.Manager):
def get_user_devices(self, username):
'''List user devices, most recently used first'''
devices = super(TokenV2Manager, self).filter(user=username)
platform_priorities = {
'windows': 0,
'linux': 0,
'mac': 0,
'android': 1,
'ios': 1,
}
def sort_devices(d1, d2):
'''Desktop clients are listed before mobile clients. Devices of
the same category are listed by most recently used first
'''
ret = cmp(platform_priorities[d1.platform], platform_priorities[d2.platform])
if ret != 0:
return ret
return cmp(d2.last_accessed, d1.last_accessed)
return [ d.as_dict() for d in sorted(devices, sort_devices) ]
def _get_token_by_user_device(self, username, platform, device_id):
try:
return super(TokenV2Manager, self).get(user=username,
platform=platform,
device_id=device_id)
except TokenV2.DoesNotExist:
return None
def get_or_create_token(self, username, platform, device_id, device_name,
client_version, platform_version, last_login_ip):
token = self._get_token_by_user_device(username, platform, device_id)
if token:
if token.client_version != client_version or token.platform_version != platform_version \
or token.device_name != device_name:
token.client_version = client_version
token.platform_version = platform_version
token.device_name = device_name
token.save()
return token
token = TokenV2(user=username,
platform=platform,
device_id=device_id,
device_name=device_name,
client_version=client_version,
platform_version=platform_version,
last_login_ip=last_login_ip)
token.save()
return token
def delete_device_token(self, username, platform, device_id):
super(TokenV2Manager, self).filter(user=username, platform=platform, device_id=device_id).delete()
class TokenV2(models.Model):
"""
Device specific token
"""
key = models.CharField(max_length=40, primary_key=True)
user = LowerCaseCharField(max_length=255)
# windows/linux/mac/ios/android
platform = LowerCaseCharField(max_length=32)
# ccnet id, android secure id, etc.
device_id = models.CharField(max_length=40)
# lin-laptop
device_name = models.CharField(max_length=40)
# platform version
platform_version = LowerCaseCharField(max_length=16)
# seafile client/app version
client_version = LowerCaseCharField(max_length=16)
# most recent activity
last_accessed = models.DateTimeField(auto_now=True)
last_login_ip = models.GenericIPAddressField(null=True, default=None)
objects = TokenV2Manager()
class Meta:
unique_together = (('user', 'platform', 'device_id'),)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(TokenV2, self).save(*args, **kwargs)
def generate_key(self):
unique = str(uuid.uuid4())
return hmac.new(unique, digestmod=sha1).hexdigest()
def __unicode__(self):
return "TokenV2{user=%(user)s,device=%(device_name)s}" % \
dict(user=self.user,device_name=self.device_name)
def is_desktop_client(self):
return str(self.platform) in ('windows', 'linux', 'mac')
def as_dict(self):
return dict(key=self.key,
user=self.user,
platform=self.platform,
device_id=self.device_id,
device_name=self.device_name,
client_version=self.client_version,
platform_version=self.platform_version,
last_accessed=self.last_accessed,
last_login_ip=self.last_login_ip)
<file_sep>/seahub/views/repo.py
# -*- coding: utf-8 -*-
import os
import posixpath
import logging
from django.core.urlresolvers import reverse
from django.db.models import F
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.utils.http import urlquote
import seaserv
from seaserv import seafile_api
from seahub.auth.decorators import login_required
from seahub.options.models import UserOptions, CryptoOptionNotSetError
from seahub.share.models import FileShare, UploadLinkShare, \
check_share_link_common
from seahub.views import gen_path_link, get_repo_dirents, \
check_repo_access_permission
from seahub.utils import gen_file_upload_url, gen_dir_share_link, \
gen_shared_upload_link, user_traffic_over_limit, render_error, \
get_file_type_and_ext
from seahub.settings import FORCE_SERVER_CRYPTO, \
ENABLE_UPLOAD_FOLDER, ENABLE_RESUMABLE_FILEUPLOAD, ENABLE_THUMBNAIL, \
THUMBNAIL_ROOT, THUMBNAIL_DEFAULT_SIZE, THUMBNAIL_SIZE_FOR_GRID
from seahub.utils import gen_file_get_url
from seahub.utils.file_types import IMAGE, GIMP
from seahub.thumbnail.utils import get_share_link_thumbnail_src
# Get an instance of a logger
logger = logging.getLogger(__name__)
def get_repo(repo_id):
return seafile_api.get_repo(repo_id)
def get_commit(repo_id, repo_version, commit_id):
return seaserv.get_commit(repo_id, repo_version, commit_id)
def get_repo_size(repo_id):
return seafile_api.get_repo_size(repo_id)
def is_password_set(repo_id, username):
return seafile_api.is_password_set(repo_id, username)
# def check_dir_access_permission(username, repo_id, path):
# """Check user has permission to view the directory.
# 1. check whether this directory is private shared.
# 2. if failed, check whether the parent of this directory is private shared.
# """
# pfs = PrivateFileDirShare.objects.get_private_share_in_dir(username,
# repo_id, path)
# if pfs is None:
# dirs = PrivateFileDirShare.objects.list_private_share_in_dirs_by_user_and_repo(username, repo_id)
# for e in dirs:
# if path.startswith(e.path):
# return e.permission
# return None
# else:
# return pfs.permission
def get_path_from_request(request):
path = request.GET.get('p', '/')
if path[-1] != '/':
path = path + '/'
return path
def get_next_url_from_request(request):
return request.GET.get('next', None)
def get_nav_path(path, repo_name):
return gen_path_link(path, repo_name)
def get_shared_groups_by_repo_and_user(repo_id, username):
"""Get all groups which this repo is shared.
"""
repo_shared_groups = seaserv.get_shared_groups_by_repo(repo_id)
# Filter out groups that user is joined.
groups = [x for x in repo_shared_groups if seaserv.is_group_user(x.id, username)]
return groups
def is_no_quota(repo_id):
return True if seaserv.check_quota(repo_id) < 0 else False
def get_upload_url(request, repo_id):
username = request.user.username
if check_repo_access_permission(repo_id, request.user) == 'rw':
token = seafile_api.get_fileserver_access_token(repo_id, 'dummy',
'upload', username)
return gen_file_upload_url(token, 'upload')
else:
return ''
# def get_api_upload_url(request, repo_id):
# """Get file upload url for web api.
# """
# username = request.user.username
# if check_repo_access_permission(repo_id, request.user) == 'rw':
# token = seafile_api.get_fileserver_access_token(repo_id, 'dummy',
# 'upload', username)
# return gen_file_upload_url(token, 'upload-api')
# else:
# return ''
# def get_api_update_url(request, repo_id):
# username = request.user.username
# if check_repo_access_permission(repo_id, request.user) == 'rw':
# token = seafile_api.get_fileserver_access_token(repo_id, 'dummy',
# 'update', username)
# return gen_file_upload_url(token, 'update-api')
# else:
# return ''
def get_fileshare(repo_id, username, path):
if path == '/': # no shared link for root dir
return None
l = FileShare.objects.filter(repo_id=repo_id).filter(
username=username).filter(path=path)
return l[0] if len(l) > 0 else None
def get_dir_share_link(fileshare):
# dir shared link
if fileshare:
dir_shared_link = gen_dir_share_link(fileshare.token)
else:
dir_shared_link = ''
return dir_shared_link
def get_uploadlink(repo_id, username, path):
if path == '/': # no shared upload link for root dir
return None
l = UploadLinkShare.objects.filter(repo_id=repo_id).filter(
username=username).filter(path=path)
return l[0] if len(l) > 0 else None
def get_dir_shared_upload_link(uploadlink):
# dir shared upload link
if uploadlink:
dir_shared_upload_link = gen_shared_upload_link(uploadlink.token)
else:
dir_shared_upload_link = ''
return dir_shared_upload_link
@login_required
def repo_history_view(request, repo_id):
"""View repo in history.
"""
repo = get_repo(repo_id)
if not repo:
raise Http404
username = request.user.username
path = get_path_from_request(request)
user_perm = check_repo_access_permission(repo.id, request.user)
if user_perm is None:
return render_error(request, _(u'Permission denied'))
try:
server_crypto = UserOptions.objects.is_server_crypto(username)
except CryptoOptionNotSetError:
# Assume server_crypto is ``False`` if this option is not set.
server_crypto = False
if repo.encrypted and \
(repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \
and not is_password_set(repo.id, username):
return render_to_response('decrypt_repo_form.html', {
'repo': repo,
'next': get_next_url_from_request(request) or reverse("view_common_lib_dir", args=[repo_id, '/']),
'force_server_crypto': FORCE_SERVER_CRYPTO,
}, context_instance=RequestContext(request))
commit_id = request.GET.get('commit_id', None)
if commit_id is None:
return HttpResponseRedirect(reverse("view_common_lib_dir", args=[repo_id, '/']))
current_commit = get_commit(repo.id, repo.version, commit_id)
if not current_commit:
current_commit = get_commit(repo.id, repo.version, repo.head_cmmt_id)
file_list, dir_list, dirent_more = get_repo_dirents(request, repo,
current_commit, path)
zipped = get_nav_path(path, repo.name)
repo_owner = seafile_api.get_repo_owner(repo.id)
is_repo_owner = True if username == repo_owner else False
return render_to_response('repo_history_view.html', {
'repo': repo,
"is_repo_owner": is_repo_owner,
'user_perm': user_perm,
'current_commit': current_commit,
'dir_list': dir_list,
'file_list': file_list,
'path': path,
'zipped': zipped,
}, context_instance=RequestContext(request))
########## shared dir/uploadlink
def _download_dir_from_share_link(request, fileshare, repo, real_path):
# check whether owner's traffic over the limit
if user_traffic_over_limit(fileshare.username):
return render_error(
request, _(u'Unable to access file: share link traffic is used up.'))
shared_by = fileshare.username
if real_path == '/':
dirname = repo.name
else:
dirname = os.path.basename(real_path.rstrip('/'))
dir_id = seafile_api.get_dir_id_by_path(repo.id, real_path)
if not dir_id:
return render_error(
request, _(u'Unable to download: folder not found.'))
try:
total_size = seaserv.seafserv_threaded_rpc.get_dir_size(
repo.store_id, repo.version, dir_id)
except Exception as e:
logger.error(str(e))
return render_error(request, _(u'Internal Error'))
if total_size > seaserv.MAX_DOWNLOAD_DIR_SIZE:
return render_error(request, _(u'Unable to download directory "%s": size is too large.') % dirname)
token = seafile_api.get_fileserver_access_token(repo.id,
dir_id,
'download-dir',
request.user.username)
try:
seaserv.send_message('seahub.stats', 'dir-download\t%s\t%s\t%s\t%s' %
(repo.id, shared_by, dir_id, total_size))
except Exception as e:
logger.error('Error when sending dir-download message: %s' % str(e))
return HttpResponseRedirect(gen_file_get_url(token, dirname))
def view_shared_dir(request, token):
assert token is not None # Checked by URLconf
fileshare = FileShare.objects.get_valid_dir_link_by_token(token)
if fileshare is None:
raise Http404
password_check_passed, err_msg = check_share_link_common(request, fileshare)
if not password_check_passed:
d = {'token': token, 'view_name': 'view_shared_dir', 'err_msg': err_msg}
return render_to_response('share_access_validation.html', d,
context_instance=RequestContext(request))
username = fileshare.username
repo_id = fileshare.repo_id
# Get path from frontend, use '/' if missing, and construct request path
# with fileshare.path to real path, used to fetch dirents by RPC.
req_path = request.GET.get('p', '/')
if req_path[-1] != '/':
req_path += '/'
if req_path == '/':
real_path = fileshare.path
else:
real_path = posixpath.join(fileshare.path, req_path.lstrip('/'))
if real_path[-1] != '/': # Normalize dir path
real_path += '/'
repo = get_repo(repo_id)
if not repo:
raise Http404
# Check path still exist, otherwise show error
if not seafile_api.get_dir_id_by_path(repo.id, fileshare.path):
return render_error(request, _('"%s" does not exist.') % fileshare.path)
# download shared dir
if request.GET.get('dl', '') == '1':
return _download_dir_from_share_link(request, fileshare, repo,
real_path)
if fileshare.path == '/':
# use repo name as dir name if share whole library
dir_name = repo.name
else:
dir_name = os.path.basename(real_path[:-1])
current_commit = seaserv.get_commits(repo_id, 0, 1)[0]
file_list, dir_list, dirent_more = get_repo_dirents(request, repo,
current_commit, real_path)
# generate dir navigator
if fileshare.path == '/':
zipped = gen_path_link(req_path, repo.name)
else:
zipped = gen_path_link(req_path, os.path.basename(fileshare.path[:-1]))
if req_path == '/': # When user view the root of shared dir..
# increase shared link view_cnt,
fileshare = FileShare.objects.get(token=token)
fileshare.view_cnt = F('view_cnt') + 1
fileshare.save()
traffic_over_limit = user_traffic_over_limit(fileshare.username)
# mode to view dir/file items
mode = request.GET.get('mode', 'list')
if mode != 'list':
mode = 'grid'
thumbnail_size = THUMBNAIL_DEFAULT_SIZE if mode == 'list' else THUMBNAIL_SIZE_FOR_GRID
if not repo.encrypted and ENABLE_THUMBNAIL:
for f in file_list:
file_type, file_ext = get_file_type_and_ext(f.obj_name)
if file_type == GIMP or file_type == IMAGE:
f.is_gimp_editable = True
if file_type == IMAGE:
f.is_img = True
if os.path.exists(os.path.join(THUMBNAIL_ROOT, str(thumbnail_size), f.obj_id)):
req_image_path = posixpath.join(req_path, f.obj_name)
src = get_share_link_thumbnail_src(token, thumbnail_size, req_image_path)
f.encoded_thumbnail_src = urlquote(src)
return render_to_response('view_shared_dir.html', {
'repo': repo,
'token': token,
'path': req_path,
'username': username,
'dir_name': dir_name,
'file_list': file_list,
'dir_list': dir_list,
'zipped': zipped,
'traffic_over_limit': traffic_over_limit,
'ENABLE_THUMBNAIL': ENABLE_THUMBNAIL,
'mode': mode,
'thumbnail_size': thumbnail_size,
}, context_instance=RequestContext(request))
def view_shared_upload_link(request, token):
assert token is not None # Checked by URLconf
uploadlink = UploadLinkShare.objects.get_valid_upload_link_by_token(token)
if uploadlink is None:
raise Http404
password_check_passed, err_msg = check_share_link_common(request,
uploadlink,
is_upload_link=True)
if not password_check_passed:
d = {'token': token, 'view_name': 'view_shared_upload_link', 'err_msg': err_msg}
return render_to_response('share_access_validation.html', d,
context_instance=RequestContext(request))
username = uploadlink.username
repo_id = uploadlink.repo_id
repo = get_repo(repo_id)
if not repo:
raise Http404
path = uploadlink.path
if path == '/':
# use repo name as dir name if share whole library
dir_name = repo.name
else:
dir_name = os.path.basename(path[:-1])
repo = get_repo(repo_id)
if not repo:
raise Http404
uploadlink.view_cnt = F('view_cnt') + 1
uploadlink.save()
no_quota = True if seaserv.check_quota(repo_id) < 0 else False
return render_to_response('view_shared_upload_link.html', {
'repo': repo,
'path': path,
'username': username,
'dir_name': dir_name,
'max_upload_file_size': seaserv.MAX_UPLOAD_FILE_SIZE,
'no_quota': no_quota,
'uploadlink': uploadlink,
'enable_upload_folder': ENABLE_UPLOAD_FOLDER,
'enable_resumable_fileupload': ENABLE_RESUMABLE_FILEUPLOAD,
}, context_instance=RequestContext(request))
<file_sep>/seahub/views/modules.py
from seahub.base.models import UserEnabledModule, GroupEnabledModule
from seahub.wiki.models import PersonalWiki
MOD_PERSONAL_WIKI = 'personal wiki'
MOD_GROUP_WIKI = 'group wiki'
class BadModNameError(Exception):
pass
def get_available_mods_by_user(username):
"""Returns a list of available modules for user.
"""
mods_available = [MOD_PERSONAL_WIKI, ]
return mods_available
def get_enabled_mods_by_user(username):
"""Returns a list of enabled modules for user.
"""
mod_enabled = []
personal_wiki_enabled = UserEnabledModule.objects.filter(
username=username, module_name=MOD_PERSONAL_WIKI).exists()
if personal_wiki_enabled:
mod_enabled.append(MOD_PERSONAL_WIKI)
return mod_enabled
def enable_mod_for_user(username, mod_name):
if mod_name != MOD_PERSONAL_WIKI:
raise BadModNameError
return UserEnabledModule(username=username, module_name=mod_name).save()
def disable_mod_for_user(username, mod_name):
if mod_name != MOD_PERSONAL_WIKI:
raise BadModNameError
UserEnabledModule.objects.filter(username=username,
module_name=mod_name).delete()
def get_available_mods_by_group(group_id):
"""Returns a list of available modules for group.
"""
mods_available = [MOD_GROUP_WIKI, ]
return mods_available
def get_enabled_mods_by_group(group_id):
"""Returns a list of enabled modules for group.
"""
mod_enabled = []
group_wiki_enabled = GroupEnabledModule.objects.filter(
group_id=group_id, module_name=MOD_GROUP_WIKI).exists()
if group_wiki_enabled:
mod_enabled.append(MOD_GROUP_WIKI)
return mod_enabled
def enable_mod_for_group(group_id, mod_name):
if mod_name != MOD_GROUP_WIKI:
raise BadModNameError
return GroupEnabledModule(group_id=group_id, module_name=mod_name).save()
def disable_mod_for_group(group_id, mod_name):
if mod_name != MOD_GROUP_WIKI:
raise BadModNameError
GroupEnabledModule.objects.filter(group_id=group_id,
module_name=mod_name).delete()
def get_wiki_enabled_group_list(in_group_ids=None):
"""Return all groups that enable wiki module by default.
If ``in_group_ids`` is provided, return groups within that collection.
Arguments:
- `in_group_ids`: A list contains group ids.
"""
qs = GroupEnabledModule.objects.all()
if in_group_ids is not None:
qs = qs.filter(group_id__in=in_group_ids)
return qs
<file_sep>/seahub/contacts/urls.py
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('',
url(r'^$', contact_list, name='contacts'),
url(r'^list/$', contact_list, name='contact_list'),
url(r'^add/$', contact_add, name='contact_add'),
url(r'^edit/$', contact_edit, name='contact_edit'),
url(r'^delete/$', contact_delete, name='contact_delete'),
)
<file_sep>/tests/api/endpoints/test_groups.py
# -*- coding: utf-8 -*-
import json
from mock import patch
from django.core.urlresolvers import reverse
from seaserv import seafile_api
from seahub.test_utils import BaseTestCase
from seahub.api2.endpoints.groups import Groups
class GroupsTest(BaseTestCase):
def setUp(self):
self.login_as(self.user)
self.group_id = self.group.id
self.group_name = self.group.group_name
self.repo_id = self.repo.id
self.url = reverse('api-v2.1-groups')
# share repo to group
seafile_api.set_group_repo(self.repo_id,
self.group_id, self.user.email, 'rw')
def tearDown(self):
self.remove_group()
self.remove_repo()
def test_get_group_info(self):
resp = self.client.get(self.url)
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert len(json_resp[0]) == 6
group_ids = []
for group in json_resp:
group_ids.append(group['id'])
assert self.group_id in group_ids
def test_get_group_info_with_repos(self):
resp = self.client.get(self.url + '?with_repos=1')
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert len(json_resp[0]) == 7
group_ids = []
group_repos = []
for group in json_resp:
group_ids.append(group['id'])
for repo in group['repos']:
group_repos.append(repo)
group_repo_ids = []
for repo in group_repos:
group_repo_ids.append(repo['id'])
assert self.repo_id in group_repo_ids
assert self.group_id in group_ids
def test_create_group(self):
new_group_name = 'new-group-1'
resp = self.client.post(self.url, {'group_name': new_group_name})
self.assertEqual(201, resp.status_code)
json_resp = json.loads(resp.content)
assert len(json_resp) == 6
assert json_resp['name'] == new_group_name
assert json_resp['creator'] == self.user.email
self.remove_group(json_resp['id'])
def test_create_group_with_cn_name(self):
new_group_name = u'中文'
resp = self.client.post(self.url, {'group_name': new_group_name})
self.assertEqual(201, resp.status_code)
json_resp = json.loads(resp.content)
assert len(json_resp) == 6
assert json_resp['name'] == new_group_name
assert json_resp['creator'] == self.user.email
self.remove_group(json_resp['id'])
def test_can_not_create_group_with_same_name(self):
resp = self.client.post(self.url, {'group_name': self.group_name})
self.assertEqual(400, resp.status_code)
def test_can_not_create_group_with_invalid_name(self):
group_name = 'new%group-2'
resp = self.client.post(self.url, {'group_name': group_name})
self.assertEqual(400, resp.status_code)
@patch.object(Groups, '_can_add_group')
def test_can_not_create_group_with_invalid_permission(self, mock_can_add_group):
mock_can_add_group.return_value = False
group_name = 'new-group-3'
resp = self.client.post(self.url, {'group_name': group_name})
self.assertEqual(403, resp.status_code)
<file_sep>/seahub/utils/repo.py
# -*- coding: utf-8 -*-
import logging
from django.utils.translation import ugettext as _
import seaserv
from seaserv import seafile_api
from seahub.utils import EMPTY_SHA1
from seahub.views import check_repo_access_permission
from seahub.base.accounts import User
logger = logging.getLogger(__name__)
def list_dir_by_path(cmmt, path):
if cmmt.root_id == EMPTY_SHA1:
return []
else:
dirs = seafile_api.list_dir_by_commit_and_path(cmmt.repo_id, cmmt.id, path)
return dirs if dirs else []
def get_sub_repo_abbrev_origin_path(repo_name, origin_path):
"""Return abbrev path for sub repo based on `repo_name` and `origin_path`.
Arguments:
- `repo_id`:
- `origin_path`:
"""
if len(origin_path) > 20:
abbrev_path = origin_path[-20:]
return repo_name + '/...' + abbrev_path
else:
return repo_name + origin_path
<file_sep>/seahub/group/utils.py
# -*- coding: utf-8 -*-
import re
import seaserv
from seahub.utils import is_org_context
class BadGroupNameError(Exception):
pass
class ConflictGroupNameError(Exception):
pass
def validate_group_name(group_name):
"""
Check whether group name is valid.
A valid group name only contains alphanumeric character, and the length
should less than 255.
"""
if len(group_name) > 255:
return False
return re.match('^[\w\s-]+$', group_name, re.U)
def check_group_name_conflict(request, new_group_name, new_group_domain=None):
"""Check if new group name conflict with existed group.
return "True" if conflicted else "False"
"""
org_id = -1
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
checked_groups = seaserv.get_org_groups_by_user(org_id, username)
else:
if request.cloud_mode:
checked_groups = seaserv.get_personal_groups_by_user(username)
else:
checked_groups = seaserv.ccnet_threaded_rpc.get_all_groups(-1, -1)
for g in checked_groups:
if g.group_name == new_group_name and get_group_domain(g.id) == new_group_domain:
return True
return False
def get_group_domain(group_id):
members = seaserv.ccnet_threaded_rpc.get_group_members(group_id)
if len(members):
return members[0].user_name.split('@')[1]
return None
<file_sep>/seahub/urls.py
from django.conf.urls.defaults import *
from django.conf import settings
# from django.views.generic.simple import direct_to_template
from django.views.generic import TemplateView
from seahub.views import *
from seahub.views.file import view_repo_file, view_history_file, view_trash_file,\
view_snapshot_file, file_edit, view_shared_file, view_file_via_shared_dir,\
text_diff, view_priv_shared_file, view_raw_file, view_raw_shared_file, \
download_file, view_lib_file, file_access
from seahub.views.repo import repo_history_view, view_shared_dir, \
view_shared_upload_link
from notifications.views import notification_list
from message.views import user_msg_list, user_msg_remove, user_received_msg_remove
from share.views import gen_private_file_share, rm_private_file_share, \
save_private_file_share
from seahub.views.wiki import personal_wiki, personal_wiki_pages, \
personal_wiki_create, personal_wiki_page_new, personal_wiki_page_edit, \
personal_wiki_page_delete, personal_wiki_use_lib
from seahub.views.sysadmin import *
from seahub.views.ajax import *
from seahub.api2.endpoints.groups import Groups
# Uncomment the next two lines to enable the admin:
#from django.contrib import admin
#admin.autodiscover()
urlpatterns = patterns(
'',
# Example:
# (r'^seahub/', include('seahub.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
#(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('seahub.base.registration_urls')),
url(r'^$', libraries, name='libraries'),
#url(r'^home/$', direct_to_template, { 'template': 'home.html' } ),
url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')),
url(r'^home/my/$', myhome, name='myhome'),
url(r'^home/wiki/$', personal_wiki, name='personal_wiki'),
url(r'^home/wiki/(?P<page_name>[^/]+)$', personal_wiki, name='personal_wiki'),
url(r'^home/wiki_pages/$', personal_wiki_pages, name='personal_wiki_pages'),
url(r'^home/wiki_create/$', personal_wiki_create, name='personal_wiki_create'),
url(r'^home/wiki_use_lib/$', personal_wiki_use_lib, name='personal_wiki_use_lib'),
url(r'^home/wiki_page_new/$', personal_wiki_page_new, name='personal_wiki_page_new'),
url(r'^home/wiki_page_edit/(?P<page_name>[^/]+)$', personal_wiki_page_edit, name='personal_wiki_page_edit'),
url(r'^home/wiki_page_delete/(?P<page_name>[^/]+)$', personal_wiki_page_delete, name='personal_wiki_page_delete'),
url(r'^devices/$', devices, name='devices'),
url(r'^home/devices/unlink/$', unlink_device, name='unlink_device'),
# url(r'^home/public/reply/(?P<msg_id>[\d]+)/$', innerpub_msg_reply, name='innerpub_msg_reply'),
# url(r'^home/owner/(?P<owner_name>[^/]+)/$', ownerhome, name='ownerhome'),
# revert file/dir/repo
url(r'^repo/revert_file/(?P<repo_id>[-0-9a-f]{36})/$', repo_revert_file, name='repo_revert_file'),
url(r'^repo/revert_dir/(?P<repo_id>[-0-9a-f]{36})/$', repo_revert_dir, name='repo_revert_dir'),
url(r'^repo/history/revert/(?P<repo_id>[-0-9a-f]{36})/$', repo_revert_history, name='repo_revert_history'),
(r'^repo/upload_check/$', validate_filename),
url(r'^repo/unsetinnerpub/(?P<repo_id>[-0-9a-f]{36})/$', unsetinnerpub, name='unsetinnerpub'),
url(r'^repo/set_password/$', repo_set_password, name="repo_set_password"),
url(r'^repo/download_dir/(?P<repo_id>[-0-9a-f]{36})/$', repo_download_dir, name='repo_download_dir'),
(r'^repo/upload_error/(?P<repo_id>[-0-9a-f]{36})/$', upload_file_error),
(r'^repo/update_error/(?P<repo_id>[-0-9a-f]{36})/$', update_file_error),
url(r'^repo/file_revisions/(?P<repo_id>[-0-9a-f]{36})/$', file_revisions, name='file_revisions'),
url(r'^repo/file-access/(?P<repo_id>[-0-9a-f]{36})/$', file_access, name='file_access'),
url(r'^repo/text_diff/(?P<repo_id>[-0-9a-f]{36})/$', text_diff, name='text_diff'),
url(r'^repo/history/(?P<repo_id>[-0-9a-f]{36})/$', repo_history, name='repo_history'),
url(r'^repo/history/view/(?P<repo_id>[-0-9a-f]{36})/$', repo_history_view, name='repo_history_view'),
url(r'^repo/recycle/(?P<repo_id>[-0-9a-f]{36})/$', repo_recycle_view, name='repo_recycle_view'),
url(r'^dir/recycle/(?P<repo_id>[-0-9a-f]{36})/$', dir_recycle_view, name='dir_recycle_view'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/online_gc/$', repo_online_gc, name='repo_online_gc'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/files/$', view_repo_file, name="repo_view_file"),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/raw/(?P<file_path>.*)$', view_raw_file, name="view_raw_file"),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/history/files/$', view_history_file, name="view_history_file"),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/trash/files/$', view_trash_file, name="view_trash_file"),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/snapshot/files/$', view_snapshot_file, name="view_snapshot_file"),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/file/edit/$', file_edit, name='file_edit'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/(?P<obj_id>[0-9a-f]{40})/download/$', download_file, name='download_file'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/settings/$', repo_basic_info, name='repo_basic_info'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/settings/transfer-owner/$', repo_transfer_owner, name='repo_transfer_owner'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/settings/change-password/$', repo_change_password, name='repo_change_password'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/settings/shared-link/$', repo_shared_link, name='repo_shared_link'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/settings/share-manage/$', repo_share_manage, name='repo_share_manage'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/settings/folder-perm/$', repo_folder_perm, name='repo_folder_perm'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/transfer-success/$', repo_transfer_success, name='repo_transfer_success'),
### lib (replace the old `repo` urls) ###
# url(r'^lib/(?P<repo_id>[-0-9a-f]{36})/dir/(?P<path>.*)$', view_lib_dir, name='view_lib_dir'),
url(r'^lib/(?P<repo_id>[-0-9a-f]{36})/file(?P<path>.*)$', view_lib_file, name='view_lib_file'),
url(r'^#common/lib/(?P<repo_id>[-0-9a-f]{36})/(?P<path>.*)$', fake_view, name='view_common_lib_dir'),
url(r'^#group/(?P<group_id>\d+)/$', fake_view, name='view_group'),
url(r'^#groups/', fake_view, name='group_list'),
# url(r'^home/my/lib/(?P<repo_id>[-0-9a-f]{36})/dir/(?P<path>.*)$', myhome_lib, name='myhome_lib'),
### share file/dir, upload link ###
# url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/privshare/$', gen_private_file_share, name='gen_private_file_share'),
# url(r'^s/f/(?P<token>[a-f0-9]{10})/$', view_priv_shared_file, name="view_priv_shared_file"),
# url(r'^s/f/(?P<token>[a-f0-9]{10})/rm/$', rm_private_file_share, name="rm_private_file_share"),
# url(r'^s/f/(?P<token>[a-f0-9]{10})/save/$', save_private_file_share, name='save_private_file_share'),
url(r'^f/(?P<token>[a-f0-9]{10})/$', view_shared_file, name='view_shared_file'),
url(r'^f/(?P<token>[a-f0-9]{10})/raw/(?P<obj_id>[0-9a-f]{40})/(?P<file_name>.*)', view_raw_shared_file, name='view_raw_shared_file'),
url(r'^d/(?P<token>[a-f0-9]{10})/$', view_shared_dir, name='view_shared_dir'),
url(r'^d/(?P<token>[a-f0-9]{10})/files/$', view_file_via_shared_dir, name='view_file_via_shared_dir'),
url(r'^u/d/(?P<token>[a-f0-9]{10})/$', view_shared_upload_link, name='view_shared_upload_link'),
### Misc ###
url(r'^image-view/(?P<filename>.*)$', image_view, name='image_view'),
(r'^file_upload_progress_page/$', file_upload_progress_page),
url(r'^activities/$', activities, name='activities'),
url(r'^starred/$', starred, name='starred'),
url(r'^i18n/$', i18n, name='i18n'),
url(r'^convert_cmmt_desc_link/$', convert_cmmt_desc_link, name='convert_cmmt_desc_link'),
url(r'^user/(?P<id_or_email>[^/]+)/msgs/$', user_msg_list, name='user_msg_list'),
url(r'^user/(?P<msg_id>\d+)/msgdel/$', user_msg_remove, name='user_msg_remove'),
url(r'^user/(?P<msg_id>\d+)/remsgdel/$', user_received_msg_remove, name='user_received_msg_remove'),
url(r'^modules/toggle/$', toggle_modules, name="toggle_modules"),
url(r'^download_client_program/$', TemplateView.as_view(template_name="download.html"), name="download_client"),
url(r'^choose_register/$', TemplateView.as_view(template_name="choose_register.html"), name="choose_register"),
### Ajax ###
(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/remove/$', repo_remove),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/dirents/$', get_dirents, name="get_dirents"),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/dirents/delete/$', delete_dirents, name='delete_dirents'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/dirents/move/$', mv_dirents, name='mv_dirents'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/dirents/copy/$', cp_dirents, name='cp_dirents'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/dir/new/$', new_dir, name='new_dir'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/dir/rename/$', rename_dirent, name='rename_dir'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/dir/delete/$', delete_dirent, name='delete_dir'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/dir/mv/$', mv_dir, name='mv_dir'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/dir/cp/$', cp_dir, name='cp_dir'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/dir/sub_repo/$', sub_repo, name='sub_repo'),
url(r'^ajax/cp_progress/$', get_cp_progress, name='get_cp_progress'),
url(r'^ajax/cancel_cp/$', cancel_cp, name='cancel_cp'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/file/new/$', new_file, name='new_file'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/file/rename/$', rename_dirent, name='rename_file'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/file/delete/$', delete_dirent, name='delete_file'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/file/mv/$', mv_file, name='mv_file'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/file/cp/$', cp_file, name='cp_file'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/file/star/$', repo_star_file, name='repo_star_file'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/file/unstar/$', repo_unstar_file, name='repo_unstar_file'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/current_commit/$', get_current_commit, name='get_current_commit'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/history/changes/$', repo_history_changes, name='repo_history_changes'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/encrypted_file/(?P<file_id>[0-9a-f]{40})/download/$', download_enc_file, name='download_enc_file'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/file_op_url/$', get_file_op_url, name='get_file_op_url'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/get-file-uploaded-bytes/$', get_file_uploaded_bytes, name='get_file_uploaded_bytes'),
url(r'^ajax/u/d/(?P<token>[-0-9a-f]{10})/upload/$', get_file_upload_url_ul, name='get_file_upload_url_ul'),
url(r'^ajax/group/(?P<group_id>\d+)/repos/$', get_unenc_group_repos, name='get_group_repos'),
url(r'^ajax/group/(?P<group_id>\d+)/basic-info/$', get_group_basic_info, name='get_group_basic_info'),
url(r'^ajax/group/(?P<group_id>\d+)/toggle-modules/$', toggle_group_modules, name='toggle_group_modules'),
url(r'^ajax/toggle-personal-modules/$', toggle_personal_modules, name='toggle_personal_modules'),
url(r'^ajax/my-unenc-repos/$', get_my_unenc_repos, name='get_my_unenc_repos'),
url(r'^ajax/unenc-rw-repos/$', unenc_rw_repos, name='unenc_rw_repos'),
url(r'^ajax/contacts/$', get_contacts, name='get_contacts'),
url(r'^ajax/upload-file-done/$', upload_file_done, name='upload_file_done'),
url(r'^ajax/unseen-notices-count/$', unseen_notices_count, name='unseen_notices_count'),
url(r'^ajax/get_popup_notices/$', get_popup_notices, name='get_popup_notices'),
url(r'^ajax/set_notices_seen/$', set_notices_seen, name='set_notices_seen'),
url(r'^ajax/set_notice_seen_by_id/$', set_notice_seen_by_id, name='set_notice_seen_by_id'),
url(r'^ajax/space_and_traffic/$', space_and_traffic, name='space_and_traffic'),
url(r'^ajax/events/$', events, name="events"),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/setting/change-basic-info/$', ajax_repo_change_basic_info, name='ajax_repo_change_basic_info'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/setting/transfer-owner/$', ajax_repo_transfer_owner, name='ajax_repo_transfer_owner'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/setting/change-passwd/$', ajax_repo_change_passwd, name='ajax_repo_change_passwd'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/get-folder-perm-by-path/$', get_folder_perm_by_path, name='get_folder_perm_by_path'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/set-user-folder-perm/$', set_user_folder_perm, name='set_user_folder_perm'),
url(r'^ajax/repo/(?P<repo_id>[-0-9a-f]{36})/set-group-folder-perm/$', set_group_folder_perm, name='set_group_folder_perm'),
url(r'^ajax/(?P<repo_id>[-0-9a-f]{36})/repo-dir/recycle/more/$', ajax_repo_dir_recycle_more, name='ajax_repo_dir_recycle_more'),
url(r'^_templates/(?P<template>.*)$', underscore_template, name="underscore_template"),
## ajax lib
url(r'^ajax/lib/(?P<repo_id>[-0-9a-f]{36})/dir/$', list_lib_dir, name="list_lib_dir"),
url(r'^ajax/unset-inner-pub-repo/(?P<repo_id>[-0-9a-f]{36})/$', ajax_unset_inner_pub_repo, name='ajax_unset_inner_pub_repo'),
### Organizaion ###
url(r'^pubinfo/libraries/$', pubrepo, name='pubrepo'),
url(r'^ajax/publicrepo/create/$', public_repo_create, name='public_repo_create'),
url(r'^pubinfo/users/$', pubuser, name='pubuser'),
### Apps ###
(r'^api2/', include('seahub.api2.urls')),
url(r'^api/v2.1/groups/$', Groups.as_view(), name='api-v2.1-groups'),
(r'^avatar/', include('seahub.avatar.urls')),
(r'^notification/', include('seahub.notifications.urls')),
(r'^contacts/', include('seahub.contacts.urls')),
(r'^group/', include('seahub.group.urls')),
(r'^message/', include('seahub.message.urls')),
(r'^options/', include('seahub.options.urls')),
(r'^profile/', include('seahub.profile.urls')),
(r'^share/', include('seahub.share.urls')),
(r'^help/', include('seahub.help.urls')),
url(r'^captcha/', include('captcha.urls')),
(r'^thumbnail/', include('seahub.thumbnail.urls')),
### system admin ###
url(r'^sys/info/$', sys_info, name='sys_info'),
url(r'^sys/settings/$', sys_settings, name='sys_settings'),
url(r'^sys/seafadmin/$', sys_repo_admin, name='sys_repo_admin'),
url(r'^sys/seafadmin/repo/(?P<repo_id>[-0-9a-f]{36})/$', sys_admin_repo, name='sys_admin_repo'),
url(r'^sys/seafadmin/repo/(?P<repo_id>[-0-9a-f]{36})/download-file/$', sys_admin_repo_download_file, name='sys_admin_repo_download_file'),
url(r'^sys/seafadmin/system/$', sys_list_system, name='sys_list_system'),
url(r'^sys/seafadmin/repo-trash/$', sys_repo_trash, name='sys_repo_trash'),
url(r'^sys/seafadmin/repo-trash/clear/$', sys_repo_trash_clear, name="sys_repo_trash_clear"),
url(r'^sys/seafadmin/repo-trash/(?P<repo_id>[-0-9a-f]{36})/remove/$', sys_repo_trash_remove, name="sys_repo_trash_remove"),
url(r'^sys/seafadmin/repo-trash/(?P<repo_id>[-0-9a-f]{36})/restore/$', sys_repo_trash_restore, name="sys_repo_trash_restore"),
url(r'^sys/seafadmin/search/$', sys_repo_search, name='sys_repo_search'),
url(r'^sys/seafadmin/transfer/$', sys_repo_transfer, name='sys_repo_transfer'),
url(r'^sys/seafadmin/delete/(?P<repo_id>[-0-9a-f]{36})/$', sys_repo_delete, name='sys_repo_delete'),
url(r'^sys/useradmin/$', sys_user_admin, name='sys_useradmin'),
url(r'^sys/useradmin/export-excel/$', sys_useradmin_export_excel, name='sys_useradmin_export_excel'),
url(r'^sys/useradmin/ldap/$', sys_user_admin_ldap, name='sys_useradmin_ldap'),
url(r'^sys/useradmin/ldap/imported$', sys_user_admin_ldap_imported, name='sys_useradmin_ldap_imported'),
url(r'^sys/useradmin/admins/$', sys_user_admin_admins, name='sys_useradmin_admins'),
url(r'^sys/groupadmin/$', sys_group_admin, name='sys_group_admin'),
url(r'^sys/groupadmin/export-excel/$', sys_group_admin_export_excel, name='sys_group_admin_export_excel'),
url(r'^sys/groupadmin/(?P<group_id>\d+)/$', sys_admin_group_info, name='sys_admin_group_info'),
url(r'^sys/orgadmin/$', sys_org_admin, name='sys_org_admin'),
url(r'^sys/orgadmin/search/$', sys_org_search, name='sys_org_search'),
url(r'^sys/orgadmin/(?P<org_id>\d+)/set_quota/$', sys_org_set_quota, name='sys_org_set_quota'),
url(r'^sys/orgadmin/(?P<org_id>\d+)/rename/$', sys_org_rename, name='sys_org_rename'),
url(r'^sys/orgadmin/(?P<org_id>\d+)/remove/$', sys_org_remove, name='sys_org_remove'),
url(r'^sys/orgadmin/(?P<org_id>\d+)/set_member_quota/$', sys_org_set_member_quota, name='sys_org_set_member_quota'),
url(r'^sys/orgadmin/(?P<org_id>\d+)/user/$', sys_org_info_user, name='sys_org_info_user'),
url(r'^sys/orgadmin/(?P<org_id>\d+)/group/$', sys_org_info_group, name='sys_org_info_group'),
url(r'^sys/orgadmin/(?P<org_id>\d+)/library/$', sys_org_info_library, name='sys_org_info_library'),
url(r'^sys/orgadmin/(?P<org_id>\d+)/setting/$', sys_org_info_setting, name='sys_org_info_setting'),
url(r'^sys/publinkadmin/$', sys_publink_admin, name='sys_publink_admin'),
url(r'^sys/publink/remove/$', sys_publink_remove, name='sys_publink_remove'),
url(r'^sys/uploadlink/remove/$', sys_upload_link_remove, name='sys_upload_link_remove'),
url(r'^sys/notificationadmin/', notification_list, name='notification_list'),
url(r'^sys/sudo/', sys_sudo_mode, name='sys_sudo_mode'),
url(r'^sys/check-license/', sys_check_license, name='sys_check_license'),
url(r'^useradmin/add/$', user_add, name="user_add"),
url(r'^useradmin/remove/(?P<email>[^/]+)/$', user_remove, name="user_remove"),
url(r'^useradmin/removetrial/(?P<user_or_org>[^/]+)/$', remove_trial, name="remove_trial"),
url(r'^useradmin/search/$', user_search, name="user_search"),
# url(r'^useradmin/makeadmin/(?P<user_id>[^/]+)/$', user_make_admin, name='user_make_admin'),
url(r'^useradmin/removeadmin/(?P<email>[^/]+)/$', user_remove_admin, name='user_remove_admin'),
url(r'^useradmin/info/(?P<email>[^/]+)/$', user_info, name='user_info'),
# url(r'^useradmin/activate/(?P<user_id>[^/]+)/$', user_activate, name='user_activate'),
# url(r'^useradmin/deactivate/(?P<user_id>[^/]+)/$', user_deactivate, name='user_deactivate'),
url(r'^useradmin/toggle_status/(?P<email>[^/]+)/$', user_toggle_status, name='user_toggle_status'),
url(r'^useradmin/toggle_role/(?P<email>[^/]+)/$', user_toggle_role, name='user_toggle_role'),
url(r'^useradmin/(?P<email>[^/]+)/set_quota/$', user_set_quota, name='user_set_quota'),
url(r'^useradmin/password/reset/(?P<email>[^/]+)/$', user_reset, name='user_reset'),
url(r'^useradmin/batchmakeadmin/$', batch_user_make_admin, name='batch_user_make_admin'),
url(r'^useradmin/batchadduser/$', batch_add_user, name='batch_add_user'),
url(r'^client-login/$', client_token_login, name='client_token_login'),
)
from seahub.utils import EVENTS_ENABLED
if EVENTS_ENABLED:
urlpatterns += patterns(
'',
url(r'^sys/virus_scan_records/$', sys_virus_scan_records, name='sys_virus_scan_records'),
url(r'^sys/virus_scan_records/delete/(?P<vid>\d+)/$', sys_delete_virus_scan_records, name='sys_delete_virus_scan_records'),
)
if settings.SERVE_STATIC:
media_url = settings.MEDIA_URL.strip('/')
urlpatterns += patterns('',
(r'^%s/(?P<path>.*)$' % (media_url), 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
if getattr(settings, 'CLOUD_MODE', False):
urlpatterns += patterns('',
(r'^demo/', demo),
)
from seahub.utils import HAS_FILE_SEARCH
if HAS_FILE_SEARCH:
from seahub_extra.search.views import search, pubuser_search
urlpatterns += patterns('',
url(r'^search/$', search, name='search'),
url(r'^pubinfo/users/search/$', pubuser_search, name='pubuser_search'),
)
if getattr(settings, 'ENABLE_PAYMENT', False):
urlpatterns += patterns('',
(r'^pay/', include('seahub_extra.pay.urls')),
)
if getattr(settings, 'ENABLE_SYSADMIN_EXTRA', False):
from seahub_extra.sysadmin_extra.views import sys_login_admin, \
sys_log_file_audit, sys_log_file_update, sys_log_perm_audit, \
sys_login_admin_export_excel, sys_log_file_audit_export_excel, \
sys_log_file_update_export_excel, sys_log_perm_audit_export_excel
urlpatterns += patterns('',
url(r'^sys/loginadmin/$', sys_login_admin, name='sys_login_admin'),
url(r'^sys/loginadmin/export-excel/$', sys_login_admin_export_excel, name='sys_login_admin_export_excel'),
url(r'^sys/log/fileaudit/$', sys_log_file_audit, name='sys_log_file_audit'),
url(r'^sys/log/fileaudit/export-excel/$', sys_log_file_audit_export_excel, name='sys_log_file_audit_export_excel'),
url(r'^sys/log/fileupdate/$', sys_log_file_update, name='sys_log_file_update'),
url(r'^sys/log/fileupdate/export-excel/$', sys_log_file_update_export_excel, name='sys_log_file_update_export_excel'),
url(r'^sys/log/permaudit/$', sys_log_perm_audit, name='sys_log_perm_audit'),
url(r'^sys/log/permaudit/export-excel/$', sys_log_perm_audit_export_excel, name='sys_log_perm_audit_export_excel'),
)
if getattr(settings, 'MULTI_TENANCY', False):
urlpatterns += patterns('',
(r'^org/', include('seahub_extra.organizations.urls')),
)
if getattr(settings, 'ENABLE_SHIB_LOGIN', False):
urlpatterns += patterns('',
url(r'^shib-login/', shib_login, name="shib_login"),
)
if getattr(settings, 'ENABLE_KRB5_LOGIN', False):
urlpatterns += patterns(
'', url(r'^krb5-login/', shib_login, name="krb5_login"),
)
# serve office converter static files
from seahub.utils import HAS_OFFICE_CONVERTER, CLUSTER_MODE, OFFICE_CONVERTOR_NODE
if HAS_OFFICE_CONVERTER:
from seahub.views.file import (
office_convert_query_status, office_convert_get_page, office_convert_add_task
)
urlpatterns += patterns('',
url(r'^office-convert/static/(?P<repo_id>[-0-9a-f]{36})/(?P<commit_id>[0-9a-f]{40})/(?P<path>.+)/(?P<filename>[^/].+)$',
office_convert_get_page,
name='office_convert_get_page'),
url(r'^office-convert/status/$', office_convert_query_status, name='office_convert_query_status'),
)
if CLUSTER_MODE and OFFICE_CONVERTOR_NODE:
urlpatterns += patterns('',
url(r'^office-convert/internal/add-task/$', office_convert_add_task),
url(r'^office-convert/internal/status/$', office_convert_query_status, {'cluster_internal': True}),
url(r'^office-convert/internal/static/(?P<repo_id>[-0-9a-f]{36})/(?P<commit_id>[0-9a-f]{40})/(?P<path>.+)/(?P<filename>[^/].+)$',
office_convert_get_page, {'cluster_internal': True}),
)
if TRAFFIC_STATS_ENABLED:
from seahub.views.sysadmin import sys_traffic_admin
urlpatterns += patterns('',
url(r'^sys/trafficadmin/$', sys_traffic_admin, name='sys_trafficadmin'),
)
<file_sep>/tests/seahub/views/wiki/test_personal_wiki.py
from django.core.urlresolvers import reverse
import seaserv
from seahub.wiki.models import PersonalWiki
from seahub.test_utils import BaseTestCase
class PersonalWikiTest(BaseTestCase):
def test_wiki_does_not_exist(self):
self.login_as(self.user)
resp = self.client.get(reverse('personal_wiki'))
assert resp.context['wiki_exists'] is False
self.assertTemplateUsed('wiki/personal_wiki.html')
def test_home_page_missing(self):
self.login_as(self.user)
PersonalWiki.objects.save_personal_wiki(self.user.username,
self.repo.id)
assert len(PersonalWiki.objects.all()) == 1
resp = self.client.get(reverse('personal_wiki'))
self.assertEqual(302, resp.status_code)
self.assertRedirects(resp, reverse('personal_wiki', args=['home']))
def test_home_page(self):
self.login_as(self.user)
PersonalWiki.objects.save_personal_wiki(self.user.username,
self.repo.id)
assert len(PersonalWiki.objects.all()) == 1
seaserv.post_empty_file(self.repo.id, "/", "home.md",
self.user.username)
for page_name in ["home", "home.md"]:
resp = self.client.get(reverse('personal_wiki', args=[page_name]))
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed('wiki/personal_wiki.html')
self.assertEqual(True, resp.context['wiki_exists'])
self.assertEqual("home", resp.context['page'])
self.assertEqual("/home.md", resp.context['path'])
<file_sep>/static/scripts/app/views/add-pub-repo.js
define([
'jquery',
'simplemodal',
'underscore',
'backbone',
'common',
'app/collections/repos',
'app/views/add-pubrepo-item'
], function($, simplemodal, _, Backbone, Common,
RepoCollection, AddPubrepoItem) {
'use strict';
var AddPubRepoView = Backbone.View.extend({
id: 'add-pubrepo-popup',
template: _.template($('#add-pubrepo-popup-tmpl').html()),
initialize: function(pubRepos) {
this.$el.html(this.template()).modal({});
$('#simplemodal-container').css({'width':'auto', 'height':'auto'});
this.$table = this.$('table');
this.$loadingTip = this.$('.loading-tip');
this.myRepos = new RepoCollection();
this.pubRepos = pubRepos;
this.listenTo(this.myRepos, 'reset', this.reset);
this.myRepos.fetch({reset: true});
},
events: {
'click .submit': 'submit'
},
submit: function () {
var myRepos = this.myRepos.where({'selected':true}),
_this = this,
requests = [];
_.each(myRepos, function (repo){
var repo_id = repo.id,
perm = 'rw';
if (repo.has('pub_perm')) {
perm = repo.get('pub_perm');
}
requests.push(
$.ajax({
url: Common.getUrl({'name':'shared_repos', 'repo_id': repo_id}) + '?share_type=public&permission=' + perm,
type: 'PUT',
beforeSend: Common.prepareCSRFToken,
dataType: 'json',
error: function(xhr, textStatus, errorThrown) {
Common.ajaxErrorHandler(xhr, textStatus, errorThrown);
}
})
);
})
var defer = $.when.apply($, requests);
defer.done(function () {
// when all ajax request complete
$.modal.close();
_this.pubRepos.fetch({reset: true});
});
},
addOne: function(model) {
var view = new AddPubrepoItem({model: model});
this.$table.append(view.render().el);
},
reset: function() {
this.$loadingTip.hide();
this.$table.show()
this.myRepos.each(this.addOne, this);
}
});
return AddPubRepoView;
});
<file_sep>/static/scripts/app/views/top-group-nav.js
define([
'jquery',
'underscore',
'backbone',
'common'
], function($, _, Backbone, Common) {
'use strict';
var GroupNavView = Backbone.View.extend({
el: '.nav .nav-item-group',
popupTemplate: _.template($('#top-group-nav-tmpl').html()),
initialize: function() {
var popup = $(this.popupTemplate({groups: app.pageOptions.top_nav_groups}));
this.$el.append(popup);
popup.css({'right': ($('#top-nav-grp').outerWidth() - popup.outerWidth())/6 * 5});
this.popup = popup;
},
events: {
'mouseenter': 'showPopup',
'mouseleave': 'hidePopup',
'mouseenter #top-nav-grp-list .item': 'highlightGroupItem',
'mouseleave #top-nav-grp-list .item': 'rmHighlightGroupItem',
'click #top-nav-grp-list .item': 'visitGroup'
},
showPopup: function(e) {
this.popup.removeClass('hide');
},
hidePopup: function(e) {
this.popup.addClass('hide');
},
highlightGroupItem: function(e) {
$(e.currentTarget).addClass('hl').children('a').removeClass('vh');
},
rmHighlightGroupItem: function(e) {
$(e.currentTarget).removeClass('hl').children('a').addClass('vh');
},
visitGroup: function(e) {
this.hidePopup(e);
location.href = $(e.currentTarget).attr('data-url');
}
});
return GroupNavView;
});
<file_sep>/static/scripts/app/views/myhome-side-nav.js
define([
'jquery',
'underscore',
'backbone',
'common'
], function($, _, Backbone, Common) {
'use strict';
var MyhomeSideNavView = Backbone.View.extend({
el: '#myhome-side-nav',
template: _.template($("#myhome-side-nav-tmpl").html()),
enableModTemplate: _.template($("#myhome-mods-enable-form-tmpl").html()),
initialize: function() {
this.default_cur_tab = 'libs';
this.data = {
'cur_tab': this.default_cur_tab,
'mods_enabled': app.pageOptions.user_mods_enabled,
'can_add_repo': app.pageOptions.can_add_repo,
'events_enabled': app.pageOptions.events_enabled
};
this.render();
},
render: function() {
this.$el.html(this.template(this.data));
return this;
},
events: {
'click #myhome-enable-mods': 'enableMods'
},
enableMods: function () {
var mods_enabled = app.pageOptions.user_mods_enabled;
var form = $(this.enableModTemplate({
'mods_available': app.pageOptions.user_mods_available,
'mods_enabled': mods_enabled
}));
form.modal();
$('#simplemodal-container').css('height', 'auto');
$('.checkbox-orig', form).click(function() {
$(this).parent().toggleClass('checkbox-checked');
});
var checkbox = $('[name="personal_wiki"]'),
original_checked = checkbox.prop('checked'),
_this = this;
form.submit(function() {
var cur_checked = checkbox.prop('checked');
if (cur_checked == original_checked) {
return false;
}
Common.ajaxPost({
form: form,
form_id: form.attr('id'),
post_url: Common.getUrl({
'name': 'toggle_personal_modules'
}),
post_data: {'personal_wiki': cur_checked },
after_op_success: function () {
if (cur_checked) {
mods_enabled.push('personal wiki');
} else {
var index = mods_enabled.indexOf('personal wiki');
if (index > -1) {
mods_enabled.splice(index, 1); // rm the item
}
}
$.modal.close();
_this.render();
}
});
return false;
});
},
show: function(options) {
if (options && options.cur_tab) {
this.data.cur_tab = options.cur_tab;
this.render();
} else {
if (this.data.cur_tab != this.default_cur_tab) {
this.data.cur_tab = this.default_cur_tab;
this.render();
}
}
this.$el.show();
},
hide: function() {
this.$el.hide();
}
});
return MyhomeSideNavView;
});
<file_sep>/seahub/api2/serializers.py
from rest_framework import serializers
from seahub.auth import authenticate
from seahub.api2.models import Token, TokenV2, DESKTOP_PLATFORMS
from seahub.api2.utils import get_token_v1, get_token_v2
from seahub.profile.models import Profile
def all_none(values):
for value in values:
if value is not None:
return False
return True
def all_not_none(values):
for value in values:
if value is None:
return False
return True
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
# There fields are used by TokenV2
platform = serializers.CharField(required=False)
device_id = serializers.CharField(required=False)
device_name = serializers.CharField(required=False)
# These fields may be needed in the future
client_version = serializers.CharField(required=False)
platform_version = serializers.CharField(required=False)
def validate(self, attrs):
login_id = attrs.get('username')
password = attrs.get('<PASSWORD>')
platform = attrs.get('platform', None)
device_id = attrs.get('device_id', None)
device_name = attrs.get('device_name', None)
client_version = attrs.get('client_version', None)
platform_version = attrs.get('platform_version', None)
v2_fields = (platform, device_id, device_name, client_version, platform_version)
# Decide the version of token we need
if all_none(v2_fields):
v2 = False
elif all_not_none(v2_fields):
v2 = True
else:
raise serializers.ValidationError('invalid params')
username = Profile.objects.get_username_by_login_id(login_id)
if username is None:
username = login_id
if username and password:
user = authenticate(username=username, password=<PASSWORD>)
if user:
if not user.is_active:
raise serializers.ValidationError('User account is disabled.')
else:
raise serializers.ValidationError('Unable to login with provided credentials.')
else:
raise serializers.ValidationError('Must include "username" and "password"')
# Now user is authenticated
if v2:
token = get_token_v2(self.context['request'], username, platform, device_id, device_name,
client_version, platform_version)
else:
token = get_token_v1(username)
return token.key
class AccountSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField()
is_staff = serializers.BooleanField(default=False)
is_active = serializers.BooleanField(default=True)
<file_sep>/static/scripts/app/views/group-item.js
define([
'jquery',
'underscore',
'backbone',
'common',
'app/collections/group-repos',
'app/views/group-repo'
], function($, _, Backbone, Common, GroupRepos, GroupRepoView) {
'use strict';
var GroupItemView = Backbone.View.extend({
template: _.template($('#group-item-tmpl').html()),
events: {
},
initialize: function() {
},
render: function() {
this.$el.html(this.template(this.model.attributes));
var repos = this.model.get('repos');
if (repos.length) {
this.renderRepoList(repos);
}
return this;
},
renderRepoList: function (repos) {
repos.sort(function(a, b) {
return Common.compareTwoWord(a.name, b.name);
});
var group_id = this.model.get('id'),
is_staff = $.inArray(app.pageOptions.username, this.model.get('admins')) != -1 ? true : false,
$listContainer = this.$('tbody');
var groupRepos = new GroupRepos();
groupRepos.setGroupID(group_id);
$(repos).each(function(index, item) {
var view = new GroupRepoView({
model: new Backbone.Model(item, {collection: groupRepos}),
group_id: group_id,
is_staff: is_staff,
show_shared_by: false // don't show 'Shared By'
});
$listContainer.append(view.render().el);
});
}
});
return GroupItemView;
});
<file_sep>/tests/seahub/views/test_shared_dir.py
import os
from django.core.urlresolvers import reverse
from django.test import TestCase
from seahub.share.models import FileShare
from seahub.test_utils import Fixtures
class SharedDirTest(TestCase, Fixtures):
def setUp(self):
share_file_info = {
'username': '<EMAIL>',
'repo_id': self.repo.id,
'path': '/',
'password': <PASSWORD>,
'expire_date': None,
}
self.fs = FileShare.objects.create_dir_link(**share_file_info)
def tearDown(self):
self.remove_repo()
def test_can_render(self):
resp = self.client.get(
reverse('view_shared_dir', args=[self.fs.token])
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_shared_dir.html')
self.assertContains(resp, '<h2>%s</h2>' % self.repo.name)
zip_url = 'href="?p=/&dl=1"'
self.assertContains(resp, zip_url)
def test_can_download(self):
dl_url = reverse('view_shared_dir', args=[self.fs.token]) + \
'?p=/&dl=1'
resp = self.client.get(dl_url)
self.assertEqual(302, resp.status_code)
assert '8082/files/' in resp.get('location')
class EncryptSharedDirTest(TestCase, Fixtures):
def setUp(self):
share_file_info = {
'username': '<EMAIL>',
'repo_id': self.repo.id,
'path': '/',
'password': '<PASSWORD>',
'expire_date': None,
}
self.fs = FileShare.objects.create_dir_link(**share_file_info)
self.sub_dir = self.folder
self.sub_file = self.file
self.filename= os.path.basename(self.file)
def tearDown(self):
self.remove_repo()
def test_can_render(self):
resp = self.client.get(
reverse('view_shared_dir', args=[self.fs.token])
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'share_access_validation.html')
self.assertContains(resp, 'Please input the password')
def test_can_decrypt(self):
resp = self.client.post(
reverse('view_shared_dir', args=[self.fs.token]), {
'password': '<PASSWORD>'
}
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_shared_dir.html')
self.assertContains(resp, '<h2>%s</h2>' % self.repo.name)
def test_wrong_password(self):
resp = self.client.post(
reverse('view_shared_dir', args=[self.fs.token]), {
'password': '<PASSWORD>'
}
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'share_access_validation.html')
self.assertContains(resp, 'Please enter a correct password')
def test_can_visit_sub_dir_without_passwd(self):
resp = self.client.post(
reverse('view_shared_dir', args=[self.fs.token]), {
'password': '<PASSWORD>'
}
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_shared_dir.html')
self.assertContains(resp, '<h2>%s</h2>' % self.repo.name)
resp = self.client.get(
reverse('view_shared_dir', args=[self.fs.token]) + '?p=' + self.sub_dir
)
self.assertEqual(200, resp.status_code)
self.assertTemplateNotUsed(resp, 'share_access_validation.html')
self.assertTemplateUsed(resp, 'view_shared_dir.html')
def test_view_file_via_shared_dir(self):
resp = self.client.post(
reverse('view_file_via_shared_dir', args=[self.fs.token]) + '?p=' + self.sub_file, {
'password': '<PASSWORD>'
}
)
self.assertEqual(200, resp.status_code)
self.assertTemplateNotUsed(resp, 'share_access_validation.html')
self.assertTemplateUsed(resp, 'shared_file_view.html')
self.assertContains(resp, '%s</h2>' % self.filename)
resp = self.client.get(
reverse('view_file_via_shared_dir', args=[self.fs.token]) + '?p=' + self.sub_file
)
self.assertEqual(200, resp.status_code)
self.assertTemplateNotUsed(resp, 'share_access_validation.html')
self.assertTemplateUsed(resp, 'shared_file_view.html')
self.assertContains(resp, '%s</h2>' % self.filename)
def test_view_file_via_shared_dir_without_password(self):
resp = self.client.get(
reverse('view_file_via_shared_dir', args=[self.fs.token]) + '?p=' + self.sub_file
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'share_access_validation.html')
resp = self.client.post(
reverse('view_file_via_shared_dir', args=[self.fs.token]) + '?p=' + self.sub_file)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'share_access_validation.html')
def test_view_file_via_shared_dir_with_wrong_password(self):
resp = self.client.post(
reverse('view_file_via_shared_dir', args=[self.fs.token]) + '?p=' + self.sub_file, {
'password': '<PASSWORD>'
}
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'share_access_validation.html')
self.assertContains(resp, 'Please enter a correct password')
<file_sep>/seahub/api2/authentication.py
import datetime
import logging
from rest_framework import status
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import APIException
import seaserv
from seahub.base.accounts import User
from seahub.constants import GUEST_USER
from seahub.api2.models import Token, TokenV2
from seahub.api2.utils import get_client_ip
from seahub.utils import within_time_range
try:
from seahub.settings import MULTI_TENANCY
except ImportError:
MULTI_TENANCY = False
logger = logging.getLogger(__name__)
HEADER_CLIENT_VERSION = 'HTTP_SEAFILE_CLEINT_VERSION'
HEADER_PLATFORM_VERSION = 'HTTP_SEAFILE_PLATFORM_VERSION'
class AuthenticationFailed(APIException):
status_code = status.HTTP_401_UNAUTHORIZED
default_detail = 'Incorrect authentication credentials.'
def __init__(self, detail=None):
self.detail = detail or self.default_detail
class TokenAuthentication(BaseAuthentication):
"""
Simple token based authentication.
Clients should authenticate by passing the token key in the "Authorization"
HTTP header, prepended with the string "Token ". For example:
Authorization: Token <PASSWORD>
A custom token model may be used, but must have the following properties.
* key -- The string identifying the token
* user -- The user to which the token belongs
"""
def authenticate(self, request):
auth = request.META.get('HTTP_AUTHORIZATION', '').split()
if not auth or auth[0].lower() != 'token':
return None
if len(auth) == 1:
msg = 'Invalid token header. No credentials provided.'
raise AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid token header. Token string should not contain spaces.'
raise AuthenticationFailed(msg)
key = auth[1]
ret = self.authenticate_v2(request, key)
if ret:
return ret
return self.authenticate_v1(request, key)
def _populate_user_permissions(self, user):
"""Disable some operations if ``user`` is a guest.
"""
if user.role == GUEST_USER:
user.permissions.can_add_repo = lambda: False
user.permissions.can_add_group = lambda: False
user.permissions.can_view_org = lambda: False
user.permissions.can_use_global_address_book = lambda: False
user.permissions.can_generate_shared_link = lambda: False
def authenticate_v1(self, request, key):
try:
token = Token.objects.get(key=key)
except Token.DoesNotExist:
raise AuthenticationFailed('Invalid token')
try:
user = User.objects.get(email=token.user)
except User.DoesNotExist:
raise AuthenticationFailed('User inactive or deleted')
if MULTI_TENANCY:
orgs = seaserv.get_orgs_by_user(token.user)
if orgs:
user.org = orgs[0]
self._populate_user_permissions(user)
if user.is_active:
return (user, token)
def authenticate_v2(self, request, key):
try:
token = TokenV2.objects.get(key=key)
except TokenV2.DoesNotExist:
return None # Continue authentication in token v1
try:
user = User.objects.get(email=token.user)
except User.DoesNotExist:
raise AuthenticationFailed('User inactive or deleted')
if MULTI_TENANCY:
orgs = seaserv.get_orgs_by_user(token.user)
if orgs:
user.org = orgs[0]
self._populate_user_permissions(user)
if user.is_active:
need_save = False
# We update the device's last_login_ip, client_version, platform_version if changed
ip = get_client_ip(request)
if ip and ip != token.last_login_ip:
token.last_login_ip = ip
need_save = True
client_version = request.META.get(HEADER_CLIENT_VERSION, '')
if client_version and client_version != token.client_version:
token.client_version = client_version
need_save = True
platform_version = request.META.get(HEADER_PLATFORM_VERSION, '')
if platform_version and platform_version != token.platform_version:
token.platform_version = platform_version
need_save = True
if not within_time_range(token.last_accessed, datetime.datetime.now(), 10 * 60):
# We only need 10min precision for the last_accessed field
need_save = True
if need_save:
try:
token.save()
except:
logger.exception('error when save token v2:')
return (user, token)
<file_sep>/static/scripts/common.js
//The build will inline common dependencies into this file.
//For any third party dependencies, like jQuery, place them in the lib folder.
//Configure loading modules from the lib directory,
//except for 'app' ones, which are in a sibling directory.
require.config({
// The shim config allows us to configure dependencies for
// scripts that do not call define() to register a module
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
}
},
paths: {
'jquery': 'lib/jquery',
'jquery.ui.core': 'lib/jquery.ui.core',
'jquery.ui.widget': 'lib/jquery.ui.widget.1.11.1',
'jquery.ui.progressbar': 'lib/jquery.ui.progressbar',
'jquery.ui.tabs': 'lib/jquery.ui.tabs',
'tmpl': 'lib/tmpl.min',
'jquery.iframe-transport': 'lib/jquery.iframe-transport.1.4',
'jquery.fileupload': 'lib/jquery.fileupload.5.42.1',
'jquery.fileupload-process': 'lib/jquery.fileupload.file-processing.1.3.0',
'jquery.fileupload-validate': 'lib/jquery.fileupload.validation.1.1.2',
'jquery.fileupload-ui': 'lib/jquery.fileupload.ui.9.6.0',
'jquery.magnific-popup': 'lib/jquery.magnific-popup',
simplemodal: 'lib/jquery.simplemodal',
jstree: 'lib/jstree.1.0',
select2: 'lib/select2-3.5.2',
underscore: 'lib/underscore',
backbone: 'lib/backbone',
text: 'lib/text'
}
});
define([
'jquery',
'underscore',
'text', // Workaround for r.js, otherwise text.js will not be included
'pinyin-by-unicode'
], function($, _, text, PinyinByUnicode) {
return {
INFO_TIMEOUT: 10000, // 10 secs for info msg
SUCCESS_TIMEOUT: 3000, // 3 secs for success msg
ERROR_TIMEOUT: 3000, // 3 secs for error msg
strChineseFirstPY: PinyinByUnicode.strChineseFirstPY,
getUrl: function(options) {
var siteRoot = app.config.siteRoot;
switch (options.name) {
case 'list_lib_dir': return siteRoot + 'ajax/lib/' + options.repo_id + '/dir/';
case 'star_file': return siteRoot + 'ajax/repo/' + options.repo_id + '/file/star/';
case 'unstar_file': return siteRoot + 'ajax/repo/' + options.repo_id + '/file/unstar/';
case 'del_dir': return siteRoot + 'ajax/repo/' + options.repo_id + '/dir/delete/';
case 'del_file': return siteRoot + 'ajax/repo/' + options.repo_id + '/file/delete/';
case 'rename_dir': return siteRoot + 'ajax/repo/' + options.repo_id + '/dir/rename/';
case 'rename_file': return siteRoot + 'ajax/repo/' + options.repo_id + '/file/rename/';
case 'mv_dir': return siteRoot + 'ajax/repo/' + options.repo_id + '/dir/mv/';
case 'cp_dir': return siteRoot + 'ajax/repo/' + options.repo_id + '/dir/cp/';
case 'mv_file': return siteRoot + 'ajax/repo/' + options.repo_id + '/file/mv/';
case 'cp_file': return siteRoot + 'ajax/repo/' + options.repo_id + '/file/cp/';
case 'lock_or_unlock_file': return siteRoot + 'api2/repos/' + options.repo_id + '/file/';
case 'new_dir': return siteRoot + 'ajax/repo/' + options.repo_id + '/dir/new/';
case 'new_file': return siteRoot + 'ajax/repo/' + options.repo_id + '/file/new/';
case 'del_dirents': return siteRoot + 'ajax/repo/' + options.repo_id + '/dirents/delete/';
case 'mv_dirents': return siteRoot + 'ajax/repo/' + options.repo_id + '/dirents/move/';
case 'cp_dirents': return siteRoot + 'ajax/repo/' + options.repo_id + '/dirents/copy/';
case 'get_file_op_url': return siteRoot + 'ajax/repo/' + options.repo_id + '/file_op_url/';
case 'get_file_uploaded_bytes': return siteRoot + 'ajax/repo/' + options.repo_id + '/get-file-uploaded-bytes/';
case 'get_dirents': return siteRoot + 'ajax/repo/' + options.repo_id + '/dirents/';
case 'repo_del': return siteRoot + 'ajax/repo/' + options.repo_id + '/remove/';
case 'sub_repo': return siteRoot + 'ajax/repo/' + options.repo_id + '/dir/sub_repo/';
case 'thumbnail_create': return siteRoot + 'thumbnail/' + options.repo_id + '/create/';
case 'get_my_unenc_repos': return siteRoot + 'ajax/my-unenc-repos/';
case 'unenc_rw_repos': return siteRoot + 'ajax/unenc-rw-repos/';
case 'get_cp_progress': return siteRoot + 'ajax/cp_progress/';
case 'cancel_cp': return siteRoot + 'ajax/cancel_cp/';
case 'ajax_repo_remove_share': return siteRoot + 'share/ajax/repo_remove_share/';
case 'get_user_contacts': return siteRoot + 'ajax/contacts/';
case 'get_shared_download_link': return siteRoot + 'share/ajax/get-download-link/';
case 'delete_shared_download_link': return siteRoot + 'share/ajax/link/remove/';
case 'send_shared_download_link': return siteRoot + 'share/link/send/';
case 'send_shared_upload_link': return siteRoot + 'share/upload_link/send/';
case 'delete_shared_upload_link': return siteRoot + 'share/ajax/upload_link/remove/';
case 'get_share_upload_link': return siteRoot + 'share/ajax/get-upload-link/';
case 'get_popup_notices': return siteRoot + 'ajax/get_popup_notices/';
case 'set_notices_seen': return siteRoot + 'ajax/set_notices_seen/';
case 'get_unseen_notices_num': return siteRoot + 'ajax/unseen-notices-count/';
case 'set_notice_seen_by_id': return siteRoot + 'ajax/set_notice_seen_by_id/';
case 'repo_set_password': return siteRoot + 'repo/set_password/';
case 'groups': return siteRoot + 'api/v2.1/groups/';
case 'group_repos': return siteRoot + 'api2/groups/' + options.group_id + '/repos/';
case 'group_basic_info': return siteRoot + 'ajax/group/' + options.group_id + '/basic-info/';
case 'toggle_group_modules': return siteRoot + 'ajax/group/' + options.group_id + '/toggle-modules/';
case 'toggle_personal_modules': return siteRoot + 'ajax/toggle-personal-modules/';
case 'ajax_unset_inner_pub_repo': return siteRoot + 'ajax/unset-inner-pub-repo/' + options.repo_id + '/';
case 'get_folder_perm_by_path': return siteRoot + 'ajax/repo/' + options.repo_id + '/get-folder-perm-by-path/';
case 'set_user_folder_perm': return siteRoot + 'ajax/repo/' + options.repo_id + '/set-user-folder-perm/';
case 'set_group_folder_perm': return siteRoot + 'ajax/repo/' + options.repo_id + '/set-group-folder-perm/';
case 'get_history_changes': return siteRoot + 'ajax/repo/' + options.repo_id + '/history/changes/';
case 'starred_files': return siteRoot + 'api2/starredfiles/';
case 'shared_repos': return siteRoot + 'api2/shared-repos/' + options.repo_id + '/';
case 'search_user': return siteRoot + 'api2/search-user/';
case 'dir_shared_items': return siteRoot + 'api2/repos/' + options.repo_id + '/dir/shared_items/';
case 'events': return siteRoot + 'api2/events/';
}
},
showConfirm: function(title, content, yesCallback) {
var $popup = $("#confirm-popup");
var $cont = $('#confirm-con');
var $yesBtn = $('#confirm-yes');
$cont.html('<h3>' + title + '</h3><p>' + content + '</p>');
$popup.modal({appendTo: '#main'});
$('#simplemodal-container').css({'height':'auto'});
$yesBtn.click(yesCallback);
},
closeModal: function() {
$.modal.close();
},
feedback: function(con, type, time) {
var time = time || 5000;
if ($('.messages').length > 0) {
$('.messages').html('<li class="' + type + '">' + con + '</li>');
} else {
var html = '<ul class="messages"><li class="' + type + '">' + con + '</li></ul>';
$('#main').append(html);
}
$('.messages').css({'left':($(window).width() - $('.messages').width())/2, 'top':10}).removeClass('hide');
setTimeout(function() { $('.messages').addClass('hide'); }, time);
},
showFormError: function(formid, error_msg) {
$("#" + formid + " .error").html(error_msg).removeClass('hide');
$("#simplemodal-container").css({'height':'auto'});
},
ajaxErrorHandler: function(xhr, textStatus, errorThrown) {
if (xhr.responseText) {
var parsed_resp = $.parseJSON(xhr.responseText);
this.feedback(parsed_resp.error||parsed_resp.error_msg, 'error');
} else {
this.feedback(gettext("Failed. Please check the network."), 'error');
}
},
// TODO: Change to jquery function like $.disableButtion(btn)
enableButton: function(btn) {
btn.removeAttr('disabled').removeClass('btn-disabled');
},
disableButton: function(btn) {
btn.attr('disabled', 'disabled').addClass('btn-disabled');
},
setCaretPos: function(inputor, pos) {
var range;
if (document.selection) {
range = inputor.createTextRange();
range.move("character", pos);
return range.select();
} else {
return inputor.setSelectionRange(pos, pos);
}
},
prepareApiCsrf: function() {
/* alias away the sync method */
Backbone._sync = Backbone.sync;
/* define a new sync method */
Backbone.sync = function(method, model, options) {
/* only need a token for non-get requests */
if (method == 'create' || method == 'update' || method == 'delete') {
// CSRF token value is in an embedded meta tag
// var csrfToken = $("meta[name='csrf_token']").attr('content');
var csrfToken = app.pageOptions.csrfToken;
options.beforeSend = function(xhr){
xhr.setRequestHeader('X-CSRFToken', csrfToken);
};
}
/* proxy the call to the old sync method */
return Backbone._sync(method, model, options);
};
},
prepareCSRFToken: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
},
ajaxPost: function(params) {
// usually used for form ajax post in modal popup
var _this = this,
form = params.form,
form_id = params.form_id,
post_url = params.post_url,
post_data = params.post_data,
after_op_success = params.after_op_success,
after_op_error;
var submit_btn = form.children('[type="submit"]');
this.disableButton(submit_btn);
if (params.after_op_error) {
after_op_error = params.after_op_error;
} else {
after_op_error = function(xhr, textStatus, errorThrown) {
var err;
if (xhr.responseText) {
err = $.parseJSON(xhr.responseText).error;
} else {
err = gettext("Failed. Please check the network.");
}
_this.showFormError(form_id, err);
_this.enableButton(submit_btn);
};
}
$.ajax({
url: post_url,
type: 'POST',
dataType: 'json',
beforeSend: this.prepareCSRFToken,
data: post_data,
success: after_op_success,
error: after_op_error
});
},
ajaxGet: function(params) {
var _this = this,
get_url = params.get_url,
data = params.data,
after_op_success = params.after_op_success,
after_op_error;
if (params.after_op_error) {
after_op_error = params.after_op_error;
} else {
after_op_error = function(xhr, textStatus, errorThrown) {
};
}
$.ajax({
url: get_url,
cache: false,
dataType: 'json',
data: data,
success: after_op_success,
error: after_op_error
});
},
HTMLescape: function(html) {
return document.createElement('div')
.appendChild(document.createTextNode(html))
.parentNode
.innerHTML;
},
pathJoin: function(array) {
var result = array[0];
for (var i = 1; i < array.length; i++) {
if (result[result.length-1] == '/' || array[i][0] == '/')
result += array[i];
else
result += '/' + array[i];
}
return result;
},
encodePath: function(path) {
// IE8 does not support 'map()'
/*
return path.split('/').map(function(e) {
return encodeURIComponent(e);
}).join('/');
*/
var path_arr = path.split('/'),
path_arr_ = [];
for (var i = 0, len = path_arr.length; i < len; i++) {
path_arr_.push(encodeURIComponent(path_arr[i]));
}
return path_arr_.join('/');
},
closePopup: function(e, popup, popup_switch) {
var target = e.target || event.srcElement;
if (!popup.hasClass('hide') && !popup.is(target) && !popup.find('*').is(target) && !popup_switch.is(target) && !popup_switch.find('*').is(target) ) {
popup.addClass('hide');
}
},
initAccountPopup: function() {
// TODO: need improving
$('#my-info').click(function() {
var popup = $('#user-info-popup');
popup.toggleClass('hide');
if (!popup.hasClass('hide')) {
var loading_tip = $('.loading-tip', popup),
space_traffic = $('#space-traffic');
loading_tip.show();
space_traffic.addClass('hide');
$('.error', popup).addClass('hide');
$.ajax({
url: space_traffic.data('url'),
dataType: 'json',
cache: false,
success: function(data) {
loading_tip.hide();
space_traffic.html(data['html']).removeClass('hide');
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.responseText) {
var error = $.parseJSON(xhr.responseText).error;
loading_tip.hide();
if ($('.error', popup).length == 0) {
loading_tip.after('<p class="error alc">' + error + '</p>');
} else {
$('.error', popup).removeClass('hide');
}
}
}
});
}
});
var _this = this;
$(document).click(function(e) {
_this.closePopup(e, $('#user-info-popup'), $('#my-info'));
});
},
initNoticePopup: function() {
var _this = this;
var msg_ct = $("#msg-count");
// for login page, and pages without 'header' such as 'file view' page.
if (msg_ct.length == 0) {
return false;
}
// original title
var orig_doc_title = document.title;
msg_ct.data('orig_doc_title', orig_doc_title); // for 'mark all read' in 'notice list' page
var reqUnreadNum = function() {
$.ajax({
url: _this.getUrl({name: 'get_unseen_notices_num'}),
dataType: 'json',
cache: false,
success: function(data) {
var count = data['count'],
num = $('.num', msg_ct);
num.html(count);
if (count > 0) {
num.removeClass('hide');
document.title = '(' + count + ')' + orig_doc_title;
} else {
num.addClass('hide');
document.title = orig_doc_title;
}
}
});
};
reqUnreadNum();
// request every 30s
setInterval(reqUnreadNum, 30*1000);
$('#notice-icon').click(function() {
var popup = $('#notice-popup');
popup.toggleClass('hide');
if (!popup.hasClass('hide')) {
$('.con', popup).css({'max-height':$(window).height() - $('#header').outerHeight() - $('.hd', popup).outerHeight() - 3});
var loading_tip = $('.loading-tip', popup),
notice_list = $('#notice-list');
notice_list.addClass('hide');
loading_tip.show();
$('.error', popup).addClass('hide');
$.ajax({
url: _this.getUrl({name: 'get_popup_notices'}),
dataType: 'json',
success: function(data) {
loading_tip.hide();
notice_list.html(data['notice_html']).removeClass('hide');
// set a notice to be read when <a> in it is clicked
$('.unread a', notice_list).click(function() {
var notice_id = $(this).parents('.unread').data('id');
var link_href = $(this).attr('href');
$.ajax({
url: _this.getUrl({name: 'set_notice_seen_by_id'}) + '?notice_id=' + encodeURIComponent(notice_id),
type: 'POST',
dataType: 'json',
beforeSend: _this.prepareCSRFToken,
success: function(data) {
location.href = link_href;
},
error: function() {
location.href = link_href;
}
});
return false;
});
$('.detail', notice_list).click(function() {
location.href = $('.brief a', $(this).parent()).attr('href');
});
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.responseText) {
var error = $.parseJSON(xhr.responseText).error;
loading_tip.hide();
if ($('.error', popup).length == 0) {
loading_tip.after('<p class="error alc">' + error + '</p>');
} else {
$('.error', popup).removeClass('hide');
}
}
}
});
}
});
$(window).resize(function() {
var popup = $('#notice-popup');
if (!popup.hasClass('hide')) {
$('.con', popup).css({'max-height':$(window).height() - $('#header').outerHeight() - $('.hd', popup).outerHeight() - 3});
}
});
$('#notice-popup .close').click(function() {
$('#notice-popup').addClass('hide');
if ($('#notice-list .unread').length > 0) {
// set all unread notice to be read
$.ajax({
url: _this.getUrl({name: 'set_notices_seen'}),
type: 'POST',
dataType: 'json',
beforeSend: _this.prepareCSRFToken,
success: function() {
$('.num', msg_ct).html(0).addClass('hide');
document.title = orig_doc_title;
}
});
}
});
$(document).click(function(e) {
_this.closePopup(e, $('#notice-popup'), $('#notice-icon'));
});
},
closeTopNoticeBar: function () {
if (!app.pageOptions.cur_note) {
return false;
}
var new_info_id = app.pageOptions.cur_note.id;
$('#info-bar').addClass('hide');
if (navigator.cookieEnabled) {
var date = new Date(),
cookies = document.cookie.split('; '),
info_id_exist = false;
date.setTime(date.getTime() + 14*24*60*60*1000);
new_info_id += '; expires=' + date.toGMTString() + '; path=' + app.config.siteRoot;
for (var i = 0, len = cookies.length; i < len; i++) {
if (cookies[i].split('=')[0] == 'info_id') {
info_id_exist = true;
document.cookie = 'info_id=' + cookies[i].split('=')[1] + new_info_id;
break;
}
}
if (!info_id_exist) {
document.cookie = 'info_id=' + new_info_id;
}
}
},
contactInputOptionsForSelect2: function() {
var _this = this;
return {
placeholder: gettext("Search users or enter emails"),
// with 'tags', the user can directly enter, not just select
// tags need `<input type="hidden" />`, not `<select>`
tags: [],
tokenSeparators: [",", " "],
minimumInputLength: 1, // input at least 1 character
formatInputTooShort: gettext("Please enter 1 or more character"),
formatNoMatches: gettext("No matches"),
formatSearching: gettext("Searching..."),
formatAjaxError: gettext("Loading failed"),
ajax: {
url: _this.getUrl({name: 'search_user'}),
dataType: 'json',
delay: 250,
cache: true,
data: function (params) {
return {
q: params
};
},
results: function (data) {
var user_list = [], users = data['users'];
for (var i = 0, len = users.length; i < len; i++) {
user_list.push({ // 'id' & 'text' are required by the plugin
"id": users[i].email,
// for search. both name & email can be searched.
// use ' '(space) to separate name & email
"text": users[i].name + ' ' + users[i].email,
"avatar": users[i].avatar,
"name": users[i].name
});
}
return {
results: user_list
};
}
},
// format items shown in the drop-down menu
formatResult: function(item) {
if (item.avatar) {
return item.avatar + '<span class="text ellipsis">' + _this.HTMLescape(item.name) + '<br />' + _this.HTMLescape(item.id) + '</span>';
} else {
return; // if no match, show nothing
}
},
// format selected item shown in the input
formatSelection: function(item) {
return _this.HTMLescape(item.name || item.id); // if no name, show the email, i.e., when directly input, show the email
},
escapeMarkup: function(m) { return m; }
}
},
// check if a file is an image
imageCheck: function (filename) {
// no file ext
if (filename.lastIndexOf('.') == -1) {
return false;
}
var file_ext = filename.substr(filename.lastIndexOf('.') + 1).toLowerCase();
var image_exts = ['gif', 'jpeg', 'jpg', 'png', 'ico', 'bmp'];
if (image_exts.indexOf(file_ext) != -1) {
return true;
} else {
return false;
}
},
gimpEditableCheck: function (filename) {
// no file ext
if (filename.lastIndexOf('.') == -1) {
return false;
}
var file_ext = filename.substr(filename.lastIndexOf('.') + 1).toLowerCase();
var image_exts = [
'avi',
'bmp',
'cel',
'fits',
'fli',
'gif',
'hrz',
'jpeg',
'jpg',
'miff',
'pcx',
'pix',
'png',
'pnm',
'ps',
'sgi',
'sunras',
'tga',
'tiff',
'xbm',
'xcf',
'xwd',
'xpm'
];
return image_exts.indexOf(file_ext) != -1;
},
compareTwoWord: function(a_name, b_name) {
// compare a_name and b_name at lower case
// if a_name >= b_name, return 1
// if a_name < b_name, return -1
var a_val, b_val,
a_uni = a_name.charCodeAt(0),
b_uni = b_name.charCodeAt(0),
strChineseFirstPY = this.strChineseFirstPY;
if ((19968 < a_uni && a_uni < 40869) && (19968 < b_uni && b_uni < 40869)) {
// both are chinese words
a_val = strChineseFirstPY.charAt(a_uni - 19968).toLowerCase();
b_val = strChineseFirstPY.charAt(b_uni - 19968).toLowerCase();
} else if ((19968 < a_uni && a_uni < 40869) && !(19968 < b_uni && b_uni < 40869)) {
// a is chinese and b is english
return 1;
} else if (!(19968 < a_uni && a_uni < 40869) && (19968 < b_uni && b_uni < 40869)) {
// a is english and b is chinese
return -1;
} else {
// both are english words
a_val = a_name.toLowerCase();
b_val = b_name.toLowerCase();
}
return a_val >= b_val ? 1 : -1;
},
fileSizeFormat: function(bytes, precision) {
var kilobyte = 1024;
var megabyte = kilobyte * 1024;
var gigabyte = megabyte * 1024;
var terabyte = gigabyte * 1024;
var precision = precision || 0;
if ((bytes >= 0) && (bytes < kilobyte)) {
return bytes + ' B';
} else if ((bytes >= kilobyte) && (bytes < megabyte)) {
return (bytes / kilobyte).toFixed(precision) + ' KB';
} else if ((bytes >= megabyte) && (bytes < gigabyte)) {
return (bytes / megabyte).toFixed(precision) + ' MB';
} else if ((bytes >= gigabyte) && (bytes < terabyte)) {
return (bytes / gigabyte).toFixed(precision) + ' GB';
} else if (bytes >= terabyte) {
return (bytes / terabyte).toFixed(precision) + ' TB';
} else {
return bytes + ' B';
}
},
isFilenameProblematicForSyncing: function (filename) {
return /[<>:"/\\|?*]/.test(filename);
},
getExportedLibraryName: function (repoId, callback) {
function _getLibraryNameFromListOfLibraries (libraries) {
for (var i = 0; i < libraries.length; i++) {
var library = libraries[i];
if (library.id === repoId) {
return library.name;
}
}
console.log("Couldn't find library name. How could that be possible?");
return false;
}
function _isLibraryNameRepeated (name, libraries) {
var num = 0;
for (var i = 0; i < libraries.length; i++) {
var library = libraries[i];
if (library.name === name) {
num++;
if (num > 1) {
return true;
}
}
}
return false;
}
var url = '/sync/api2/repos/';
$.ajax(url, {
success: function(libraries) {
if (libraries && libraries.length) {
var name = _getLibraryNameFromListOfLibraries(libraries);
if (!name) {
return callback(new Error('Can\'t get the name of the library'));
}
if (_isLibraryNameRepeated(name, libraries)) {
name += '-' + repoId.substr(0, 6);
}
return callback(null, name);
} else {
callback(new Error('Can\'t get the name of the library'));
}
},
error: function (err) {
callback(err);
}
});
}
}
});
<file_sep>/seahub/base/middleware.py
from django.core.cache import cache
import seaserv
from seahub.notifications.models import Notification
from seahub.notifications.utils import refresh_cache
try:
from seahub.settings import CLOUD_MODE
except ImportError:
CLOUD_MODE = False
try:
from seahub.settings import MULTI_TENANCY
except ImportError:
MULTI_TENANCY = False
class BaseMiddleware(object):
"""
Middleware that add organization, group info to user.
"""
def process_request(self, request):
username = request.user.username
request.user.org = None
if CLOUD_MODE:
request.cloud_mode = True
if MULTI_TENANCY:
orgs = seaserv.get_orgs_by_user(username)
if orgs:
request.user.org = orgs[0]
else:
request.cloud_mode = False
if CLOUD_MODE and request.user.org is not None:
org_id = request.user.org.org_id
request.user.joined_groups = seaserv.get_org_groups_by_user(
org_id, username)
else:
request.user.joined_groups = seaserv.get_personal_groups_by_user(
username)
return None
def process_response(self, request, response):
return response
class InfobarMiddleware(object):
"""Query info bar close status, and store into request."""
def get_from_db(self):
ret = Notification.objects.all().filter(primary=1)
refresh_cache()
return ret
def process_request(self, request):
topinfo_close = request.COOKIES.get('info_id', '')
cur_note = cache.get('CUR_TOPINFO') if cache.get('CUR_TOPINFO') else \
self.get_from_db()
if not cur_note:
request.cur_note = None
else:
if str(cur_note[0].id) in topinfo_close.split('_'):
request.cur_note = None
else:
request.cur_note = cur_note[0]
return None
def process_response(self, request, response):
return response
# from https://djangosnippets.org/snippets/218/
class ForceDefaultLanguageMiddleware(object):
"""
Ignore Accept-Language HTTP headers
This will force the I18N machinery to always choose settings.LANGUAGE_CODE
as the default initial language, unless another one is set via sessions or cookies
Should be installed *before* any middleware that checks request.META['HTTP_ACCEPT_LANGUAGE'],
namely django.middleware.locale.LocaleMiddleware
"""
def process_request(self, request):
if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
del request.META['HTTP_ACCEPT_LANGUAGE']
<file_sep>/seahub/base/templatetags/seahub_tags.py
# encoding: utf-8
import datetime as dt
from datetime import datetime
import re
import time
from django import template
from django.core.cache import cache
from django.utils.safestring import mark_safe
from django.utils import translation, formats
from django.utils.dateformat import DateFormat
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext, ungettext
from django.utils.translation import pgettext
from django.utils.html import escape
from seahub.base.accounts import User
from seahub.profile.models import Profile
from seahub.profile.settings import NICKNAME_CACHE_TIMEOUT, NICKNAME_CACHE_PREFIX, \
EMAIL_ID_CACHE_TIMEOUT, EMAIL_ID_CACHE_PREFIX
from seahub.cconvert import CConvert
from seahub.po import TRANSLATION_MAP
from seahub.shortcuts import get_first_object_or_none
from seahub.utils import normalize_cache_key, CMMT_DESC_PATT
from seahub.utils.html import avoid_wrapping
from seahub.utils.file_size import get_file_size_unit
register = template.Library()
@register.filter(name='tsstr_sec')
def tsstr_sec(value):
"""Turn a timestamp to string"""
try:
return datetime.fromtimestamp(value).strftime("%Y-%m-%d %H:%M:%S")
except:
return datetime.fromtimestamp(value/1000000).strftime("%Y-%m-%d %H:%M:%S")
@register.filter(name='tsstr_day')
def tsstr_day(value):
"""Turn a timestamp to string"""
try:
return datetime.fromtimestamp(value).strftime("%Y-%m-%d")
except:
return datetime.fromtimestamp(value/1000000).strftime("%Y-%m-%d")
# Supported file extensions and file icon name.
FILEEXT_ICON_MAP = {
# pdf file
'pdf' : 'pdf.png',
# document file
'doc' : 'word.png',
'docx' : 'word.png',
'ppt' : 'ppt.png',
'pptx' : 'ppt.png',
'xls' : 'excel.png',
'xlsx' : 'excel.png',
'txt' : 'txt.png',
'odt' : 'word.png',
'fodt' : 'word.png',
'ods' : 'excel.png',
'fods' : 'excel.png',
'odp' : 'ppt.png',
'fodp' : 'ppt.png',
# music file
'mp3' : 'music.png',
'oga' : 'music.png',
'ogg' : 'music.png',
'flac' : 'music.png',
'aac' : 'music.png',
'ac3' : 'music.png',
'wma' : 'music.png',
# picture file
'jpg' : 'pic.png',
'jpeg' : 'pic.png',
'png' : 'pic.png',
'svg' : 'pic.png',
'gif' : 'pic.png',
'bmp' : 'pic.png',
'ico' : 'pic.png',
# GIMP-editable picture file
'avi' : 'pic.png',
'cel' : 'pic.png',
'fits' : 'pic.png',
'fli' : 'pic.png',
'hrz' : 'pic.png',
'miff' : 'pic.png',
'pcx' : 'pic.png',
'pix' : 'pic.png',
'pnm' : 'pic.png',
'ps' : 'pic.png',
'sgi' : 'pic.png',
'sunras' : 'pic.png',
'tga' : 'pic.png',
'tiff' : 'pic.png',
'xbm' : 'pic.png',
'xcf' : 'pic.png',
'xpm' : 'pic.png',
'xwd' : 'pic.png',
# normal file and unknown file
'default' : 'file.png',
# for 192 pixel icon
# pdf file
'pdf-192' : 'pdf-192.png',
# document file
'doc-192' : 'word-192.png',
'docx-192' : 'word-192.png',
'ppt-192' : 'ppt-192.png',
'pptx-192' : 'ppt-192.png',
'xls-192' : 'excel-192.png',
'xlsx-192' : 'excel-192.png',
'txt-192' : 'txt-192.png',
'odt-192' : 'word-192.png',
'fodt-192' : 'word-192.png',
'ods-192' : 'excel-192.png',
'fods-192' : 'excel-192.png',
'odp-192' : 'ppt-192.png',
'fodp-192' : 'ppt-192.png',
# music file
'mp3-192' : 'music-192.png',
'oga-192' : 'music-192.png',
'ogg-192' : 'music-192.png',
'flac-192' : 'music-192.png',
'aac-192' : 'music-192.png',
'ac3-192' : 'music-192.png',
'wma-192' : 'music-192.png',
# picture file
'jpg-192' : 'pic-192.png',
'jpeg-192' : 'pic-192.png',
'png-192' : 'pic-192.png',
'svg-192' : 'pic-192.png',
'gif-192' : 'pic-192.png',
'bmp-192' : 'pic-192.png',
'ico-192' : 'pic-192.png',
# GIMP-editable picture-file
'avi-192' : 'pic-192.png',
'cel-192' : 'pic-192.png',
'fits-192' : 'pic-192.png',
'fli-192' : 'pic-192.png',
'hrz-192' : 'pic-192.png',
'miff-192' : 'pic-192.png',
'pcx-192' : 'pic-192.png',
'pix-192' : 'pic-192.png',
'pnm-192' : 'pic-192.png',
'ps-192' : 'pic-192.png',
'sgi-192' : 'pic-192.png',
'sunras-192' : 'pic-192.png',
'tga-192' : 'pic-192.png',
'tiff-192' : 'pic-192.png',
'xbm-192' : 'pic-192.png',
'xcf-192' : 'pic-192.png',
'xpm-192' : 'pic-192.png',
'xwd-192' : 'pic-192.png',
# normal file and unknown file
'default-192' : 'file-192.png',
}
@register.filter(name='file_icon_filter')
def file_icon_filter(value, size=None):
"""Get file icon according to the file postfix"""
if value.rfind('.') > 0:
file_ext = value.split('.')[-1].lower()
else:
file_ext = None
if file_ext and FILEEXT_ICON_MAP.has_key(file_ext):
if size == 192:
return FILEEXT_ICON_MAP.get(file_ext + '-192')
else:
return FILEEXT_ICON_MAP.get(file_ext)
else:
if size == 192:
return FILEEXT_ICON_MAP.get('default-192')
else:
return FILEEXT_ICON_MAP.get('default')
# This way of translation looks silly, but works well.
COMMIT_MSG_TRANSLATION_MAP = {
'Added' : _('Added'),
'Deleted' : _('Deleted'),
'Removed' : _('Removed'),
'Modified' : _('Modified'),
'Renamed' : _('Renamed'),
'Moved' : _('Moved'),
'Added directory' : _('Added directory'),
'Removed directory' : _('Removed directory'),
'Renamed directory' : _('Renamed directory'),
'Moved directory' : _('Moved directory'),
'Added or modified' : _('Added or modified'),
}
@register.filter(name='translate_commit_desc')
def translate_commit_desc(value):
"""Translate commit description."""
if value.startswith('Reverted repo'):
# Change 'repo' to 'library' in revert commit msg, since 'repo' is
# only used inside of seafile system.
value = value.replace('repo', 'library')
# Do nothing if current language is English.
if translation.get_language() == 'en':
return value
if value.startswith('Reverted library'):
return value.replace('Reverted library to status at', _('Reverted library to status at'))
elif value.startswith('Reverted file'):
def repl(matchobj):
return _('Reverted file "%(file)s" to status at %(time)s.') % \
{'file':matchobj.group(1), 'time':matchobj.group(2)}
return re.sub('Reverted file "(.*)" to status at (.*)', repl, value)
elif value.startswith('Recovered deleted directory'):
return value.replace('Recovered deleted directory', _('Recovered deleted directory'))
elif value.startswith('Changed library'):
return value.replace('Changed library name or description', _('Changed library name or description'))
elif value.startswith('Merged') or value.startswith('Auto merge'):
return _('Auto merge by seafile system')
else:
# Use regular expression to translate commit description.
# Commit description has two forms, e.g., 'Added "foo.txt" and 3 more files.' or 'Added "foo.txt".'
operations = '|'.join(COMMIT_MSG_TRANSLATION_MAP.keys())
patt = r'(%s) "(.*)"\s?(and ([0-9]+) more (files|directories))?' % operations
ret_list = []
for e in value.split('\n'):
if not e:
continue
m = re.match(patt, e)
if not m:
ret_list.append(e)
continue
op = m.group(1) # e.g., "Added"
op_trans = _(op)
file_name = m.group(2) # e.g., "foo.txt"
has_more = m.group(3) # e.g., "and 3 more files"
n_files = m.group(4) # e.g., "3"
more_type = m.group(5) # e.g., "files"
if has_more:
if translation.get_language() == 'zh-cn':
typ = u'文件' if more_type == 'files' else u'目录'
ret = op_trans + u' "' + file_name + u'"以及另外' + n_files + u'个' + typ + '.'
# elif translation.get_language() == 'ru':
# ret = ...
else:
ret = e
else:
ret = op_trans + u' "' + file_name + u'".'
ret_list.append(ret)
return '\n'.join(ret_list)
@register.filter(name='translate_commit_desc_escape')
def translate_commit_desc_escape(value):
"""Translate commit description."""
if value.startswith('Reverted repo'):
# Change 'repo' to 'library' in revert commit msg, since 'repo' is
# only used inside of seafile system.
value = value.replace('repo', 'library')
ret_list = []
# Do nothing if current language is English.
if translation.get_language() == 'en':
for e in value.split('\n'):
# if not match, this commit desc will not convert link, so
# escape it
ret = e if re.search(CMMT_DESC_PATT, e) else escape(e)
ret_list.append(ret)
return '\n'.join(ret_list)
if value.startswith('Reverted library'):
return_value = escape(value.replace('Reverted library to status at', _('Reverted library to status at')))
elif value.startswith('Reverted file'):
def repl(matchobj):
return _('Reverted file "%(file)s" to status at %(time)s.') % \
{'file':matchobj.group(1), 'time':matchobj.group(2)}
return_value = escape(re.sub('Reverted file "(.*)" to status at (.*)', repl, value))
elif value.startswith('Recovered deleted directory'):
return_value = escape(value.replace('Recovered deleted directory', _('Recovered deleted directory')))
elif value.startswith('Changed library'):
return_value = escape(value.replace('Changed library name or description', _('Changed library name or description')))
elif value.startswith('Merged') or value.startswith('Auto merge'):
return_value = escape(_('Auto merge by seafile system'))
else:
# Use regular expression to translate commit description.
# Commit description has two forms, e.g., 'Added "foo.txt" and 3 more files.' or 'Added "foo.txt".'
operations = '|'.join(COMMIT_MSG_TRANSLATION_MAP.keys())
patt = r'(%s) "(.*)"\s?(and ([0-9]+) more (files|directories))?' % operations
for e in value.split('\n'):
if not e:
continue
m = re.match(patt, e)
if not m:
# if not match, this commit desc will not convert link, so
# escape it
ret_list.append(escape(e))
continue
op = m.group(1) # e.g., "Added"
op_trans = _(op)
file_name = m.group(2) # e.g., "foo.txt"
has_more = m.group(3) # e.g., "and 3 more files"
n_files = m.group(4) # e.g., "3"
more_type = m.group(5) # e.g., "files"
if has_more:
if translation.get_language() == 'zh-cn':
typ = u'文件' if more_type == 'files' else u'目录'
ret = op_trans + u' "' + file_name + u'"以及另外' + n_files + u'个' + typ + '.'
# elif translation.get_language() == 'ru':
# ret = ...
else:
ret = e
else:
ret = op_trans + u' "' + file_name + u'".'
# if not match, this commit desc will not convert link, so
# escape it
ret = ret if re.search(CMMT_DESC_PATT, e) else escape(ret)
ret_list.append(ret)
return_value = '\n'.join(ret_list)
return return_value
@register.filter(name='translate_seahub_time')
def translate_seahub_time(value, autoescape=None):
if isinstance(value, int) or isinstance(value, long): # check whether value is int
try:
val = datetime.fromtimestamp(value) # convert timestamp to datetime
except ValueError as e:
return ""
elif isinstance(value, datetime):
val = value
else:
return value
translated_time = translate_seahub_time_str(val)
if autoescape:
translated_time = escape(translated_time)
timestring = val.isoformat()
titletime = DateFormat(val).format('r')
time_with_tag = '<time datetime="'+timestring+'" is="relative-time" title="'+titletime+'" >'+translated_time+'</time>'
return mark_safe(time_with_tag)
def translate_seahub_time_str(val):
"""Convert python datetime to human friendly format."""
now = datetime.now()
# If current time is less than `val`, that means clock at user machine is
# faster than server, in this case, we just set time description to `just now`
if now < val:
return _('Just now')
limit = 14 * 24 * 60 * 60 # Timestamp with in two weeks will be translated
delta = now - (val - dt.timedelta(0, 0, val.microsecond))
seconds = delta.seconds
days = delta.days
if days * 24 * 60 * 60 + seconds > limit:
return val.strftime("%Y-%m-%d")
elif days > 0:
ret = ungettext(
'%(days)d day ago',
'%(days)d days ago',
days ) % { 'days': days }
return ret
elif seconds > 60 * 60:
hours = seconds / 3600
ret = ungettext(
'%(hours)d hour ago',
'%(hours)d hours ago',
hours ) % { 'hours': hours }
return ret
elif seconds > 60:
minutes = seconds/60
ret = ungettext(
'%(minutes)d minute ago',
'%(minutes)d minutes ago',
minutes ) % { 'minutes': minutes }
return ret
elif seconds > 0:
ret = ungettext(
'%(seconds)d second ago',
'%(seconds)d seconds ago',
seconds ) % { 'seconds': seconds }
return ret
else:
return _('Just now')
@register.filter(name='email2nickname')
def email2nickname(value):
"""
Return nickname if it exists and it's not an empty string,
otherwise return short email.
"""
if not value:
return ''
key = normalize_cache_key(value, NICKNAME_CACHE_PREFIX)
cached_nickname = cache.get(key)
if cached_nickname and cached_nickname.strip():
return cached_nickname.strip()
profile = get_first_object_or_none(Profile.objects.filter(user=value))
if profile is not None and profile.nickname and profile.nickname.strip():
nickname = profile.nickname.strip()
else:
nickname = value.split('@')[0]
cache.set(key, nickname, NICKNAME_CACHE_TIMEOUT)
return nickname
@register.filter(name='email2id')
def email2id(value):
"""
Return the user id of an email. User id can be 0(ldap user),
positive(registered user) or negtive(unregistered user).
"""
if not value:
return -1
key = normalize_cache_key(value, EMAIL_ID_CACHE_PREFIX)
user_id = cache.get(key)
if user_id is None:
try:
user = User.objects.get(email=value)
user_id = user.id
except User.DoesNotExist:
user_id = -1
cache.set(key, user_id, EMAIL_ID_CACHE_TIMEOUT)
return user_id
@register.filter(name='id_or_email')
def id_or_email(value):
"""A wrapper to ``email2id``. Returns origin email if user id is 0(ldap user).
"""
uid = email2id(value)
return value if uid == 0 else uid
@register.filter(name='url_target_blank')
def url_target_blank(text):
return text.replace('<a ', '<a target="_blank" ')
url_target_blank.is_safe=True
at_pattern = re.compile(r'(@\w+)', flags=re.U)
@register.filter(name='find_at')
def find_at(text):
return at_pattern.sub(r'<span class="at">\1</span>', text)
find_at.is_safe=True
@register.filter(name='short_email')
def short_email(email):
"""
Return short email which is the string before '@'.
"""
idx = email.find('@')
if idx <= 0:
return email
else:
return email[:idx]
@register.filter(name='seahub_urlize')
def seahub_urlize(value, autoescape=None):
"""Converts URLs in plain text into clickable links."""
from seahub.base.utils import urlize
return mark_safe(urlize(value, nofollow=True, autoescape=autoescape))
seahub_urlize.is_safe=True
seahub_urlize.needs_autoescape = True
cc = CConvert()
cc.spliter = ''
@register.filter(name='char2pinyin')
def char2pinyin(value):
"""Convert Chinese character to pinyin."""
key = normalize_cache_key(value, 'CHAR2PINYIN_')
py = cache.get(key)
if not py:
py = cc.convert(value)
cache.set(key, py, 365 * 24 * 60 * 60)
return py
@register.filter(name='translate_permission')
def translate_permission(value):
if value == 'rw':
return _(u'Read-Write')
elif value == 'r':
return _(u'Read-Only')
else:
return ''
@register.filter(name='trim')
def trim(value, length):
if len(value) > length:
return value[:length-2] + '...'
else:
return value
@register.filter(name='strip_slash')
def strip_slash(value):
return value.strip('/')
@register.filter(is_safe=True)
def seahub_filesizeformat(bytes):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
"""
try:
bytes = float(bytes)
except (TypeError, ValueError, UnicodeDecodeError):
value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
return avoid_wrapping(value)
filesize_number_format = lambda value: formats.number_format(round(value, 1), 1)
KB = get_file_size_unit('KB')
MB = get_file_size_unit('MB')
GB = get_file_size_unit('GB')
TB = get_file_size_unit('TB')
PB = get_file_size_unit('PB')
if bytes < KB:
value = ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
elif bytes < MB:
value = ugettext("%s KB") % filesize_number_format(bytes / KB)
elif bytes < GB:
value = ugettext("%s MB") % filesize_number_format(bytes / MB)
elif bytes < TB:
value = ugettext("%s GB") % filesize_number_format(bytes / GB)
elif bytes < PB:
value = ugettext("%s TB") % filesize_number_format(bytes / TB)
else:
value = ugettext("%s PB") % filesize_number_format(bytes / PB)
return avoid_wrapping(value)
<file_sep>/thirdpart/rest_framework/utils/__init__.py
from django.utils.encoding import smart_unicode
from django.utils.xmlutils import SimplerXMLGenerator
from rest_framework.compat import StringIO
import re
import xml.etree.ElementTree as ET
# From xml2dict
class XML2Dict(object):
def __init__(self):
pass
def _parse_node(self, node):
node_tree = {}
# Save attrs and text, hope there will not be a child with same name
if node.text:
node_tree = node.text
for (k, v) in node.attrib.items():
k, v = self._namespace_split(k, v)
node_tree[k] = v
#Save childrens
for child in node.getchildren():
tag, tree = self._namespace_split(child.tag, self._parse_node(child))
if tag not in node_tree: # the first time, so store it in dict
node_tree[tag] = tree
continue
old = node_tree[tag]
if not isinstance(old, list):
node_tree.pop(tag)
node_tree[tag] = [old] # multi times, so change old dict to a list
node_tree[tag].append(tree) # add the new one
return node_tree
def _namespace_split(self, tag, value):
"""
Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients'
ns = http://cs.sfsu.edu/csc867/myscheduler
name = patients
"""
result = re.compile("\{(.*)\}(.*)").search(tag)
if result:
value.namespace, tag = result.groups()
return (tag, value)
def parse(self, file):
"""parse a xml file to a dict"""
f = open(file, 'r')
return self.fromstring(f.read())
def fromstring(self, s):
"""parse a string"""
t = ET.fromstring(s)
unused_root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t))
return root_tree
def xml2dict(input):
return XML2Dict().fromstring(input)
# Piston:
class XMLRenderer():
def _to_xml(self, xml, data):
if isinstance(data, (list, tuple)):
for item in data:
xml.startElement("list-item", {})
self._to_xml(xml, item)
xml.endElement("list-item")
elif isinstance(data, dict):
for key, value in data.iteritems():
xml.startElement(key, {})
self._to_xml(xml, value)
xml.endElement(key)
elif data is None:
# Don't output any value
pass
else:
xml.characters(smart_unicode(data))
def dict2xml(self, data):
stream = StringIO.StringIO()
xml = SimplerXMLGenerator(stream, "utf-8")
xml.startDocument()
xml.startElement("root", {})
self._to_xml(xml, data)
xml.endElement("root")
xml.endDocument()
return stream.getvalue()
def dict2xml(input):
return XMLRenderer().dict2xml(input)
<file_sep>/build.sh
set -x
set -u
set -o pipefail
apk update
apk add build-base gettext
npm install -g requirejs
cd /var/lib/seafile/scripts/seahub
export PYTHONPATH=$PWD/../seafile/lib64/python2.6/site-packages:$PWD/thirdpart:$PWD
export PATH=$PATH:thirdpart/Django-1.5.12-py2.6.egg/django/bin
export CCNET_CONF_DIR=$PWD/../../conf
export SEAFILE_CONF_DIR="$CCNET_CONF_DIR"
make dist
<file_sep>/static/scripts/app/views/fileupload.js
define([
'common',
'backbone',
'jquery.fileupload-ui'
], function(Common, Backbone, FileUpload) {
window.locale = {
"fileupload": {
"errors": {
"maxFileSize": gettext("File is too big"),
"minFileSize": gettext("File is too small"),
"acceptFileTypes": gettext("Filetype not allowed"),
"maxNumberOfFiles": gettext("Max number of files exceeded"),
"uploadedBytes": gettext("Uploaded bytes exceed file size"),
"emptyResult": gettext("Empty file upload result")
},
"error": gettext("Error"),
"uploaded": gettext("uploaded"),
"canceled": gettext("canceled"),
"start": gettext("Start"),
"cancel": gettext("Cancel"),
"destroy": gettext("Delete")
}
};
var FileUploadView = Backbone.View.extend({
el: $('#upload-file-dialog'),
fileupdateConfirmTemplate: _.template($("#fileupdate-confirm-template").html()),
initialize: function (options) {
var dirView = this.dirView = options.dirView;
var dirents = dirView.dir;
var popup = this.$el.addClass('fixed-upload-file-dialog');
this.popup_height = '200px';
var $fu_status = $('.status', popup),
$total_progress = $('.total-progress', popup),
cancel_all_btn = $('.fileupload-buttonbar .cancel', popup),
close_icon = $('.close', popup),
saving_tip = $('.saving-tip', popup);
var fu_status = {
'uploading': gettext("File Uploading..."),
'complete': gettext("File Upload complete"),
'canceled': gettext("File Upload canceled"),
'failed': gettext("File Upload failed")
};
var uploaded_files = [];
var updated_files = [];
var enable_upload_folder = app.pageOptions.enable_upload_folder;
var enable_resumable_fileupload = app.pageOptions.enable_resumable_fileupload;
var new_dir_names = [];
var dirs_to_update = [];
var _this = this;
popup.fileupload({
paramName: 'file',
// customize it for 'done'
getFilesFromResponse: function (data) {
if (data.result) {
return data.result;
}
},
autoUpload:true,
maxNumberOfFiles: 500,
sequentialUploads: true
})
.bind('fileuploadadd', function(e, data) {
// for drag & drop
if (!dirView.$el.is(':visible')) {
return false;
}
if (dirents.user_perm && dirents.user_perm != 'rw') {
return false;
}
popup.removeClass('hide');
cancel_all_btn.removeClass('hide');
close_icon.addClass('hide');
var path = dirents.path;
popup.fileupload('option', {
'formData': {
'parent_dir': path == '/' ? path : path + '/'
},
'maxChunkSize': undefined,
'uploadedBytes': undefined
});
if (!enable_upload_folder) {
return;
}
// hide the upload menu
var menu = dirView.$('#upload-menu');
if (!menu.hasClass('hide')) {
menu.find('.item').removeAttr('style')
.end().addClass('hide');
}
var file = data.files[0];
// add folder by clicking 'Upload Folder'
if (file.name == '.') { // a subdirectory will be shown as '.'
data.files.shift();
return;
}
if (file.webkitRelativePath) {
file.relative_path = file.webkitRelativePath;
}
// add folder by drag & drop
if (file.relativePath) {
file.relative_path = file.relativePath + file.name;
}
})
.bind('fileuploadstart', function() {
$fu_status.html(fu_status.uploading);
})
.bind('fileuploadsubmit', function(e, data) {
if (data.files.length == 0) {
return false;
}
var file = data.files[0];
if (file.error) {
return false;
}
var parser = document.createElement('a');
parser.href = document.URL;
var hostname = parser.hostname;
var upload_file = function() {
$.ajax({
url: Common.getUrl({
name: 'get_file_op_url',
repo_id: dirents.repo_id
}),
data: {
'op_type': 'upload',
'path': dirents.path,
'hostname': hostname
},
cache: false,
dataType: 'json',
success: function(ret) {
if (enable_upload_folder && file.relative_path) { // 'add folder'
var file_path = file.relative_path,
r_path = file_path.substring(0, file_path.lastIndexOf('/') + 1),
formData = popup.fileupload('option', 'formData');
formData.relative_path = r_path;
popup.fileupload('option', {
'formData': formData
});
data.url = ret['url'];
data.jqXHR = popup.fileupload('send', data);
} else {
var block_size = 1024 * 1024;
if (enable_resumable_fileupload &&
file.size && file.size > block_size) {
popup.fileupload('option', 'maxChunkSize', block_size);
$.ajax({
url: Common.getUrl({
name: 'get_file_uploaded_bytes',
repo_id: dirents.repo_id
}),
data: {
'parent_dir': dirents.path,
'file_name': file.name,
'hostname': hostname
},
cache: false,
dataType: 'json',
success: function(file_uploaded_data) {
popup.fileupload('option', 'uploadedBytes', file_uploaded_data.uploadedBytes);
data.url = ret['url'];
data.jqXHR = popup.fileupload('send', data);
}
});
} else {
data.url = ret['url'];
data.jqXHR = popup.fileupload('send', data);
}
}
},
error: function() {
file.error = gettext("Failed to get upload url");
}
});
};
if (file.relative_path || data.originalFiles.length > 1) { // 'add folder' or upload more than 1 file once
upload_file();
return false;
}
var update_file = function() {
$.ajax({
url: Common.getUrl({
name: 'get_file_op_url',
repo_id: dirents.repo_id
}),
data: {
'op_type': 'update',
'path': dirents.path,
'hostname': hostname
},
cache: false,
dataType: 'json',
success: function(ret) {
var formData = popup.fileupload('option', 'formData');
formData.target_file = formData.parent_dir + file.name;
popup.fileupload('option', 'formData', formData);
file.to_update = true;
data.url = ret['url'];
data.jqXHR = popup.fileupload('send', data);
},
error: function() {
file.error = gettext("Failed to get update url");
}
});
};
var files = dirents.where({'is_file': true}),
file_names = [];
$(files).each(function() {
file_names.push(this.get('obj_name'));
});
if (file_names.indexOf(file.name) != -1) { // file with the same name already exists in the dir
var confirm_title = gettext("Replace file {filename}?")
.replace('{filename}', '<span class="op-target">' + Common.HTMLescape(file.name) + '</span>');
var confirm_popup = $(_this.fileupdateConfirmTemplate({
title: confirm_title
}));
confirm_popup.modal({
onClose: function() {
$.modal.close();
if (file.choose_to_update) {
update_file();
} else if (file.choose_to_upload) {
upload_file();
} else {
data.jqXHR = popup.fileupload('send', data);
data.jqXHR.abort();
}
}
});
$('#simplemodal-container').css({'height':'auto'});
$('.yes', confirm_popup).click(function() {
var selected_file = dirents.findWhere({'obj_name': file.name});
if (selected_file.get('is_locked')) {
if (selected_file.get('locked_by_me')) {
file.choose_to_update = true;
$.modal.close();
} else {
$('.error', confirm_popup).html(gettext("File is locked")).removeClass('hide');
Common.disableButton($(this));
}
} else {
file.choose_to_update = true;
$.modal.close();
}
});
$('.no', confirm_popup).click(function() {
file.choose_to_upload = true;
$.modal.close();
});
} else {
upload_file();
}
return false;
})
.bind('fileuploadprogressall', function (e, data) {
$total_progress.html(parseInt(data.loaded / data.total * 100, 10) + '% ' +
'<span style="font-size:14px;color:#555;">(' +
$(this).data('blueimp-fileupload')._formatBitrate(data.bitrate) +
')</span>').removeClass('hide');
if (data.loaded > 0 && data.loaded == data.total) {
saving_tip.show();
}
})
.bind('fileuploaddone', function(e, data) {
if (data.textStatus != 'success') {
return;
}
var file = data.files[0];
var file_path = file.relative_path;
var file_uploaded = data.result[0]; // 'id', 'name', 'size'
// for 'template_download' render
file_uploaded.uploaded = true;
if (file_path) {
file_uploaded.relative_path = file_path.substring(0, file_path.lastIndexOf('/') + 1) + file_uploaded.name;
}
var path = dirents.path;
path = path == '/' ? path : path + '/';
if (data.formData.parent_dir != path) {
return;
}
if (!file_path) {
if (!file.to_update) {
uploaded_files.push(file_uploaded);
} else {
updated_files.push(file_uploaded);
}
return;
}
if (!enable_upload_folder) {
return;
}
// for 'add folder'
var dir_name = file_path.substring(0, file_path.indexOf('/'));
var dir = dirents.where({'is_dir': true, 'obj_name': dir_name});
if (dir.length > 0) { // 0 or 1
if (dirs_to_update.indexOf(dir_name) == -1) {
dirs_to_update.push(dir_name);
}
} else {
if (new_dir_names.indexOf(dir_name) == -1) {
new_dir_names.push(dir_name);
}
}
})
.bind('fileuploadstop', function () {
cancel_all_btn.addClass('hide');
close_icon.removeClass('hide');
var path = dirents.path;
path = path == '/' ? path : path + '/';
if (popup.fileupload('option','formData').parent_dir != path) {
return;
}
var now = parseInt(new Date().getTime()/1000);
if (uploaded_files.length > 0) {
$(uploaded_files).each(function(index, file) {
var new_dirent = dirents.add({
'is_file': true,
'is_img': Common.imageCheck(file.name),
'is_gimp_editable': Common.gimpEditableCheck(file.name),
'obj_name': file.name,
'last_modified': now,
'file_size': Common.fileSizeFormat(file.size, 1),
'obj_id': file.id,
'file_icon': 'file.png',
'perm': 'rw',
'last_update': gettext("Just now"),
'starred': false
}, {silent: true});
dirView.addNewFile(new_dirent);
});
uploaded_files = [];
}
if (new_dir_names.length > 0) {
$(new_dir_names).each(function(index, new_name) {
var new_dirent = dirents.add({
'is_dir': true,
'obj_name': new_name,
'perm': 'rw',
'last_modified': now,
'last_update': gettext("Just now"),
'p_dpath': path + new_name
}, {silent: true});
dirView.addNewDir(new_dirent);
});
new_dir_names = [];
}
if (dirs_to_update.length > 0) {
$(dirs_to_update).each(function(index, dir_name) {
var dir_to_update = dirents.where({'is_dir':true, 'obj_name':dir_name});
dir_to_update[0].set({
'last_modified': now,
'last_update': gettext("Just now")
});
});
dirs_to_update = [];
}
if (updated_files.length > 0) {
$(updated_files).each(function(index, item) {
var file_to_update = dirents.where({'is_file':true, 'obj_name':item.name});
file_to_update[0].set({
'obj_id': item.id,
'file_size': Common.fileSizeFormat(item.size, 1),
'last_modified': now,
'last_update': gettext("Just now")
});
});
updated_files = [];
}
})
// after tpl has rendered
.bind('fileuploadcompleted', function() { // 'done'
if ($('.files .cancel', popup).length == 0) {
saving_tip.hide();
$total_progress.addClass('hide');
$fu_status.html(fu_status.complete);
}
})
.bind('fileuploadfailed', function(e, data) { // 'fail'
if ($('.files .cancel', popup).length == 0) {
cancel_all_btn.addClass('hide');
close_icon.removeClass('hide');
$total_progress.addClass('hide');
saving_tip.hide();
if (data.errorThrown == 'abort') { // 'cancel'
$fu_status.html(fu_status.canceled);
} else { // 'error'
$fu_status.html(fu_status.failed);
}
}
});
var max_upload_file_size = app.pageOptions.max_upload_file_size;
if (max_upload_file_size) {
popup.fileupload(
'option',
'maxFileSize',
max_upload_file_size);
}
// Enable iframe cross-domain access via redirect option:
popup.fileupload(
'option',
'redirect',
window.location.href.replace(/\/repo\/[-a-z0-9]{36}\/.*/, app.config.mediaUrl + 'cors/result.html?%s')
);
$(document).click(function(e) {
var target = e.target || event.srcElement;
var closePopup = function(popup, popup_switch) {
if (!popup.hasClass('hide') && !popup.is(target) && !popup.find('*').is(target) && !popup_switch.is(target) && !popup_switch.find('*').is(target) ) {
popup.addClass('hide');
}
};
closePopup(dirView.$('#upload-menu'), dirView.$('#upload-file'));
});
},
events: {
'click .fold-switch': 'foldAndUnfoldPopup',
'click .close': 'closePopup'
},
foldAndUnfoldPopup : function () {
var popup = this.$el;
var full_ht = parseInt(this.popup_height);
var main_con = $('.fileupload-buttonbar, .table', popup);
if (popup.height() == full_ht) {
popup.height($('.hd', popup).outerHeight(true));
main_con.addClass('hide');
} else {
popup.height(full_ht);
main_con.removeClass('hide');
}
},
closePopup: function () {
var popup = this.$el;
popup.addClass('hide');
$('.files', popup).empty();
},
setFileInput: function () {
var dirView = this.dirView,
dir = dirView.dir;
var popup = this.$el;
if (dir.user_perm && dir.user_perm == 'rw') {
popup.fileupload(
'option',
'fileInput',
dirView.$('#upload-file input'));
}
if (!app.pageOptions.enable_upload_folder) {
return;
}
var upload_btn = dirView.$('#upload-file'),
upload_menu = dirView.$('#upload-menu');
if (dir.user_perm && dir.user_perm == 'rw' &&
'webkitdirectory' in $('input[type="file"]', upload_btn)[0]) {
upload_btn.find('input').remove().end().addClass('cspt');
$('.item', upload_menu).click(function() {
popup.fileupload(
'option',
'fileInput',
$('input[type="file"]', $(this))
);
})
.hover(
function() {
$(this).css({'background':'#f3f3f3'});
},
function() {
$(this).css({'background':'transparent'});
}
);
upload_btn.click(function () {
upload_menu.toggleClass('hide');
upload_menu.css({
'left': upload_btn.position().left,
'top': parseInt(dirView.$('.repo-op').css('padding-top')) + upload_btn.outerHeight(true)
});
});
}
}
});
return FileUploadView;
});
<file_sep>/seahub/templates/upload_file_error.html
{% extends base_template %}
{% load seahub_tags i18n %}
{% block main_panel %}
<div class="narrow-panel">
<h3>{% trans "Upload file" %} {% if filename %} {{ filename }} {% endif %} {% trans "to" %}
{% for name, link in zipped %}
<a href="{% url 'view_common_lib_dir' repo.id link|urlencode|strip_slash %}">{{ name }}</a> /
{% endfor %}
{% trans "error: " %}
</h3>
<p>{{ err_msg }}</p>
</div>
{% endblock %}
<file_sep>/static/scripts/app/views/organization-repo.js
define([
'jquery',
'underscore',
'backbone',
'common'
], function($, _, Backbone, Common) {
'use strict';
var OrganizationRepoView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#organization-repo-tmpl').html()),
initialize: function() {
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
events: {
'mouseenter': 'highlight',
'mouseleave': 'rmHighlight',
'click .cancel-share': 'removeShare'
},
highlight: function() {
this.$el.addClass('hl').find('.op-icon').removeClass('vh');
},
rmHighlight: function() {
this.$el.removeClass('hl').find('.op-icon').addClass('vh');
},
removeShare: function() {
var el = this.$el;
var lib_name = this.model.get('name');
$.ajax({
url: Common.getUrl({
name: 'ajax_unset_inner_pub_repo',
repo_id: this.model.get('id')
}),
type: 'POST',
data: {
'permission': this.model.get('permission')
},
beforeSend: Common.prepareCSRFToken,
dataType: 'json',
success: function () {
el.remove();
var msg = gettext('Successfully unshared {placeholder}').replace('{placeholder}', '<span class="op-target">' + Common.HTMLescape(lib_name) + '</span>');
Common.feedback(msg, 'success', Common.SUCCESS_TIMOUT);
},
error: function(xhr) {
Common.ajaxErrorHandler(xhr);
}
});
}
});
return OrganizationRepoView;
});
<file_sep>/tests/seahub/views/test_view_lib_file.py
import requests
from mock import Mock
from mock import patch
from django.core.urlresolvers import reverse
from seahub.test_utils import BaseTestCase
class ViewLibFileTest(BaseTestCase):
def setUp(self):
# self.login_as(self.user)
pass
def tearDown(self):
self.remove_repo(self.repo.id)
def test_repo_not_exist(self):
self.login_as(self.user)
url = reverse('view_lib_file', args=[
'4a3d8cbe-6c79-4dad-8234-76b000000000', '/'])
resp = self.client.get(url)
self.assertEqual(404, resp.status_code)
def test_file_not_exist(self):
self.login_as(self.user)
url = reverse('view_lib_file', args=[
self.repo.id, '/some_random_file'])
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'error.html')
def test_file_permission_error(self):
self.login_as(self.admin)
url = reverse('view_lib_file', args=[
self.repo.id, self.file])
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'permission_error.html')
def test_invalid_file_extension(self):
self.login_as(self.user)
file_path = self.create_file(repo_id=self.repo.id, parent_dir='/',
filename="foo.___", username=self.user.email)
url = reverse('view_lib_file', args=[
self.repo.id, file_path])
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_file_base.html')
assert resp.context['err'] == 'invalid extension'
@patch('seahub.views.file.FILE_PREVIEW_MAX_SIZE', -1)
def test_file_size_exceeds_limit(self):
self.login_as(self.user)
url = reverse('view_lib_file', args=[
self.repo.id, self.file])
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_file_base.html')
assert resp.context['err'] == 'File size surpasses -1 bytes, can not be opened online.'
def test_text_file(self):
self.login_as(self.user)
url = reverse('view_lib_file', args=[self.repo.id, self.file])
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_file_text.html')
assert resp.context['filetype'].lower() == 'text'
assert resp.context['err'] == ''
assert resp.context['file_content'] == ''
assert resp.context['encoding'] == 'utf-8'
# token for text file is one time only
raw_path = resp.context['raw_path']
r = requests.get(raw_path)
self.assertEqual(400, r.status_code)
def test_ms_doc_without_office_converter(self):
self.login_as(self.user)
file_path = self.create_file(repo_id=self.repo.id, parent_dir='/',
filename="foo.doc", username=self.user.email)
url = reverse('view_lib_file', args=[self.repo.id, file_path])
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_file_unknown.html')
assert resp.context['filetype'].lower() == 'unknown'
assert resp.context['err'] == ''
# token for doc file is one time only
raw_path = resp.context['raw_path']
r = requests.get(raw_path)
self.assertEqual(200, r.status_code)
r = requests.get(raw_path)
self.assertEqual(400, r.status_code)
# @patch('seahub.views.file.HAS_OFFICE_CONVERTER', True)
# @patch('seahub.views.file.can_preview_file')
# @patch('seahub.views.file.prepare_converted_html', create=True)
# def test_ms_doc_with_office_converter(self, mock_prepare_converted_html,
# mock_can_preview_file):
# mock_prepare_converted_html.return_value = None
# mock_can_preview_file.return_value = (True, None)
# self.login_as(self.user)
# file_path = self.create_file(repo_id=self.repo.id, parent_dir='/',
# filename="foo.doc", username=self.user.email)
# url = reverse('view_lib_file', args=[self.repo.id, file_path])
# resp = self.client.get(url)
# self.assertEqual(200, resp.status_code)
# self.assertTemplateUsed(resp, 'view_file_document.html')
# assert resp.context['filetype'].lower() == 'document'
# assert resp.context['err'] == ''
# # token for doc file is one time only
# raw_path = resp.context['raw_path']
# r = requests.get(raw_path)
# self.assertEqual(200, r.status_code)
# r = requests.get(raw_path)
# self.assertEqual(400, r.status_code)
@patch('seahub.views.file.get_file_size')
def test_opendoc(self, mock_get_file_size):
mock_get_file_size.return_value = 1
self.login_as(self.user)
file_path = self.create_file(repo_id=self.repo.id, parent_dir='/',
filename="foo.odt", username=self.user.email)
url = reverse('view_lib_file', args=[self.repo.id, file_path])
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_file_opendocument.html')
assert resp.context['filetype'].lower() == 'opendocument'
assert resp.context['err'] == ''
# token for doc file is one time only
raw_path = resp.context['raw_path']
r = requests.get(raw_path)
self.assertEqual(200, r.status_code)
r = requests.get(raw_path)
self.assertEqual(400, r.status_code)
def test_pdf_file(self):
self.login_as(self.user)
file_path = self.create_file(repo_id=self.repo.id, parent_dir='/',
filename="foo.pdf", username=self.user.email)
url = reverse('view_lib_file', args=[self.repo.id, file_path])
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_file_pdf.html')
assert resp.context['filetype'].lower() == 'pdf'
assert resp.context['err'] == ''
# token for doc file is one time only
raw_path = resp.context['raw_path']
r = requests.get(raw_path)
self.assertEqual(200, r.status_code)
r = requests.get(raw_path)
self.assertEqual(400, r.status_code)
def test_img_file(self):
self.login_as(self.user)
file_path = self.create_file(repo_id=self.repo.id, parent_dir='/',
filename="foo.jpg", username=self.user.email)
self.create_file(repo_id=self.repo.id, parent_dir='/',
filename="foo2.jpg", username=self.user.email)
url = reverse('view_lib_file', args=[self.repo.id, file_path])
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_file_image.html')
assert resp.context['filetype'].lower() == 'image'
assert resp.context['err'] == ''
assert resp.context['img_next'] == '/foo2.jpg'
assert resp.context['img_prev'] is None
# token for doc file is one time only
raw_path = resp.context['raw_path']
r = requests.get(raw_path)
self.assertEqual(200, r.status_code)
r = requests.get(raw_path)
self.assertEqual(400, r.status_code)
def test_video_file(self):
self.login_as(self.user)
file_path = self.create_file(repo_id=self.repo.id, parent_dir='/',
filename="foo.mp4", username=self.user.email)
url = reverse('view_lib_file', args=[self.repo.id, file_path])
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'view_file_video.html')
assert resp.context['filetype'].lower() == 'video'
assert resp.context['err'] == ''
raw_path = resp.context['raw_path']
for _ in range(3): # token for video is not one time only
r = requests.get(raw_path)
self.assertEqual(200, r.status_code)
def test_can_download(self):
self.login_as(self.user)
url = reverse('view_lib_file', args=[self.repo.id, self.file]) + '?dl=1'
resp = self.client.get(url)
self.assertEqual(302, resp.status_code)
assert '8082/files/' in resp.get('location')
resp = requests.request('GET', resp.get('location'))
cont_disp = resp.headers['content-disposition']
assert 'inline' not in cont_disp
assert 'attachment' in cont_disp
def test_can_view_raw(self):
self.login_as(self.user)
url = reverse('view_lib_file', args=[self.repo.id, self.file]) + '?raw=1'
resp = self.client.get(url)
self.assertEqual(302, resp.status_code)
assert '8082/files/' in resp.get('location')
resp = requests.request('GET', resp.get('location'))
cont_disp = resp.headers['content-disposition']
assert 'inline' in cont_disp
assert 'attachment' not in cont_disp
<file_sep>/seahub/share/views.py
# encoding: utf-8
import os
import logging
import json
from dateutil.relativedelta import relativedelta
from constance import config
from django.core.urlresolvers import reverse
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect, Http404, \
HttpResponseBadRequest
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST
from django.contrib import messages
from django.utils import timezone
from django.utils.html import escape
# from django.contrib.sites.models import RequestSite
import seaserv
from seaserv import seafile_api
from seaserv import ccnet_threaded_rpc, is_org_group, \
get_org_id_by_group, del_org_group_repo, unset_inner_pub_repo
from pysearpc import SearpcError
from seahub.share.forms import RepoShareForm, FileLinkShareForm, \
UploadLinkShareForm
from seahub.share.models import FileShare, PrivateFileDirShare, \
UploadLinkShare, OrgFileShare
from seahub.share.signals import share_repo_to_user_successful
# from settings import ANONYMOUS_SHARE_COOKIE_TIMEOUT
# from tokens import anon_share_token_generator
from seahub.auth.decorators import login_required, login_required_ajax
from seahub.base.accounts import User
from seahub.base.decorators import user_mods_check, require_POST
from seahub.contacts.models import Contact
from seahub.contacts.signals import mail_sended
from seahub.signals import share_file_to_user_successful
from seahub.views import is_registered_user, check_repo_access_permission, \
check_folder_permission
from seahub.utils import render_permission_error, string2list, render_error, \
gen_token, gen_shared_link, gen_shared_upload_link, gen_dir_share_link, \
gen_file_share_link, IS_EMAIL_CONFIGURED, check_filename_with_rename, \
is_valid_username, send_html_email, is_org_context, normalize_file_path, \
normalize_dir_path, send_perm_audit_msg, get_origin_repo_info
from seahub.settings import SITE_ROOT, REPLACE_FROM_EMAIL, ADD_REPLY_TO_HEADER
# Get an instance of a logger
logger = logging.getLogger(__name__)
########## rpc wrapper
def is_org_repo_owner(username, repo_id):
owner = seaserv.seafserv_threaded_rpc.get_org_repo_owner(repo_id)
return True if owner == username else False
def get_org_group_repos_by_owner(org_id, username):
return seaserv.seafserv_threaded_rpc.get_org_group_repos_by_owner(org_id,
username)
def list_org_inner_pub_repos_by_owner(org_id, username):
return seaserv.seafserv_threaded_rpc.list_org_inner_pub_repos_by_owner(
org_id, username)
def org_share_repo(org_id, repo_id, from_user, to_user, permission):
return seaserv.seafserv_threaded_rpc.org_add_share(org_id, repo_id,
from_user, to_user,
permission)
def org_remove_share(org_id, repo_id, from_user, to_user):
return seaserv.seafserv_threaded_rpc.org_remove_share(org_id, repo_id,
from_user, to_user)
########## functions
def share_to_public(request, repo, permission):
"""Share repo to public with given permission.
"""
try:
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.set_org_inner_pub_repo(
org_id, repo.id, permission)
elif request.cloud_mode:
return # no share to public in cloud mode
else:
seafile_api.add_inner_pub_repo(repo.id, permission)
except Exception, e:
logger.error(e)
messages.error(request, _(u'Failed to share to all members, please try again later.'))
else:
msg = _(u'Shared to all members successfully, go check it at <a href="%s">Shares</a>.') % \
(reverse('share_admin'))
messages.success(request, msg, extra_tags='safe')
def share_to_group(request, repo, group, permission):
"""Share repo to group with given permission.
"""
repo_id = repo.id
group_id = group.id
from_user = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
group_repo_ids = seafile_api.get_org_group_repoids(org_id, group.id)
else:
group_repo_ids = seafile_api.get_group_repoids(group.id)
if repo.id in group_repo_ids:
return False
try:
if is_org_context(request):
org_id = request.user.org.org_id
seafile_api.add_org_group_repo(repo_id, org_id, group_id,
from_user, permission)
else:
seafile_api.set_group_repo(repo_id, group_id, from_user,
permission)
return True
except Exception, e:
logger.error(e)
return False
def share_to_user(request, repo, to_user, permission):
"""Share repo to a user with given permission.
"""
repo_id = repo.id
from_user = request.user.username
if from_user == to_user:
return False
# permission check
if is_org_context(request):
org_id = request.user.org.org_id
if not seaserv.ccnet_threaded_rpc.org_user_exists(org_id, to_user):
return False
else:
if not is_registered_user(to_user):
return False
try:
if is_org_context(request):
org_id = request.user.org.org_id
org_share_repo(org_id, repo_id, from_user, to_user, permission)
else:
seafile_api.share_repo(repo_id, from_user, to_user, permission)
except SearpcError as e:
return False
logger.error(e)
else:
# send a signal when sharing repo successful
share_repo_to_user_successful.send(sender=None,
from_user=from_user,
to_user=to_user, repo=repo)
return True
########## views
@login_required
@require_POST
def share_repo(request):
"""
Handle POST method to share a repo to public/groups/users based on form
data. Return to ``myhome`` page and notify user whether success or failure.
"""
next = request.META.get('HTTP_REFERER', None)
if not next:
next = SITE_ROOT
form = RepoShareForm(request.POST)
if not form.is_valid():
# TODO: may display error msg on form
raise Http404
email_or_group = form.cleaned_data['email_or_group']
repo_id = form.cleaned_data['repo_id']
permission = form.cleaned_data['permission']
repo = seafile_api.get_repo(repo_id)
if not repo:
raise Http404
# Test whether user is the repo owner.
username = request.user.username
if not seafile_api.is_repo_owner(username, repo_id) and \
not is_org_repo_owner(username, repo_id):
msg = _(u'Only the owner of the library has permission to share it.')
messages.error(request, msg)
return HttpResponseRedirect(next)
# Parsing input values.
share_to_all, share_to_groups, share_to_users = False, [], []
user_groups = request.user.joined_groups
share_to_list = string2list(email_or_group)
for share_to in share_to_list:
if share_to == 'all':
share_to_all = True
elif share_to.find('@') == -1:
for user_group in user_groups:
if user_group.group_name == share_to:
share_to_groups.append(user_group)
else:
share_to = share_to.lower()
if is_valid_username(share_to):
share_to_users.append(share_to)
origin_repo_id, origin_path = get_origin_repo_info(repo.id)
if origin_repo_id is not None:
perm_repo_id = origin_repo_id
perm_path = origin_path
else:
perm_repo_id = repo.id
perm_path = '/'
if share_to_all:
share_to_public(request, repo, permission)
send_perm_audit_msg('add-repo-perm', username, 'all', \
perm_repo_id, perm_path, permission)
for group in share_to_groups:
if share_to_group(request, repo, group, permission):
send_perm_audit_msg('add-repo-perm', username, group.id, \
perm_repo_id, perm_path, permission)
for email in share_to_users:
# Add email to contacts.
mail_sended.send(sender=None, user=request.user.username, email=email)
if share_to_user(request, repo, email, permission):
send_perm_audit_msg('add-repo-perm', username, email, \
perm_repo_id, perm_path, permission)
return HttpResponseRedirect(next)
@login_required_ajax
@require_POST
def ajax_repo_remove_share(request):
"""
Remove repo shared to user/group/public
"""
content_type = 'application/json; charset=utf-8'
repo_id = request.POST.get('repo_id', None)
share_type = request.POST.get('share_type', None)
if not seafile_api.get_repo(repo_id):
return HttpResponse(json.dumps({'error': _(u'Library does not exist')}), status=400,
content_type=content_type)
username = request.user.username
if share_type == 'personal':
from_email = request.POST.get('from', None)
if not is_valid_username(from_email):
return HttpResponse(json.dumps({'error': _(u'Invalid argument')}), status=400,
content_type=content_type)
if is_org_context(request):
org_id = request.user.org.org_id
org_remove_share(org_id, repo_id, from_email, username)
else:
seaserv.remove_share(repo_id, from_email, username)
return HttpResponse(json.dumps({'success': True}), status=200,
content_type=content_type)
elif share_type == 'group':
from_email = request.POST.get('from', None)
if not is_valid_username(from_email):
return HttpResponse(json.dumps({'error': _(u'Invalid argument')}), status=400,
content_type=content_type)
group_id = request.POST.get('group_id', None)
group = seaserv.get_group(group_id)
if not group:
return HttpResponse(json.dumps({'error': _(u"Group does not exist")}), status=400,
content_type=content_type)
if seaserv.check_group_staff(group_id, username) or \
seafile_api.is_repo_owner(username, repo_id):
if is_org_group(group_id):
org_id = get_org_id_by_group(group_id)
del_org_group_repo(repo_id, org_id, group_id)
else:
seafile_api.unset_group_repo(repo_id, group_id, from_email)
return HttpResponse(json.dumps({'success': True}), status=200,
content_type=content_type)
else:
return HttpResponse(json.dumps({'error': _(u'Permission denied')}), status=400,
content_type=content_type)
elif share_type == 'public':
if is_org_context(request):
org_repo_owner = seafile_api.get_org_repo_owner(repo_id)
is_org_repo_owner = True if org_repo_owner == username else False
if request.user.org.is_staff or is_org_repo_owner:
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.unset_org_inner_pub_repo(org_id,
repo_id)
return HttpResponse(json.dumps({'success': True}), status=200,
content_type=content_type)
else:
return HttpResponse(json.dumps({'error': _(u'Permission denied')}), status=403,
content_type=content_type)
else:
if seafile_api.is_repo_owner(username, repo_id) or \
request.user.is_staff:
unset_inner_pub_repo(repo_id)
return HttpResponse(json.dumps({'success': True}), status=200,
content_type=content_type)
else:
return HttpResponse(json.dumps({'error': _(u'Permission denied')}), status=403,
content_type=content_type)
else:
return HttpResponse(json.dumps({'error': _(u'Invalid argument')}), status=400,
content_type=content_type)
@login_required
@require_POST
def repo_remove_share(request):
"""
If repo is shared from one person to another person, only these two person
can remove share.
If repo is shared from one person to a group, then only the one share the
repo and group staff can remove share.
"""
repo_id = request.GET.get('repo_id', '')
group_id = request.GET.get('gid', '')
from_email = request.GET.get('from', '')
perm = request.GET.get('permission', None)
if not is_valid_username(from_email) or perm is None:
return render_error(request, _(u'Argument is not valid'))
username = request.user.username
repo = seafile_api.get_repo(repo_id)
if not repo:
return render_error(request, _(u'Library does not exist'))
origin_repo_id, origin_path = get_origin_repo_info(repo.id)
if origin_repo_id is not None:
perm_repo_id = origin_repo_id
perm_path = origin_path
else:
perm_repo_id = repo.id
perm_path = '/'
# if request params don't have 'gid', then remove repos that share to
# to other person; else, remove repos that share to groups
if not group_id:
to_email = request.GET.get('to', '')
if not is_valid_username(to_email):
return render_error(request, _(u'Argument is not valid'))
if username != from_email and username != to_email:
return render_permission_error(request, _(u'Failed to remove share'))
if is_org_context(request):
org_id = request.user.org.org_id
org_remove_share(org_id, repo_id, from_email, to_email)
else:
seaserv.remove_share(repo_id, from_email, to_email)
send_perm_audit_msg('delete-repo-perm', from_email, to_email, \
perm_repo_id, perm_path, perm)
else:
try:
group_id = int(group_id)
except:
return render_error(request, _(u'group id is not valid'))
group = seaserv.get_group(group_id)
if not group:
return render_error(request, _(u"Failed to unshare: the group doesn't exist."))
if not seaserv.check_group_staff(group_id, username) \
and username != from_email:
return render_permission_error(request, _(u'Failed to remove share'))
if is_org_group(group_id):
org_id = get_org_id_by_group(group_id)
del_org_group_repo(repo_id, org_id, group_id)
else:
seafile_api.unset_group_repo(repo_id, group_id, from_email)
send_perm_audit_msg('delete-repo-perm', from_email, group_id, \
perm_repo_id, perm_path, perm)
messages.success(request, _('Successfully removed share'))
next = request.META.get('HTTP_REFERER', SITE_ROOT)
return HttpResponseRedirect(next)
def get_share_out_repo_list(request):
"""List repos that @user share to other users.
Returns:
A list of repos.
"""
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
return seafile_api.get_org_share_out_repo_list(org_id, username,
-1, -1)
else:
return seafile_api.get_share_out_repo_list(username, -1, -1)
def get_group_repos_by_owner(request):
"""List repos that @user share to groups.
Returns:
A list of repos.
"""
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
return get_org_group_repos_by_owner(org_id, username)
else:
return seaserv.get_group_repos_by_owner(username)
def list_inner_pub_repos_by_owner(request):
"""List repos that @user share to organizatoin.
Returns:
A list of repos, or empty list if in cloud_mode.
"""
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
return list_org_inner_pub_repos_by_owner(org_id, username)
elif request.cloud_mode:
return []
else:
return seaserv.list_inner_pub_repos_by_owner(username)
def list_share_out_repos(request):
shared_repos = []
# repos shared from this user
shared_repos += get_share_out_repo_list(request)
# repos shared to groups
group_repos = get_group_repos_by_owner(request)
for repo in group_repos:
group = ccnet_threaded_rpc.get_group(int(repo.group_id))
if not group:
repo.props.user = ''
continue
repo.props.user = group.props.group_name
repo.props.user_info = repo.group_id
shared_repos += group_repos
# inner pub repos
pub_repos = list_inner_pub_repos_by_owner(request)
for repo in pub_repos:
repo.props.user = _(u'all members')
repo.props.user_info = 'all'
shared_repos += pub_repos
return shared_repos
@login_required
@user_mods_check
def list_shared_repos(request):
""" List user repos shared to users/groups/public.
"""
share_out_repos = list_share_out_repos(request)
out_repos = []
for repo in share_out_repos:
if repo.is_virtual: # skip virtual repos
continue
if repo.props.permission == 'rw':
repo.share_permission = _(u'Read-Write')
elif repo.props.permission == 'r':
repo.share_permission = _(u'Read-Only')
else:
repo.share_permission = ''
if repo.props.share_type == 'personal':
repo.props.user_info = repo.props.user
out_repos.append(repo)
out_repos.sort(lambda x, y: cmp(x.repo_name, y.repo_name))
return render_to_response('share/repos.html', {
"out_repos": out_repos,
}, context_instance=RequestContext(request))
@login_required
@user_mods_check
def list_shared_links(request):
"""List shared links, and remove invalid links(file/dir is deleted or moved).
"""
username = request.user.username
# download links
fileshares = FileShare.objects.filter(username=username)
fs_files, fs_dirs = [], []
for fs in fileshares:
r = seafile_api.get_repo(fs.repo_id)
if not r:
fs.delete()
continue
if fs.is_file_share_link():
if seafile_api.get_file_id_by_path(r.id, fs.path) is None:
fs.delete()
continue
fs.filename = os.path.basename(fs.path)
fs.shared_link = gen_file_share_link(fs.token)
else:
if seafile_api.get_dir_id_by_path(r.id, fs.path) is None:
fs.delete()
continue
if fs.path != '/':
fs.filename = os.path.basename(fs.path.rstrip('/'))
else:
fs.filename = fs.path
fs.shared_link = gen_dir_share_link(fs.token)
fs.repo = r
if fs.expire_date is not None and timezone.now() > fs.expire_date:
fs.is_expired = True
fs_files.append(fs) if fs.is_file_share_link() else fs_dirs.append(fs)
fs_files.sort(lambda x, y: cmp(x.filename, y.filename))
fs_dirs.sort(lambda x, y: cmp(x.filename, y.filename))
# upload links
uploadlinks = UploadLinkShare.objects.filter(username=username)
p_uploadlinks = []
for link in uploadlinks:
r = seafile_api.get_repo(link.repo_id)
if not r:
link.delete()
continue
if seafile_api.get_dir_id_by_path(r.id, link.path) is None:
link.delete()
continue
if link.path != '/':
link.dir_name = os.path.basename(link.path.rstrip('/'))
else:
link.dir_name = link.path
link.shared_link = gen_shared_upload_link(link.token)
link.repo = r
p_uploadlinks.append(link)
p_uploadlinks.sort(lambda x, y: cmp(x.dir_name, y.dir_name))
return render_to_response('share/links.html', {
"fileshares": fs_dirs + fs_files,
"uploadlinks": p_uploadlinks,
}, context_instance=RequestContext(request))
@login_required
@user_mods_check
def list_priv_shared_folders(request):
"""List private shared folders.
Arguments:
- `request`:
"""
share_out_repos = list_share_out_repos(request)
shared_folders = []
for repo in share_out_repos:
if not repo.is_virtual: # skip non-virtual repos
continue
if repo.props.permission == 'rw':
repo.share_permission = _(u'Read-Write')
elif repo.props.permission == 'r':
repo.share_permission = _(u'Read-Only')
else:
repo.share_permission = ''
if repo.props.share_type == 'personal':
repo.props.user_info = repo.props.user
shared_folders.append(repo)
shared_folders.sort(lambda x, y: cmp(x.repo_id, y.repo_id))
return render_to_response('share/list_priv_shared_folders.html', {
'shared_folders': shared_folders,
}, context_instance=RequestContext(request))
@login_required_ajax
def share_permission_admin(request):
"""Change repo share permission in ShareAdmin.
"""
share_type = request.GET.get('share_type', '')
content_type = 'application/json; charset=utf-8'
form = RepoShareForm(request.POST)
form.is_valid()
email_or_group = form.cleaned_data['email_or_group']
repo_id = form.cleaned_data['repo_id']
permission = form.cleaned_data['permission']
from_email = request.user.username
repo = seafile_api.get_repo(repo_id)
if not repo:
return render_error(request, _(u'Library does not exist'))
origin_repo_id, origin_path = get_origin_repo_info(repo.id)
if origin_repo_id is not None:
perm_repo_id = origin_repo_id
perm_path = origin_path
else:
perm_repo_id = repo.id
perm_path = '/'
if share_type == 'personal':
if not is_valid_username(email_or_group):
return HttpResponse(json.dumps({'success': False}), status=400,
content_type=content_type)
try:
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.org_set_share_permission(
org_id, repo_id, from_email, email_or_group, permission)
else:
seafile_api.set_share_permission(repo_id, from_email,
email_or_group, permission)
send_perm_audit_msg('modify-repo-perm', from_email, \
email_or_group, perm_repo_id, perm_path, permission)
except SearpcError:
return HttpResponse(json.dumps({'success': False}), status=500,
content_type=content_type)
return HttpResponse(json.dumps({'success': True}),
content_type=content_type)
elif share_type == 'group':
try:
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.set_org_group_repo_permission(
org_id, int(email_or_group), repo_id, permission)
else:
group_id = int(email_or_group)
seafile_api.set_group_repo_permission(group_id,
repo_id,
permission)
send_perm_audit_msg('modify-repo-perm', from_email, \
group_id, perm_repo_id, perm_path, permission)
except SearpcError:
return HttpResponse(json.dumps({'success': False}), status=500,
content_type=content_type)
return HttpResponse(json.dumps({'success': True}),
content_type=content_type)
elif share_type == 'public':
try:
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.set_org_inner_pub_repo(
org_id, repo_id, permission)
else:
seafile_api.add_inner_pub_repo(repo_id, permission)
send_perm_audit_msg('modify-repo-perm', from_email, 'all', \
perm_repo_id, perm_path, permission)
except SearpcError:
return HttpResponse(json.dumps({'success': False}), status=500,
content_type=content_type)
return HttpResponse(json.dumps({'success': True}),
content_type=content_type)
else:
return HttpResponse(json.dumps({'success': False}), status=400,
content_type=content_type)
########## share link
@login_required_ajax
@require_POST
def ajax_remove_shared_link(request):
username = request.user.username
content_type = 'application/json; charset=utf-8'
result = {}
token = request.POST.get('t')
if not token:
result = {'error': _(u"Argument missing")}
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
try:
link = FileShare.objects.get(token=token)
except FileShare.DoesNotExist:
result = {'error': _(u"The link doesn't exist")}
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
if not link.is_owner(username):
result = {'error': _("Permission denied")}
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
link.delete()
result = {'success': True}
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
@require_POST
def ajax_remove_shared_upload_link(request):
username = request.user.username
content_type = 'application/json; charset=utf-8'
result = {}
token = request.POST.get('t')
if not token:
result = {'error': _(u"Argument missing")}
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
try:
upload_link = UploadLinkShare.objects.get(token=token)
except UploadLinkShare.DoesNotExist:
result = {'error': _(u"The link doesn't exist")}
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
if not upload_link.is_owner(username):
result = {'error': _("Permission denied")}
return HttpResponse(json.dumps(result), status=403,
content_type=content_type)
upload_link.delete()
result = {'success': True}
return HttpResponse(json.dumps(result), content_type=content_type)
@login_required_ajax
def send_shared_link(request):
"""
Handle ajax post request to send file shared link.
"""
if not request.method == 'POST':
raise Http404
content_type = 'application/json; charset=utf-8'
if not IS_EMAIL_CONFIGURED:
data = json.dumps({'error':_(u'Sending shared link failed. Email service is not properly configured, please contact administrator.')})
return HttpResponse(data, status=500, content_type=content_type)
from seahub.settings import SITE_NAME
form = FileLinkShareForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
file_shared_link = form.cleaned_data['file_shared_link']
file_shared_name = form.cleaned_data['file_shared_name']
file_shared_type = form.cleaned_data['file_shared_type']
extra_msg = escape(form.cleaned_data['extra_msg'])
to_email_list = string2list(email)
send_success, send_failed = [], []
for to_email in to_email_list:
if not is_valid_username(to_email):
send_failed.append(to_email)
continue
# Add email to contacts.
mail_sended.send(sender=None, user=request.user.username,
email=to_email)
c = {
'email': request.user.username,
'to_email': to_email,
'file_shared_link': file_shared_link,
'file_shared_name': file_shared_name,
}
if extra_msg:
c['extra_msg'] = extra_msg
if REPLACE_FROM_EMAIL:
from_email = request.user.username
else:
from_email = None # use default from email
if ADD_REPLY_TO_HEADER:
reply_to = request.user.username
else:
reply_to = None
try:
if file_shared_type == 'f':
c['file_shared_type'] = _(u"file")
send_html_email(_(u'A file is shared to you on %s') % SITE_NAME,
'shared_link_email.html',
c, from_email, [to_email],
reply_to=reply_to
)
else:
c['file_shared_type'] = _(u"directory")
send_html_email(_(u'A directory is shared to you on %s') % SITE_NAME,
'shared_link_email.html',
c, from_email, [to_email],
reply_to=reply_to)
send_success.append(to_email)
except Exception, e:
send_failed.append(to_email)
if len(send_success) > 0:
data = json.dumps({"send_success": send_success, "send_failed": send_failed})
return HttpResponse(data, status=200, content_type=content_type)
else:
data = json.dumps({"error": _("Internal server error, or please check the email(s) you entered")})
return HttpResponse(data, status=400, content_type=content_type)
else:
return HttpResponseBadRequest(json.dumps(form.errors),
content_type=content_type)
@login_required
def save_shared_link(request):
"""Save public share link to one's library.
"""
username = request.user.username
token = request.GET.get('t', '')
dst_repo_id = request.POST.get('dst_repo', '')
dst_path = request.POST.get('dst_path', '')
next = request.META.get('HTTP_REFERER', None)
if not next:
next = SITE_ROOT
if not dst_repo_id or not dst_path:
messages.error(request, _(u'Please choose a directory.'))
return HttpResponseRedirect(next)
if check_folder_permission(request, dst_repo_id, dst_path) != 'rw':
messages.error(request, _('Permission denied'))
return HttpResponseRedirect(next)
try:
fs = FileShare.objects.get(token=token)
except FileShare.DoesNotExist:
raise Http404
src_repo_id = fs.repo_id
src_path = os.path.dirname(fs.path)
obj_name = os.path.basename(fs.path)
new_obj_name = check_filename_with_rename(dst_repo_id, dst_path, obj_name)
seafile_api.copy_file(src_repo_id, src_path, obj_name,
dst_repo_id, dst_path, new_obj_name, username,
need_progress=0)
messages.success(request, _(u'Successfully saved.'))
return HttpResponseRedirect(next)
########## private share
@require_POST
def gen_private_file_share(request, repo_id):
emails = request.POST.getlist('emails', '')
s_type = request.POST.get('s_type', '')
path = request.POST.get('path', '')
perm = request.POST.get('perm', 'r')
file_or_dir = os.path.basename(path.rstrip('/'))
username = request.user.username
next = request.META.get('HTTP_REFERER', None)
if not next:
next = SITE_ROOT
if not check_folder_permission(request, repo_id, file_or_dir):
messages.error(request, _('Permission denied'))
return HttpResponseRedirect(next)
for email in [e.strip() for e in emails if e.strip()]:
if not is_valid_username(email):
continue
if not is_registered_user(email):
messages.error(request, _('Failed to share to "%s", user not found.') % email)
continue
if s_type == 'f':
pfds = PrivateFileDirShare.objects.add_read_only_priv_file_share(
username, email, repo_id, path)
elif s_type == 'd':
pfds = PrivateFileDirShare.objects.add_private_dir_share(
username, email, repo_id, path, perm)
else:
continue
# send a signal when sharing file successful
share_file_to_user_successful.send(sender=None, priv_share_obj=pfds)
messages.success(request, _('Successfully shared %s.') % file_or_dir)
return HttpResponseRedirect(next)
@login_required
def rm_private_file_share(request, token):
"""Remove private file shares.
"""
try:
pfs = PrivateFileDirShare.objects.get_priv_file_dir_share_by_token(token)
except PrivateFileDirShare.DoesNotExist:
raise Http404
from_user = pfs.from_user
to_user = pfs.to_user
path = pfs.path
file_or_dir = os.path.basename(path.rstrip('/'))
username = request.user.username
if username == from_user or username == to_user:
pfs.delete()
messages.success(request, _('Successfully unshared "%s".') % file_or_dir)
else:
messages.error(request, _("You don't have permission to unshare %s.") % file_or_dir)
next = request.META.get('HTTP_REFERER', None)
if not next:
next = SITE_ROOT
return HttpResponseRedirect(next)
@login_required
def save_private_file_share(request, token):
"""
Save private share file to someone's library.
"""
username = request.user.username
next = request.META.get('HTTP_REFERER', None)
if not next:
next = SITE_ROOT
try:
pfs = PrivateFileDirShare.objects.get_priv_file_dir_share_by_token(token)
except PrivateFileDirShare.DoesNotExist:
raise Http404
from_user = pfs.from_user
to_user = pfs.to_user
repo_id = pfs.repo_id
path = pfs.path
src_path = os.path.dirname(path)
obj_name = os.path.basename(path.rstrip('/'))
if username == from_user or username == to_user:
dst_repo_id = request.POST.get('dst_repo')
dst_path = request.POST.get('dst_path')
if check_folder_permission(request, dst_repo_id, dst_path) != 'rw':
messages.error(request, _('Permission denied'))
return HttpResponseRedirect(next)
new_obj_name = check_filename_with_rename(dst_repo_id, dst_path, obj_name)
seafile_api.copy_file(repo_id, src_path, obj_name,
dst_repo_id, dst_path, new_obj_name, username,
need_progress=0)
messages.success(request, _(u'Successfully saved.'))
else:
messages.error(request, _("You don't have permission to save %s.") % obj_name)
return HttpResponseRedirect(next)
@login_required_ajax
def send_shared_upload_link(request):
"""
Handle ajax post request to send shared upload link.
"""
if not request.method == 'POST':
raise Http404
content_type = 'application/json; charset=utf-8'
if not IS_EMAIL_CONFIGURED:
data = json.dumps({'error':_(u'Sending shared upload link failed. Email service is not properly configured, please contact administrator.')})
return HttpResponse(data, status=500, content_type=content_type)
from seahub.settings import SITE_NAME
form = UploadLinkShareForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
shared_upload_link = form.cleaned_data['shared_upload_link']
extra_msg = escape(form.cleaned_data['extra_msg'])
to_email_list = string2list(email)
send_success, send_failed = [], []
for to_email in to_email_list:
if not is_valid_username(to_email):
send_failed.append(to_email)
continue
# Add email to contacts.
mail_sended.send(sender=None, user=request.user.username,
email=to_email)
c = {
'email': request.user.username,
'to_email': to_email,
'shared_upload_link': shared_upload_link,
}
if extra_msg:
c['extra_msg'] = extra_msg
if REPLACE_FROM_EMAIL:
from_email = request.user.username
else:
from_email = None # use default from email
if ADD_REPLY_TO_HEADER:
reply_to = request.user.username
else:
reply_to = None
try:
send_html_email(_(u'An upload link is shared to you on %s') % SITE_NAME,
'shared_upload_link_email.html',
c, from_email, [to_email],
reply_to=reply_to)
send_success.append(to_email)
except Exception, e:
send_failed.append(to_email)
if len(send_success) > 0:
data = json.dumps({"send_success": send_success, "send_failed": send_failed})
return HttpResponse(data, status=200, content_type=content_type)
else:
data = json.dumps({"error": _("Internal server error, or please check the email(s) you entered")})
return HttpResponse(data, status=400, content_type=content_type)
else:
return HttpResponseBadRequest(json.dumps(form.errors),
content_type=content_type)
@login_required_ajax
def ajax_get_upload_link(request):
content_type = 'application/json; charset=utf-8'
if request.method == 'GET':
repo_id = request.GET.get('repo_id', '')
path = request.GET.get('p', '')
username = request.user.username
if not path.endswith('/'):
path = path + '/'
l = UploadLinkShare.objects.filter(repo_id=repo_id).filter(
username=username).filter(path=path)
if len(l) > 0:
token = l[0].token
data = {
'upload_link': gen_shared_upload_link(token),
'token': token,
}
else:
data = {}
return HttpResponse(json.dumps(data), content_type=content_type)
elif request.method == 'POST':
if not request.user.permissions.can_generate_shared_link():
err = _('You do not have permission to generate shared link')
data = json.dumps({'error': err})
return HttpResponse(data, status=403, content_type=content_type)
repo_id = request.POST.get('repo_id', '')
path = request.POST.get('p', '')
use_passwd = True if int(request.POST.get('use_passwd', '0')) == 1 else False
passwd = request.POST.get('passwd') if use_passwd else None
if not (repo_id and path):
err = _('Invalid arguments')
data = json.dumps({'error': err})
return HttpResponse(data, status=400, content_type=content_type)
if passwd and len(passwd) < config.SHARE_LINK_PASSWORD_MIN_LENGTH:
err = _('Password is too short')
data = json.dumps({'error': err})
return HttpResponse(data, status=400, content_type=content_type)
if path[-1] != '/': # append '/' at end of path
path += '/'
repo = seaserv.get_repo(repo_id)
user_perm = check_repo_access_permission(repo.id, request.user)
if user_perm == 'rw':
l = UploadLinkShare.objects.filter(repo_id=repo_id).filter(
username=request.user.username).filter(path=path)
if len(l) > 0:
upload_link = l[0]
token = upload_link.token
else:
username = request.user.username
uls = UploadLinkShare.objects.create_upload_link_share(
username, repo_id, path, passwd)
token = uls.token
shared_upload_link = gen_shared_upload_link(token)
data = json.dumps({'token': token, 'upload_link': shared_upload_link})
return HttpResponse(data, content_type=content_type)
else:
return HttpResponse(json.dumps({'error': _(u'Permission denied')}),
status=403, content_type=content_type)
@login_required_ajax
def ajax_get_download_link(request):
"""
Handle ajax request to generate file or dir shared link.
"""
content_type = 'application/json; charset=utf-8'
if request.method == 'GET':
repo_id = request.GET.get('repo_id', '')
share_type = request.GET.get('type', 'f') # `f` or `d`
path = request.GET.get('p', '')
username = request.user.username
if share_type == 'd' and not path.endswith('/'):
path = path + '/'
l = FileShare.objects.filter(repo_id=repo_id).filter(
username=username).filter(path=path)
if len(l) > 0:
token = l[0].token
data = {
'download_link': gen_shared_link(token, l[0].s_type),
'token': token,
'is_expired': l[0].is_expired(),
}
else:
data = {}
return HttpResponse(json.dumps(data), content_type=content_type)
elif request.method == 'POST':
if not request.user.permissions.can_generate_shared_link():
err = _('You do not have permission to generate shared link')
data = json.dumps({'error': err})
return HttpResponse(data, status=403, content_type=content_type)
repo_id = request.POST.get('repo_id', '')
share_type = request.POST.get('type', 'f') # `f` or `d`
path = request.POST.get('p', '')
use_passwd = True if int(request.POST.get('use_passwd', '0')) == 1 else False
passwd = request.POST.get('passwd') if use_passwd else None
if not (repo_id and path):
err = _('Invalid arguments')
data = json.dumps({'error': err})
return HttpResponse(data, status=400, content_type=content_type)
if passwd and len(passwd) < config.SHARE_LINK_PASSWORD_MIN_LENGTH:
err = _('Password is too short')
data = json.dumps({'error': err})
return HttpResponse(data, status=400, content_type=content_type)
try:
expire_days = int(request.POST.get('expire_days', 0))
except ValueError:
expire_days = 0
if expire_days <= 0:
expire_date = None
else:
expire_date = timezone.now() + relativedelta(days=expire_days)
username = request.user.username
if share_type == 'f':
fs = FileShare.objects.get_file_link_by_path(username, repo_id, path)
if fs is None:
fs = FileShare.objects.create_file_link(username, repo_id, path,
passwd, expire_date)
if is_org_context(request):
org_id = request.user.org.org_id
OrgFileShare.objects.set_org_file_share(org_id, fs)
else:
fs = FileShare.objects.get_dir_link_by_path(username, repo_id, path)
if fs is None:
fs = FileShare.objects.create_dir_link(username, repo_id, path,
passwd, expire_date)
if is_org_context(request):
org_id = request.user.org.org_id
OrgFileShare.objects.set_org_file_share(org_id, fs)
token = fs.token
shared_link = gen_shared_link(token, fs.s_type)
data = json.dumps({'token': token, 'download_link': shared_link})
return HttpResponse(data, content_type=content_type)
@login_required_ajax
@require_POST
def ajax_private_share_dir(request):
content_type = 'application/json; charset=utf-8'
repo_id = request.POST.get('repo_id', '')
path = request.POST.get('path', '')
username = request.user.username
result = {}
repo = seafile_api.get_repo(repo_id)
if not repo:
result['error'] = _(u'Library does not exist.')
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
if seafile_api.get_dir_id_by_path(repo_id, path) is None:
result['error'] = _(u'Directory does not exist.')
return HttpResponse(json.dumps(result), status=400, content_type=content_type)
if path != '/':
# if share a dir, check sub-repo first
try:
if is_org_context(request):
org_id = request.user.org.org_id
sub_repo = seaserv.seafserv_threaded_rpc.get_org_virtual_repo(
org_id, repo_id, path, username)
else:
sub_repo = seafile_api.get_virtual_repo(repo_id, path, username)
except SearpcError as e:
result['error'] = e.msg
return HttpResponse(json.dumps(result), status=500, content_type=content_type)
if not sub_repo:
name = os.path.basename(path)
# create a sub-lib
try:
# use name as 'repo_name' & 'repo_desc' for sub_repo
if is_org_context(request):
org_id = request.user.org.org_id
sub_repo_id = seaserv.seafserv_threaded_rpc.create_org_virtual_repo(
org_id, repo_id, path, name, name, username)
else:
sub_repo_id = seafile_api.create_virtual_repo(repo_id, path,
name, name, username)
sub_repo = seafile_api.get_repo(sub_repo_id)
except SearpcError as e:
result['error'] = e.msg
return HttpResponse(json.dumps(result), status=500, content_type=content_type)
shared_repo_id = sub_repo.id
shared_repo = sub_repo
else:
shared_repo_id = repo_id
shared_repo = repo
emails_string = request.POST.get('emails', '')
groups_string = request.POST.get('groups', '')
perm = request.POST.get('perm', '')
emails = string2list(emails_string)
groups = string2list(groups_string)
# Test whether user is the repo owner.
if not seafile_api.is_repo_owner(username, shared_repo_id) and \
not is_org_repo_owner(username, shared_repo_id):
result['error'] = _(u'Only the owner of the library has permission to share it.')
return HttpResponse(json.dumps(result), status=500, content_type=content_type)
# Parsing input values.
# no 'share_to_all'
share_to_groups, share_to_users, shared_success, shared_failed = [], [], [], []
for email in emails:
email = email.lower()
if is_valid_username(email):
share_to_users.append(email)
else:
shared_failed.append(email)
for group_id in groups:
share_to_groups.append(seaserv.get_group(group_id))
for email in share_to_users:
# Add email to contacts.
mail_sended.send(sender=None, user=request.user.username, email=email)
if share_to_user(request, shared_repo, email, perm):
shared_success.append(email)
else:
shared_failed.append(email)
for group in share_to_groups:
if share_to_group(request, shared_repo, group, perm):
shared_success.append(group.group_name)
else:
shared_failed.append(group.group_name)
if len(shared_success) > 0:
return HttpResponse(json.dumps({
"shared_success": shared_success,
"shared_failed": shared_failed
}), content_type=content_type)
else:
# for case: only share to users and the emails are not valid
data = json.dumps({"error": _("Please check the email(s) you entered")})
return HttpResponse(data, status=400, content_type=content_type)
<file_sep>/seahub/help/urls.py
from django.conf.urls.defaults import *
from django.views.generic import TemplateView
urlpatterns = patterns(
'',
(r'^$', TemplateView.as_view(template_name="help/help_install_v2.html") ),
(r'^install/$', TemplateView.as_view(template_name="help/help_install_v2.html") ),
(r'^delete/$', TemplateView.as_view(template_name="help/help_delete.html") ),
(r'^security/$', TemplateView.as_view(template_name="help/help_security.html") ),
(r'^colab/$', TemplateView.as_view(template_name="help/help_colab.html") ),
(r'^ignore/$', TemplateView.as_view(template_name="help/help_ignore.html") ),
(r'^group_share/$', TemplateView.as_view(template_name="help/help_group_share.html") ),
(r'^view_encrypted/$', TemplateView.as_view(template_name="help/help_view_encrypted.html") ),
)
<file_sep>/seahub/wiki/utils.py
# -*- coding: utf-8 -*-
import os
import stat
import urllib2
from django.core.urlresolvers import reverse
from django.utils.http import urlquote
from django.utils.encoding import smart_str
import seaserv
from seaserv import seafile_api
from pysearpc import SearpcError
from seahub.utils import EMPTY_SHA1
from seahub.utils.slugify import slugify
from seahub.utils import render_error, render_permission_error, string2list, \
gen_file_get_url, get_file_type_and_ext, gen_inner_file_get_url
from seahub.utils.file_types import IMAGE
from models import WikiPageMissing, WikiDoesNotExist, GroupWiki, PersonalWiki
__all__ = ["get_wiki_dirent", "clean_page_name", "page_name_to_file_name"]
SLUG_OK = "!@#$%^&()_+-,.;'"
def normalize_page_name(page_name):
# Remove special characters. Lower page name and replace spaces with '-'.
return slugify(page_name, ok=SLUG_OK)
def clean_page_name(page_name):
# Remove special characters. Do not lower page name and spaces are allowed.
return slugify(page_name, ok=SLUG_OK, lower=False, spaces=True)
def page_name_to_file_name(page_name):
"""Append ".md" if page name does not end with .md or .markdown.
"""
if page_name.endswith('.md') or page_name.endswith('.markdown'):
return page_name
return page_name + '.md'
def get_wiki_dirent(repo_id, page_name):
file_name = page_name_to_file_name(page_name)
repo = seaserv.get_repo(repo_id)
if not repo:
raise WikiDoesNotExist
cmmt = seaserv.get_commits(repo.id, 0, 1)[0]
if cmmt is None:
raise WikiPageMissing
dirs = seafile_api.list_dir_by_commit_and_path(cmmt.repo_id, cmmt.id, "/")
if dirs:
for e in dirs:
if stat.S_ISDIR(e.mode):
continue # skip directories
if normalize_page_name(file_name) == normalize_page_name(e.obj_name):
return e
raise WikiPageMissing
def get_inner_file_url(repo, obj_id, file_name):
repo_id = repo.id
access_token = seafile_api.get_fileserver_access_token(repo_id, obj_id,
'view', '')
url = gen_inner_file_get_url(access_token, file_name)
return url
def get_personal_wiki_repo(username):
try:
wiki = PersonalWiki.objects.get(username=username)
except PersonalWiki.DoesNotExist:
raise WikiDoesNotExist
repo = seaserv.get_repo(wiki.repo_id)
if not repo:
raise WikiDoesNotExist
return repo
def get_group_wiki_repo(group, username):
try:
groupwiki = GroupWiki.objects.get(group_id=group.id)
except GroupWiki.DoesNotExist:
raise WikiDoesNotExist
repos = seaserv.get_group_repos(group.id, username)
for repo in repos:
if repo.id == groupwiki.repo_id:
return repo
raise WikiDoesNotExist
def get_personal_wiki_page(username, page_name):
repo = get_personal_wiki_repo(username)
dirent = get_wiki_dirent(repo.id, page_name)
url = get_inner_file_url(repo, dirent.obj_id, dirent.obj_name)
file_response = urllib2.urlopen(url)
content = file_response.read()
return content, repo, dirent
def get_group_wiki_page(username, group, page_name):
repo = get_group_wiki_repo(group, username)
dirent = get_wiki_dirent(repo.id, page_name)
url = get_inner_file_url(repo, dirent.obj_id, dirent.obj_name)
file_response = urllib2.urlopen(url)
content = file_response.read()
return content, repo, dirent
def get_wiki_pages(repo):
"""
return pages in hashtable {normalized_name: page_name}
"""
dir_id = seaserv.seafserv_threaded_rpc.get_dir_id_by_path(repo.id, '/')
if not dir_id:
return {}
dirs = seafile_api.list_dir_by_dir_id(repo.id, dir_id)
pages = {}
for e in dirs:
if stat.S_ISDIR(e.mode):
continue # skip directories
name, ext = os.path.splitext(e.obj_name)
if ext == '.md':
key = normalize_page_name(name)
pages[key] = name
return pages
def convert_wiki_link(content, url_prefix, repo_id, username):
import re
def repl(matchobj):
if matchobj.group(2): # return origin string in backquotes
return matchobj.group(2)
page_alias = page_name = matchobj.group(1).strip()
if len(page_name.split('|')) > 1:
page_alias = page_name.split('|')[0]
page_name = page_name.split('|')[1]
filetype, fileext = get_file_type_and_ext(page_name)
if fileext == '':
# convert page_name that extension is missing to a markdown page
try:
dirent = get_wiki_dirent(repo_id, page_name)
a_tag = '''<a href="%s">%s</a>'''
return a_tag % (smart_str(url_prefix + normalize_page_name(page_name) + '/'), page_alias)
except (WikiDoesNotExist, WikiPageMissing):
a_tag = '''<a href="%s" class="wiki-page-missing">%s</a>'''
return a_tag % (smart_str(url_prefix + normalize_page_name(page_name) + '/'), page_alias)
elif filetype == IMAGE:
# load image to wiki page
path = "/" + page_name
filename = os.path.basename(path)
obj_id = seaserv.get_file_id_by_path(repo_id, path)
if not obj_id:
# Replace '/' in page_name to '-', since wiki name can not
# contain '/'.
return '''<a href="%s" class="wiki-page-missing">%s</a>''' % \
(url_prefix + '/' + page_name.replace('/', '-'), page_name)
token = seafile_api.get_fileserver_access_token(repo_id, obj_id,
'view', username)
ret = '<img src="%s" alt="%s" class="wiki-image" />' % (gen_file_get_url(token, filename), filename)
return smart_str(ret)
else:
from seahub.base.templatetags.seahub_tags import file_icon_filter
from django.conf import settings
# convert other types of filelinks to clickable links
path = "/" + page_name
icon = file_icon_filter(page_name)
s = reverse('view_lib_file', args=[repo_id, urlquote(path)])
a_tag = '''<img src="%simg/file/%s" alt="%s" class="file-icon vam" /> <a href="%s" class="vam" target="_blank">%s</a>'''
ret = a_tag % (settings.MEDIA_URL, icon, icon, smart_str(s), page_name)
return smart_str(ret)
return re.sub(r'\[\[(.+?)\]\]|(`.+?`)', repl, content)
<file_sep>/seahub/contacts/models.py
# encoding: utf-8
from django import forms
from django.db import models
from django.forms import ModelForm
from django.utils.translation import ugettext as _
from django.core.exceptions import MultipleObjectsReturned
from seaserv import ccnet_threaded_rpc
from seahub.base.fields import LowerCaseCharField
from settings import CONTACT_EMAIL_LENGTH
class ContactManager(models.Manager):
def add_contact(self, user_email, contact_email, contact_name=None, note=None):
contact = self.model(user_email=user_email,
contact_email=contact_email,
contact_name=contact_name, note=note)
contact.save(using=self._db)
return contact
def get_contacts_by_user(self, user_email):
"""Get a user's contacts.
"""
return super(ContactManager, self).filter(user_email=user_email)
def get_contact_by_user(self, user_email, contact_email):
"""Return a certern contact of ``user_email``.
"""
try:
c = super(ContactManager, self).get(user_email=user_email,
contact_email=contact_email)
except Contact.DoesNotExist:
c = None
except MultipleObjectsReturned:
c = super(ContactManager, self).filter(user_email=user_email,
contact_email=contact_email)[0]
return c
# def get_registered_contacts_by_user(self, user_email):
# """Get a user's registered contacts.
# Returns:
# A list contains the contacts.
# """
# contacts = [ c.contact_email for c in super(
# ContactManager, self).filter(user_email=user_email) ]
# emailusers = ccnet_threaded_rpc.filter_emailusers_by_emails(
# ','.join(contacts))
# return [ Contact(user_email=user_email, contact_email=e.email) \
# for e in emailusers ]
class Contact(models.Model):
"""Record user's contacts."""
user_email = LowerCaseCharField(max_length=CONTACT_EMAIL_LENGTH, db_index=True)
contact_email = LowerCaseCharField(max_length=CONTACT_EMAIL_LENGTH)
contact_name = models.CharField(max_length=255, blank=True, null=True, \
default='')
note = models.CharField(max_length=255, blank=True, null=True, default='')
objects = ContactManager()
def __unicode__(self):
return self.contact_email
# class Meta:
# unique_together = ("user_email", "contact_email")
class ContactAddForm(ModelForm):
class Meta:
model = Contact
def clean(self):
if not 'contact_email' in self.cleaned_data:
raise forms.ValidationError(_('Email is required.'))
else:
return self.cleaned_data
class ContactEditForm(ModelForm):
class Meta:
model = Contact
def __init__(self, *args, **kwargs):
super(ContactEditForm, self).__init__(*args, **kwargs)
self.fields['contact_email'].widget.attrs['readonly'] = True
def clean(self):
# This is used to override unique index check
return self.cleaned_data
<file_sep>/seahub/api2/endpoints/dir_shared_items.py
import logging
import json
import os
from django.http import HttpResponse
from pysearpc import SearpcError
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
import seaserv
from seaserv import seafile_api
from seahub.api2.authentication import TokenAuthentication
from seahub.api2.permissions import IsRepoAccessible
from seahub.api2.utils import api_error
from seahub.base.templatetags.seahub_tags import email2nickname
from seahub.base.accounts import User
from seahub.share.signals import share_repo_to_user_successful
from seahub.utils import (is_org_context, is_valid_username,
send_perm_audit_msg)
logger = logging.getLogger(__name__)
json_content_type = 'application/json; charset=utf-8'
class DirSharedItemsEndpoint(APIView):
"""Support uniform interface(list, share, unshare, modify) for sharing
library/folder to users/groups.
"""
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated, IsRepoAccessible)
throttle_classes = (UserRateThrottle, )
def list_user_shared_items(self, request, repo_id, path):
username = request.user.username
if path == '/':
share_items = seafile_api.list_repo_shared_to(username, repo_id)
else:
share_items = seafile_api.get_shared_users_for_subdir(repo_id,
path, username)
ret = []
for item in share_items:
ret.append({
"share_type": "user",
"user_info": {
"name": item.user,
"nickname": email2nickname(item.user),
},
"permission": item.perm,
})
return ret
def list_group_shared_items(self, request, repo_id, path):
username = request.user.username
if path == '/':
share_items = seafile_api.list_repo_shared_group(username, repo_id)
else:
share_items = seafile_api.get_shared_groups_for_subdir(repo_id,
path, username)
ret = []
for item in share_items:
ret.append({
"share_type": "group",
"group_info": {
"id": item.group_id,
"name": seaserv.get_group(item.group_id).group_name,
},
"permission": item.perm,
})
return ret
def handle_shared_to_args(self, request):
share_type = request.GET.get('share_type', None)
shared_to_user = False
shared_to_group = False
if share_type:
for e in share_type.split(','):
e = e.strip()
if e not in ['user', 'group']:
continue
if e == 'user':
shared_to_user = True
if e == 'group':
shared_to_group = True
else:
shared_to_user = True
shared_to_group = True
return (shared_to_user, shared_to_group)
def get_sub_repo_by_path(self, request, repo, path):
if path == '/':
raise Exception("Invalid path")
# get or create sub repo
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
sub_repo = seaserv.seafserv_threaded_rpc.get_org_virtual_repo(
org_id, repo.id, path, username)
else:
sub_repo = seafile_api.get_virtual_repo(repo.id, path, username)
return sub_repo
def get_or_create_sub_repo_by_path(self, request, repo, path):
username = request.user.username
sub_repo = self.get_sub_repo_by_path(request, repo, path)
if not sub_repo:
name = os.path.basename(path)
# create a sub-lib,
# use name as 'repo_name' & 'repo_desc' for sub_repo
if is_org_context(request):
org_id = request.user.org.org_id
sub_repo_id = seaserv.seafserv_threaded_rpc.create_org_virtual_repo(
org_id, repo.id, path, name, name, username)
else:
sub_repo_id = seafile_api.create_virtual_repo(repo.id, path,
name, name, username)
sub_repo = seafile_api.get_repo(sub_repo_id)
return sub_repo
def get_repo_owner(self, request, repo_id):
if is_org_context(request):
return seafile_api.get_org_repo_owner(repo_id)
else:
return seafile_api.get_repo_owner(repo_id)
def get(self, request, repo_id, format=None):
"""List shared items(shared to users/groups) for a folder/library.
"""
repo = seafile_api.get_repo(repo_id)
if not repo:
return api_error(status.HTTP_400_BAD_REQUEST, 'Repo not found.')
shared_to_user, shared_to_group = self.handle_shared_to_args(request)
path = request.GET.get('p', '/')
if seafile_api.get_dir_id_by_path(repo.id, path) is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Directory not found.')
ret = []
if shared_to_user:
ret += self.list_user_shared_items(request, repo_id, path)
if shared_to_group:
ret += self.list_group_shared_items(request, repo_id, path)
return HttpResponse(json.dumps(ret), status=200,
content_type=json_content_type)
def post(self, request, repo_id, format=None):
"""Update shared item permission.
"""
username = request.user.username
repo = seafile_api.get_repo(repo_id)
if not repo:
return api_error(status.HTTP_400_BAD_REQUEST, 'Repo not found.')
path = request.GET.get('p', '/')
if seafile_api.get_dir_id_by_path(repo.id, path) is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Directory not found.')
if username != self.get_repo_owner(request, repo_id):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
shared_to_user, shared_to_group = self.handle_shared_to_args(request)
permission = request.DATA.get('permission', 'r')
if permission not in ['r', 'rw']:
return api_error(status.HTTP_400_BAD_REQUEST, 'Bad permission')
if path == '/':
shared_repo = repo
else:
try:
sub_repo = self.get_sub_repo_by_path(request, repo, path)
if sub_repo:
shared_repo = sub_repo
else:
return api_error(status.HTTP_400_BAD_REQUEST, 'No sub repo found')
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Failed to get sub repo')
if shared_to_user:
shared_to = request.GET.get('username')
if shared_to is None or not is_valid_username(shared_to):
return api_error(status.HTTP_400_BAD_REQUEST, 'Bad username.')
try:
User.objects.get(email=shared_to)
except User.DoesNotExist:
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid user, should be registered')
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.org_set_share_permission(
org_id, shared_repo.id, username, shared_to, permission)
else:
seafile_api.set_share_permission(shared_repo.id, username,
shared_to, permission)
send_perm_audit_msg('modify-repo-perm', username, shared_to,
repo_id, path, permission)
if shared_to_group:
gid = request.GET.get('group_id')
try:
gid = int(gid)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST, 'Bad group id: %s' % gid)
group = seaserv.get_group(gid)
if not group:
return api_error(status.HTTP_400_BAD_REQUEST, 'Group not found: %s' % gid)
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.set_org_group_repo_permission(
org_id, gid, shared_repo.id, permission)
else:
seafile_api.set_group_repo_permission(gid, shared_repo.id,
permission)
send_perm_audit_msg('modify-repo-perm', username, gid,
repo_id, path, permission)
return HttpResponse(json.dumps({'success': True}), status=200,
content_type=json_content_type)
def put(self, request, repo_id, format=None):
username = request.user.username
repo = seafile_api.get_repo(repo_id)
if not repo:
return api_error(status.HTTP_400_BAD_REQUEST, 'Repo not found.')
path = request.GET.get('p', '/')
if seafile_api.get_dir_id_by_path(repo.id, path) is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Directory not found.')
if username != self.get_repo_owner(request, repo_id):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
if path != '/':
try:
sub_repo = self.get_or_create_sub_repo_by_path(request, repo, path)
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Failed to get sub repo')
else:
sub_repo = None
share_type = request.DATA.get('share_type')
if share_type != 'user' and share_type != 'group':
return api_error(status.HTTP_400_BAD_REQUEST, 'Bad share type')
permission = request.DATA.get('permission', 'r')
if permission not in ['r', 'rw']:
return api_error(status.HTTP_400_BAD_REQUEST, 'Bad permission')
shared_repo = repo if path == '/' else sub_repo
result = {}
result['failed'] = []
result['success'] = []
if share_type == 'user':
share_to_users = request.DATA.getlist('username')
for to_user in share_to_users:
if not is_valid_username(to_user):
result['failed'].append({
'email': to_user,
'error_msg': 'username invalid.'
})
continue
try:
User.objects.get(email=to_user)
except User.DoesNotExist:
result['failed'].append({
'email': to_user,
'error_msg': 'User %s not found.' % to_user
})
continue
try:
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.org_add_share(
org_id, shared_repo.id, username, to_user,
permission)
else:
seafile_api.share_repo(shared_repo.id, username,
to_user, permission)
# send a signal when sharing repo successful
share_repo_to_user_successful.send(sender=None,
from_user=username,
to_user=to_user,
repo=shared_repo)
result['success'].append({
"share_type": "user",
"user_info": {
"name": to_user,
"nickname": email2nickname(to_user),
},
"permission": permission
})
send_perm_audit_msg('add-repo-perm', username, to_user,
repo_id, path, permission)
except SearpcError as e:
logger.error(e)
result['failed'].append({
'email': to_user,
'error_msg': 'Internal Server Error'
})
continue
if share_type == 'group':
group_ids = request.DATA.getlist('group_id')
for gid in group_ids:
try:
gid = int(gid)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST, 'Bad group id: %s' % gid)
group = seaserv.get_group(gid)
if not group:
return api_error(status.HTTP_400_BAD_REQUEST, 'Group not found: %s' % gid)
try:
if is_org_context(request):
org_id = request.user.org.org_id
seafile_api.add_org_group_repo(shared_repo.repo_id,
org_id, gid, username,
permission)
else:
seafile_api.set_group_repo(shared_repo.repo_id, gid,
username, permission)
result['success'].append({
"share_type": "group",
"group_info": {
"id": gid,
"name": group.group_name,
},
"permission": permission
})
send_perm_audit_msg('add-repo-perm', username, gid,
repo_id, path, permission)
except SearpcError as e:
logger.error(e)
result['failed'].append({
'group_name': group.group_name,
'error_msg': 'Internal Server Error'
})
continue
return HttpResponse(json.dumps(result),
status=200, content_type=json_content_type)
def delete(self, request, repo_id, format=None):
username = request.user.username
repo = seafile_api.get_repo(repo_id)
if not repo:
return api_error(status.HTTP_400_BAD_REQUEST, 'Repo not found.')
path = request.GET.get('p', '/')
if seafile_api.get_dir_id_by_path(repo.id, path) is None:
return api_error(status.HTTP_400_BAD_REQUEST, 'Directory not found.')
if username != self.get_repo_owner(request, repo_id):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
shared_to_user, shared_to_group = self.handle_shared_to_args(request)
if path == '/':
shared_repo = repo
else:
try:
sub_repo = self.get_sub_repo_by_path(request, repo, path)
if sub_repo:
shared_repo = sub_repo
else:
return api_error(status.HTTP_400_BAD_REQUEST, 'No sub repo found')
except SearpcError as e:
logger.error(e)
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Failed to get sub repo')
if shared_to_user:
shared_to = request.GET.get('username')
if shared_to is None or not is_valid_username(shared_to):
return api_error(status.HTTP_400_BAD_REQUEST, 'Bad argument.')
try:
User.objects.get(email=shared_to)
except User.DoesNotExist:
return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid user, should be registered')
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.seafserv_threaded_rpc.org_remove_share(
org_id, shared_repo.id, username, shared_to)
else:
seaserv.remove_share(shared_repo.id, username, shared_to)
permission = seafile_api.check_permission_by_path(repo.id, path,
shared_to)
send_perm_audit_msg('delete-repo-perm', username, shared_to,
repo_id, path, permission)
if shared_to_group:
group_id = request.GET.get('group_id')
try:
group_id = int(group_id)
except ValueError:
return api_error(status.HTTP_400_BAD_REQUEST, 'Bad group id')
# hacky way to get group repo permission
permission = ''
for e in seafile_api.list_repo_shared_group(username, shared_repo.id):
if e.group_id == group_id:
permission = e.perm
break
if is_org_context(request):
org_id = request.user.org.org_id
seaserv.del_org_group_repo(shared_repo.id, org_id, group_id)
else:
seafile_api.unset_group_repo(shared_repo.id, group_id, username)
send_perm_audit_msg('delete-repo-perm', username, group_id,
repo_id, path, permission)
return HttpResponse(json.dumps({'success': True}), status=200,
content_type=json_content_type)
<file_sep>/seahub/group/templates/group/discussion_list.html
{% load i18n seahub_tags avatar_tags%}
{% load url from future %}
{# for file/dir 'discuss to grp' #}
{% for msg in messages %}
<li class="msg ovhd" data-id="{{msg.id}}">
<a class="pic fleft" href="{% url 'user_profile' msg.from_email %}">{% avatar msg.from_email 48 %}</a>
<div class="txt">
<div class="msg-main">
<a href="{% url 'user_profile' msg.from_email %}">{{ msg.from_email|email2nickname }}</a>
<span class="time">{{ msg.timestamp|translate_seahub_time }}</span>
<p class="msg-con">{{ msg.message|seahub_urlize|find_at|linebreaksbr }}</p>
<span class="say"></span>
</div>
<div class="msg-op">
<div class="replies-op{% if msg.reply_cnt < 4 %} hide{% endif %}" data-rstatus="hide">
<span class="unfold-replies">{% blocktrans with amount=msg.reply_cnt %}{{ amount }} replies{% endblocktrans %}</span>
<span class="fold-replies hide">{% trans "Hide replies" %}</span>
</div>
{% if msg.reply_cnt == 0 %}
<ul class="reply-list hide"></ul>
{% else %}
<ul class="reply-list">
{% for r in msg.replies %}
<li class="reply w100 ovhd">
{% with id=r.from_email name=r.from_email|email2nickname %}
<a href="{% url 'user_profile' id %}" class="pic fleft">{% avatar r.from_email 28 %}</a>
<div class="txt">
<a href="{% url 'user_profile' id %}">{{ name }}</a>
<span class="time">{{ r.timestamp|translate_seahub_time }}</span>
<span class="reply-at op vh" data="{{ name }}">{% trans 'Reply' %}</span>
<p class="reply-con">{{ r.message|seahub_urlize|find_at|linebreaksbr }}</p>
</div>
{% endwith %}
</li>
{% endfor %}
</ul>
{% endif %}
<form action="" method="post" class="reply-form">
<textarea placeholder="{% trans "Add a reply..." %}" name="message" class="reply-input"></textarea>
<p class="error hide">{% trans "It can not be blank and should be no more than 2048 characters." %}</p>
<button type="submit" class="reply-submit hide">{% trans "Submit" %}</button>
<button type="button" class="reply-cancel hide">{% trans "Cancel" %}</button>
</form>
</div>
</div>
</li>
{% endfor %}
| 94d41c888bf52acf75646b03851ba5ee7b42a1f3 | [
"SQL",
"HTML",
"JavaScript",
"Markdown",
"Makefile",
"Python",
"Text",
"Shell"
] | 131 | Python | Open365/seahub | 6f1598be7793a8d4d0510a6559f9ec364f51cfab | 0f5337f0137c41c39e65045ba8d032131de84004 |
refs/heads/master | <repo_name>emreinan34/NoHandicApp_server<file_sep>/CrunchifyTutorials/src/model/ProjectManager.java
package model;
import java.sql.Connection;
import java.util.ArrayList;
import java.sql.ResultSet;
import dao.Database;
import dao.Project;
import dto.AttributeValidation;
import dto.Greeting;
import dto.OperationalCategoryExtended;
import dto.User;
import dto.Violation;
public class ProjectManager {
public ArrayList<Greeting> GetGreetings() throws Exception {
ArrayList<Greeting> greetings = null;
try {
Database database = new Database();
Connection connection = database.Get_Connection();
Project project = new Project();
greetings = project.GetGreetings(connection);
} catch (Exception e) {
throw e;
}
return greetings;
}
public ArrayList<Greeting> GetSubcategories(String parentCategoryId) throws Exception {
ArrayList<Greeting> greetings = null;
try {
Database database = new Database();
Connection connection = database.Get_Connection();
Project project = new Project();
greetings = project.GetSubcategories(connection,parentCategoryId);
} catch (Exception e) {
throw e;
}
return greetings;
}
public ArrayList<Greeting> GetAttributes(String parentCategoryId) throws Exception {
ArrayList<Greeting> greetings = null;
try {
Database database = new Database();
Connection connection = database.Get_Connection();
Project project = new Project();
greetings = project.GetAttributes(connection,parentCategoryId);
} catch (Exception e) {
throw e;
}
return greetings;
}
public void RegisterUser(User newUser) throws Exception {
try {
Database database = new Database();
Connection connection = database.Get_Connection();
Project project = new Project();
// ResultSet rs=project.RegisterUser(connection,newUser);
project.RegisterUser(connection,newUser);
} catch (Exception e) {
throw e;
}
}
public User GetUserWithFullData(User user) {
try {
Database database = new Database();
Connection connection = database.Get_Connection();
Project project = new Project();
user=project.GetUserWithFullData(connection,user);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
public Boolean userExists(User newUser) {
Boolean userExists=null;
try {
Database database = new Database();
Connection connection = database.Get_Connection();
Project project = new Project();
userExists=project.userExists(connection,newUser);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return userExists;
}
public Boolean ValidateViolationAttribute(AttributeValidation attributeValidationObject) {
Boolean attributeValueValid=null;
try {
Database database = new Database();
Connection connection = database.Get_Connection();
Project project = new Project();
attributeValueValid=project.ValidateViolationAttribute(connection,attributeValidationObject);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return attributeValueValid;
}
public Boolean PersistViolation(Violation violation) throws Exception {
Boolean violationPersistenceSuccessful=null;
try {
Database database = new Database();
Connection connection = database.Get_Connection();
Project project = new Project();
violationPersistenceSuccessful=project.PersistViolation(connection,violation);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return violationPersistenceSuccessful;
}
public ArrayList<OperationalCategoryExtended> GetOperationalCategoriesExtended(int categoryID) throws Exception {
ArrayList<OperationalCategoryExtended> operationalCategoriesExtended = null;
try {
Database database = new Database();
Connection connection = database.Get_Connection();
Project project = new Project();
operationalCategoriesExtended = project.GetOperationalCategoriesExtended(connection,categoryID);
} catch (Exception e) {
throw e;
}
return operationalCategoriesExtended;
}
}<file_sep>/CrunchifyTutorials/src/dao/Project.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import dto.AttributeValidation;
import dto.Greeting;
import dto.OperationalAttribute;
import dto.OperationalCategory;
import dto.OperationalCategoryExtended;
import dto.User;
import dto.Violation;
public class Project {
public ArrayList<Greeting> GetGreetings(Connection connection) throws Exception {
ArrayList<Greeting> greetingData = new ArrayList<Greeting>();
try {
PreparedStatement ps = connection.prepareStatement("SELECT id,description,topic FROM categories where description='0' ORDER BY id");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Greeting greeting = new Greeting();
greeting.setId(rs.getString("id"));
greeting.setDescription(rs.getString("description"));
greeting.setTopic(rs.getString("topic"));
greetingData.add(greeting);
}
return greetingData;
} catch (Exception e) {
throw e;
}
}
public ArrayList<Greeting> GetSubcategories(Connection connection,String ParentCategoryId) throws Exception {
ArrayList<Greeting> greetingData = new ArrayList<Greeting>();
try {
String sqlString="";
StringBuilder builder=new StringBuilder();
builder.append("SELECT id,description,topic FROM categories where description=");
builder.append(ParentCategoryId);
builder.append(" ORDER BY id");
sqlString=builder.toString();
System.out.println(sqlString);
PreparedStatement ps = connection.prepareStatement(sqlString);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Greeting greeting = new Greeting();
greeting.setId(rs.getString("id"));
greeting.setDescription(rs.getString("description"));
greeting.setTopic(rs.getString("topic"));
greetingData.add(greeting);
}
return greetingData;
} catch (Exception e) {
throw e;
}
}
public ArrayList<Greeting> GetAttributes(Connection connection, String parentCategoryId) throws Exception {
ArrayList<Greeting> greetingData = new ArrayList<Greeting>();
try {
String sqlString="";
StringBuilder builder=new StringBuilder();
builder.append("SELECT attributeID,name,parentCategoryID FROM attributes where parentCategoryID=");
builder.append(parentCategoryId);
builder.append(" ORDER BY attributeID");
sqlString=builder.toString();
System.out.println(sqlString);
PreparedStatement ps = connection.prepareStatement(sqlString);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Greeting greeting = new Greeting();
greeting.setId(rs.getString("attributeID"));
greeting.setTopic(rs.getString("name"));
greeting.setDescription(rs.getString("parentCategoryID"));
greetingData.add(greeting);
}
return greetingData;
} catch (Exception e) {
throw e;
}
}
public void RegisterUser(Connection connection, User newUser) throws SQLException {
String username;
String password;
username=newUser.getUserName();
password=<PASSWORD>();
String sqlString="";
StringBuilder builder=new StringBuilder();
builder.append("INSERT INTO studentdb.users (username, password) VALUES ('");
builder.append(username);
builder.append("', '");
builder.append(password);
builder.append("')");
sqlString=builder.toString();
PreparedStatement ps;
try {
ps = connection.prepareStatement(sqlString);
ps.executeUpdate();
System.out.println("registration OK");
// return rs;
} catch (SQLException e) {
// TODO Auto-generated catch block
throw e;
}
}
public User GetUserWithFullData(Connection connection, User user) throws Exception {
try {
String username=user.getUserName();
String sqlString="";
StringBuilder builder=new StringBuilder();
builder.append("SELECT userID,username,password FROM users where username='");
builder.append(username);
builder.append("'");
sqlString=builder.toString();
// System.out.println(sqlString);
PreparedStatement ps = connection.prepareStatement(sqlString);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
user.setUserID(rs.getLong("userID"));
user.setUserName(rs.getString("username"));
user.setPassword(rs.getString("<PASSWORD>"));
}
return user;
} catch (Exception e) {
throw e;
}
}
public Boolean userExists(Connection connection, User newUser) throws Exception {
try {
String username=newUser.getUserName();
String sqlString="";
StringBuilder builder=new StringBuilder();
builder.append("SELECT userID FROM users where username='");
builder.append(username);
builder.append("'");
sqlString=builder.toString();
PreparedStatement ps = connection.prepareStatement(sqlString);
ResultSet rs = ps.executeQuery();
int rowCount=0;
if (rs!=null){
rs.beforeFirst();
rs.last();
rowCount=rs.getRow();
}
if (rowCount==0){
return false;}
else{
return true;}
} catch (Exception e) {
throw e;
}
}
public Boolean ValidateViolationAttribute(Connection connection, AttributeValidation attributeValidationObject) throws Exception {
try {
String sqlString="";
StringBuilder builder=new StringBuilder();
builder.append("SELECT minDeger, maxDeger, unit, validationMethod FROM attributes where attributeID=");
builder.append(attributeValidationObject.getAttributeID());
sqlString=builder.toString();
PreparedStatement ps = connection.prepareStatement(sqlString);
ResultSet rs = ps.executeQuery();
rs.first();
Double minValue=rs.getDouble("minDeger");
Double maxValue=rs.getDouble("maxDeger");
String unit=rs.getString("unit");
String validationMethod=rs.getString("validationMethod");
Double valueToCompare=Double.parseDouble(attributeValidationObject.getValue());
if(attributeValidationObject.getUnit().equals("m")){
valueToCompare=1000*valueToCompare;
}
else if(attributeValidationObject.getUnit().equals("cm")){
valueToCompare=100*valueToCompare;
}
else if(attributeValidationObject.getUnit().equals("mm")){
//do nothing.
}
else if(attributeValidationObject.getUnit().equals("--")){
//do nothing.
}
if(validationMethod.equals("Max")){
if(valueToCompare>maxValue){return false;}
}
else if(validationMethod.equals("Min")){
if(valueToCompare<minValue){return false;}
}
else if (validationMethod.equals("Between")){
if(valueToCompare>maxValue || valueToCompare<minValue){return false;}
}
return true;
} catch (Exception e) {
throw e;
}
}
public Boolean PersistViolation(Connection connection, Violation violation) throws SQLException {
String sqlString="";
StringBuilder builder=new StringBuilder();
builder.append("INSERT into violations (state,stateChangeCounter,userID) values (1,1,");
builder.append(violation.getUserID());
builder.append(")");
sqlString=builder.toString();
PreparedStatement ps;
int violationID;
try {
ps = connection.prepareStatement(sqlString);
ps.executeUpdate();
sqlString="SELECT LAST_INSERT_ID()";
ps = connection.prepareStatement(sqlString);
ResultSet rs = ps.executeQuery();
rs.first();
violationID=rs.getInt("LAST_INSERT_ID()");
System.out.println("violation persistence OK, violationID: " + violationID);
} catch (SQLException e) {
// TODO Auto-generated catch block
throw e;
}
OperationalCategory operationalCategory=violation.getMyCategory();
builder.setLength(0);
builder.append("INSERT into operationalcategories (violationID,categoryID,description) values (");
builder.append(violationID);
builder.append(", ");
builder.append(violation.getMyCategory().getCategoryID());
builder.append(", '");
builder.append(violation.getMyCategory().getDescription());
builder.append("')");
sqlString=builder.toString();
int operationalCategoryID;
try {
ps = connection.prepareStatement(sqlString);
ps.executeUpdate();
sqlString="SELECT LAST_INSERT_ID()";
ps = connection.prepareStatement(sqlString);
ResultSet rs = ps.executeQuery();
rs.first();
operationalCategoryID=rs.getInt("LAST_INSERT_ID()");
System.out.println("category persistence OK, operationalCategoryID: " + operationalCategoryID);
} catch (SQLException e) {
// TODO Auto-generated catch block
throw e;
}
Map<Integer, OperationalAttribute> operationalAttributes=operationalCategory.getMapOfOperationalAttributes();
try {
for (OperationalAttribute operationalAttribute:operationalAttributes.values()){
builder.setLength(0);
builder.append("INSERT into operationalattributes (operationalCategoryID,attributeID,description,value,unit) values (");
builder.append(operationalCategoryID);
builder.append(", ");
builder.append(operationalAttribute.getAttributeID());
builder.append(", '");
builder.append(operationalAttribute.getDescription());
builder.append("', ");
builder.append(operationalAttribute.getValue());
builder.append(", '");
builder.append(operationalAttribute.getUnit());
builder.append("')");
sqlString=builder.toString();
ps = connection.prepareStatement(sqlString);
ps.executeUpdate();
sqlString="SELECT LAST_INSERT_ID()";
ps = connection.prepareStatement(sqlString);
ResultSet rs = ps.executeQuery();
rs.first();
int operationalAttributeID=rs.getInt("LAST_INSERT_ID()");
System.out.println("attribute persistence OK, operationalAttributeID: " + operationalAttributeID);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
throw e;
}
return true;
}
public ArrayList<OperationalCategoryExtended> GetOperationalCategoriesExtended(Connection connection, int categoryID) throws Exception {
ArrayList<OperationalCategoryExtended> operationalCategoriesExtended = new ArrayList<OperationalCategoryExtended>();
List<Integer> categoryIDs=new ArrayList<Integer>();
try {
PreparedStatement ps;
ResultSet rs;
String sqlString="";
if (categoryID==0){
sqlString="SELECT operationalCategoryID, violationID, categoryID, oc.description as violationDesc, topic, c.description as parentCategoryID FROM operationalcategories oc, categories c where oc.categoryID=c.id";
}
else{
StringBuilder builder=new StringBuilder();
builder.append("SELECT description FROM categories where id=");
builder.append(categoryID);
sqlString=builder.toString();
System.out.println(sqlString);
ps = connection.prepareStatement(sqlString);
rs = ps.executeQuery();
if (rs.next()) {
int parentCategoryID=rs.getInt("description");
if (parentCategoryID!=0) {
categoryIDs.add(categoryID);
}
}
builder.setLength(0);
builder.append("SELECT id FROM categories where description=");
builder.append(categoryID);
sqlString=builder.toString();
System.out.println(sqlString);
ps = connection.prepareStatement(sqlString);
rs = ps.executeQuery();
while (rs.next()) {
categoryID=rs.getInt("id");
categoryIDs.add(categoryID);
builder.setLength(0);
builder.append("SELECT id FROM categories where description=");
builder.append(categoryID);
sqlString=builder.toString();
System.out.println(sqlString);
ps = connection.prepareStatement(sqlString);
ResultSet rs2 = ps.executeQuery();
while (rs2.next()) {
categoryID=rs2.getInt("id");
categoryIDs.add(categoryID);
builder.setLength(0);
builder.append("SELECT id FROM categories where description=");
builder.append(categoryID);
sqlString=builder.toString();
System.out.println(sqlString);
ps = connection.prepareStatement(sqlString);
ResultSet rs3 = ps.executeQuery();
while (rs3.next()) {
categoryID=rs3.getInt("id");
categoryIDs.add(categoryID);
builder.setLength(0);
builder.append("SELECT id FROM categories where description=");
builder.append(categoryID);
sqlString=builder.toString();
System.out.println(sqlString);
ps = connection.prepareStatement(sqlString);
}
}
}
builder.setLength(0);
builder.append("SELECT operationalCategoryID, violationID, categoryID, oc.description as violationDesc, topic, c.description as parentCategoryID FROM operationalcategories oc, categories c where oc.categoryID=c.id and c.id in (");
String prefix = "";
for(Iterator<Integer> i = categoryIDs.iterator(); i.hasNext(); ) {
Integer item = i.next();
builder.append(prefix);
prefix=", ";
builder.append(item);
}
builder.append(")");
sqlString=builder.toString();
}
System.out.println(sqlString);
ps = connection.prepareStatement(sqlString);
rs = ps.executeQuery();
while (rs.next()) {
operationalCategoriesExtended.add(new OperationalCategoryExtended(rs.getInt("parentCategoryID"),rs.getString("topic"),rs.getString("violationDesc"),rs.getInt("categoryID"),rs.getInt("violationID"),rs.getInt("operationalCategoryID")));
}
return operationalCategoriesExtended;
} catch (Exception e) {
throw e;
}
}
}<file_sep>/CrunchifyTutorials/src/com/crunchify/tutorials/CrunchifyRESTService.java
package com.crunchify.tutorials;
/**
* @author Crunchify.com
*
*/
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.print.attribute.standard.Media;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONException;
import org.json.JSONObject;
@Path("/")
public class CrunchifyRESTService {
@POST
@Path("/crunchifyService")
@Consumes(MediaType.APPLICATION_JSON)
public Response crunchifyREST(InputStream incomingData) {
StringBuilder crunchifyBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
crunchifyBuilder.append(line);
}
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
System.out.println("Data Received: " + crunchifyBuilder.toString());
// return HTTP response 200 in case of success
return Response.status(200).entity(crunchifyBuilder.toString()).build();
}
@GET
@Path("/verify")
@Produces(MediaType.TEXT_PLAIN)
public Response verifyRESTService(InputStream incomingData) throws JSONException {
String result = "CrunchifyRESTService Successfully started..";
// return HTTP response 200 in case of success
return Response.status(200).entity(result).build();
}
@GET
@Path("/verify2")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response verifyRESTService2(InputStream incomingData) throws IOException, JSONException {
String string = "";
try {
// Step1: Let's 1st read file from fileSystem
// Change CrunchifyJSON.txt path here
InputStream crunchifyInputStream = new FileInputStream("c:\\CrunchifyJSON.txt");
//InputStream crunchifyInputStream=incomingData;
InputStreamReader crunchifyReader = new InputStreamReader(crunchifyInputStream);
BufferedReader br = new BufferedReader(crunchifyReader);
String line;
while ((line = br.readLine()) != null) {
string += line + "\n";
}
JSONObject jsonObject = new JSONObject(string);
// return HTTP response 200 in case of success
return Response.status(200).entity(jsonObject.toString()).build();
}
finally {
System.out.println("Error or not error while sending JSON data");
}
}
@GET
@Path("/verify3")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response verifyRESTService3(InputStream incomingData) throws IOException, JSONException {
String string = "";
try {
// Step1: Let's 1st read file from fileSystem
// Change CrunchifyJSON.txt path here
InputStream crunchifyInputStream = new FileInputStream("c:\\MyApplication3JSON.txt");
//InputStream crunchifyInputStream=incomingData;
InputStreamReader crunchifyReader = new InputStreamReader(crunchifyInputStream);
BufferedReader br = new BufferedReader(crunchifyReader);
String line;
while ((line = br.readLine()) != null) {
string += line + "\n";
}
JSONObject jsonObject = new JSONObject(string);
// return HTTP response 200 in case of success
return Response.status(200).entity(jsonObject.toString()).build();
}
finally {
System.out.println("Error or not error while sending JSON data");
}
}
@GET
@Path("/verify4")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response verifyRESTService4(InputStream incomingData) throws IOException, JSONException {
String string = "";
try {
// Step1: Let's 1st read file from fileSystem
// Change CrunchifyJSON.txt path here
InputStream crunchifyInputStream = new FileInputStream("c:\\MyApplication3JSON4.txt");
//InputStream crunchifyInputStream=incomingData;
InputStreamReader crunchifyReader = new InputStreamReader(crunchifyInputStream);
BufferedReader br = new BufferedReader(crunchifyReader);
String line;
while ((line = br.readLine()) != null) {
string += line + "\n";
}
JSONObject jsonObject = new JSONObject(string);
// return HTTP response 200 in case of success
return Response.status(200).entity(jsonObject.toString()).build();
}
finally {
System.out.println("Error or not error while sending JSON data");
}
}
} | c7a5b7c4f0729f06803f599fd4bd6196518293e6 | [
"Java"
] | 3 | Java | emreinan34/NoHandicApp_server | 776e049c32e27b34ff7de025601ba401c100ce8e | b6ae3764ce8cfaf50d83b0cb0aeedb1cb2a562ba |
refs/heads/master | <file_sep>"""Utility functions for writing Webathena-based APIs in Bottle"""
import base64
import ccaches
import json
import moira
import os
import tempfile
from bottle import request
MOIRA_TIME_FORMAT = "%d-%b-%Y %H:%M:%S"
def webathena(function):
"""
A decorator that loads a Kerberos ticket from the base64 encoded "webathena"
url paramater and stores it in a ccache for the duration of request
processing. This allows programs and libraries such as python-moira to
autheticate.
Selected code borrowed from davidben's shellinabox example in the Webathena
source tree. https://github.com/davidben/webathena.
"""
def wrapped(*args, **kwargs):
# Extract credential from request
ticket_data = request.query["webathena"]
if not ticket_data:
raise KeyError("Missing Webathena ticket!")
credential = json.loads(base64.b64decode(ticket_data))
with tempfile.NamedTemporaryFile(prefix="webathena_ccache_") as ccache:
# Write credentials to a temporary krb5 ccache
ccache.write(ccaches.make_ccache(credential))
ccache.flush()
os.environ["KRB5CCNAME"] = ccache.name
# Run the inner function while in the with..as; return
return function(*args, **kwargs)
return wrapped
def moira_auth(client_name):
"""
A decorator that opens an authenticated Moira session before the wrapped
function is executed. Goes well with @webathena, above.
"""
def wrapper(function):
def wrapped(*args, **kwargs):
moira.connect()
moira.auth(client_name)
return function(*args, **kwargs)
return wrapped
return wrapper
def json_api(function):
"""
A decorator that automatically JSON-encodes output.
"""
def wrapped(*args, **kwargs):
result = function(*args, **kwargs)
return json.dumps(result)
return wrapped
<file_sep>#!/usr/bin/env python2
#
# Webathena-Moira Post Office Box interface, a mostly-RESTful API.
#
# Background:
#
# All actions are authenticated. Every request must include a cookie (in this
# case, named "mailto-session") containing the JSON-encoded value of the
# "session" attribute returned by Webathena. Inside of this credential should
# reside a Moira ticket (moira/mo<EMAIL>).
#
# Endpoints:
#
# GET /<user>
# List <user>'s post office boxes, including both current ones and disabled ones
# that we can find out about. Return the pobox status as a dictionary:
# - boxes: a list of dictionaries, each containing:
# - address: the pobox represented as an email address
# - type: the type of box, either "IMAP", "EXCHANGE" or "SMTP"
# - enabled: a boolean value, true iff mail is being sent to this pobox
# - modtime: the time of the last modification, in ISO 8601 format
# - modby: the username of the person who performed the modification
# - modwith: the tool used to modify the settings
#
# PUT /<user>/<address>
# Set <address> as <user>'s only post office box. Return the updated list of
# poboxes in the same format as the GET call.
#
# PUT /<user>/<internal>/<external>
# Set <internal> as <user>'s internal post office box and <external> as the
# external forwarder. The internal pobox must be of type IMAP or EXCHANGE, and
# the external pobox must be of type SMTP. Return the updated list of poboxes in
# the same format as the GET call.
#
# PUT /<user>/reset
# Reset <user>'s post office box settings using the set_pobox_pop query. Return
# the updated list of poboxes in the same format as the GET call.
#
import moira
import os
import re
from bottle import get, put, delete, abort, request
from bottle_webathena import *
from datetime import datetime
APP_ROOT = os.path.abspath(os.path.dirname(__file__))
MN = "mailto" # this application's name, for Moira modwith
@get("/<user>")
@webathena
@moira_auth(MN)
@json_api
def get_poboxes(user):
return pobox_status(user)
@put("/<user>/reset")
@webathena
@moira_auth(MN)
@json_api
def reset(user):
moira.query("set_pobox_pop", user)
return pobox_status(user)
@put("/<user>/<address>")
@webathena
@moira_auth(MN)
@json_api
def put_address(user, address):
mtype, box = type_and_box(address)
moira.query("set_pobox", user, mtype, box)
return pobox_status(user)
@put("/<user>/<internal>/<external>")
@webathena
@moira_auth(MN)
@json_api
def put_split_addresses(user, internal, external):
internal_mtype, internal_box = type_and_box(internal)
if internal_mtype == "SMTP":
abort(400, "Internal address cannot be type SMTP.")
external_mtype, external_box = type_and_box(external)
if external_mtype != "SMTP":
abort(400, "External address must be type SMTP.")
moira.query("set_pobox", user, internal_mtype, internal_box)
moira.query("set_pobox", user, "SPLIT", external_box)
return pobox_status(user)
def pobox_status(user):
# Run Moira Query
try:
boxinfo = moira.query("get_pobox", user)[0]
except moira.MoiraException as e:
if len(e.args) >= 2 and e[1].lower() == "no such user":
abort(404, e[1])
raise e
# Search Moira
moira_addresses = boxinfo["address"].split(", ")
exchange = []
imap = []
external = []
for address in moira_addresses:
# Categorize as Exchange, IMAP or External
if re.search("@EXCHANGE.MIT.EDU$", address, re.IGNORECASE):
exchange.append(address)
elif re.search("@PO\d+.MIT.EDU$", address, re.IGNORECASE):
imap.append(address)
else:
external.append(address)
# Construct Response
boxes = []
for addresses, mtype in ((exchange, "EXCHANGE"), (imap, "IMAP"),
(external, "SMTP")):
for address in addresses:
boxes.append({"address": address,
"type": mtype,
"enabled": True})
isotime = datetime.strptime(boxinfo["modtime"], MOIRA_TIME_FORMAT) \
.isoformat()
return {"boxes": boxes,
"modtime": isotime,
"modwith": boxinfo["modwith"],
"modby": boxinfo["modby"]}
def type_and_box(address):
"""Return the type and box associated with an email address."""
if re.search("@EXCHANGE.MIT.EDU$", address, re.IGNORECASE):
return "EXCHANGE", "EXCHANGE.MIT.EDU"
elif re.search("@PO\d+.MIT.EDU$", address, re.IGNORECASE):
username = address.split("@")[0]
return "IMAP", "%s.po" % username
else:
return "SMTP", address
if __name__ == "__main__":
import bottle
from flup.server.fcgi import WSGIServer
bottle.debug(True) # TODO: disable this
app = bottle.default_app()
WSGIServer(app).run()
<file_sep>bottle
flup
#python-moira
# https://github.com/ebroder/python-moira
<file_sep>mailto
======
`mailto` is a web application that allows Athena users to view and change their
mail forwarding settings. It's like `chpobox` for the web!
* Use it (MIT only): https://mailto.mit.edu/
* Preview: https://mailto.mit.edu/#mockup
| deecbeead68f3c98d064f8065be75a7c47a743a6 | [
"Markdown",
"Python",
"Text"
] | 4 | Python | btidor/mailto | fbc3dee3a9d4f0aaf12c3ddf85b0cb1d455b444b | 42e629df71e147e1a0306bd7dd970a4e4636421c |
refs/heads/master | <repo_name>mc0514/kerasEMG<file_sep>/kerasEMG.py
import scipy.io as sio
import numpy as np
from sklearn.cross_validation import train_test_split
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.core import Dropout
from keras.utils import np_utils
NUMBER_OF_FEATURES=4
NUMBER_OF_CLASSES=6
def loaddata(dir):
dataset=sio.loadmat(dir)
palm_data=(abs(dataset['palm_ch1'])+abs(dataset['palm_ch2']))/2.00000
lat_data=(abs(dataset['lat_ch1'])+abs(dataset['lat_ch2']))/2.00000
tip_data=(abs(dataset['tip_ch1'])+abs(dataset['tip_ch2']))/2.00000
spher_data=(abs(dataset['spher_ch1'])+abs(dataset['spher_ch2']))/2.00000
hook_data=(abs(dataset['hook_ch1'])+abs(dataset['hook_ch2']))/2.00000
cyl_data=(abs(dataset['cyl_ch1'])+abs(dataset['cyl_ch2']))/2.00000
#print cyl_data.shape
return palm_data, lat_data, tip_data, spher_data, hook_data, cyl_data
def calc_IEMG(raw_data):
temp=0
IEMG=[]
timesteps, length=raw_data.shape
for i in range(timesteps):
for j in range(length):
temp=temp+raw_data[i,j]
IEMG.append(temp)
temp=0
return IEMG
def calc_SSC(raw_data):
temp=0
SSC=[]
timesteps, length=raw_data.shape
for i in range(timesteps):
for j in range(length-2):
if((raw_data[i,j+1]<raw_data[i,j+2])and(raw_data[i,j+1]<raw_data[i,j]))or((raw_data[i,j+1]>raw_data[i,j+2])and(raw_data[i,j+1]>raw_data[i,j])):
temp=temp+1
SSC.append(temp)
temp=0
return SSC
def calc_CZ(raw_data):
temp=0
CZ=[]
timesteps, length=raw_data.shape
for i in range(timesteps):
theta=0.025*(raw_data[i,:].max()-raw_data[i,:].min())
for j in range(length-1):
if(raw_data[i,j]>theta and raw_data[i,j+1]<theta)or(raw_data[i,j]<theta and raw_data[i,j+1]>theta):
temp=temp+1
CZ.append(temp)
temp=0
return CZ
def calc_WL(raw_data):
temp=0
WL=[]
timesteps, length=raw_data.shape
for i in range(timesteps):
for j in range(length-1):
temp=temp+abs(raw_data[i,j+1]-raw_data[i,j])
WL.append(temp)
temp=0
return WL
def extractfeatures(raw_data):
timesteps=raw_data.shape[0]
features=[]
temp=[]
IEMG=calc_IEMG(raw_data)
CZ=calc_CZ(raw_data)
SSC=calc_SSC(raw_data)
WL=calc_WL(raw_data)
for i in range(timesteps):
temp.append(IEMG[i])
temp.append(CZ[i])
temp.append(SSC[i])
temp.append(WL[i])
features.append(temp)
temp=[]
return features
def combinfeatures(palm,lat,tip,hook,spher,cyl):
#combin=[]
y=[]
combin=np.append(palm,lat,axis=0)
combin=np.append(combin,tip,axis=0)
combin=np.append(combin,hook,axis=0)
combin=np.append(combin,spher,axis=0)
combin=np.append(combin,cyl,axis=0)
for i in range(np.shape(palm)[0]):
y.append(0)
for i in range(np.shape(lat)[0]):
y.append(1)
for i in range(np.shape(tip)[0]):
y.append(2)
for i in range(np.shape(hook)[0]):
y.append(3)
for i in range(np.shape(spher)[0]):
y.append(4)
for i in range(np.shape(cyl)[0]):
y.append(5)
return combin, y
def build_model(first_layer_neurons, second_layer_neurons,input_shape):
model = Sequential()
model.add(LSTM(first_layer_neurons, input_dim=NUMBER_OF_FEATURES, dropout_U=0.3))
model.add(Dense(second_layer_neurons))
model.add(Dropout(0.2))
model.add(Dense(NUMBER_OF_CLASSES, activation="softmax"))
#model.add(Dense(1, activation="softmax"))
model.compile(loss="categorical_crossentropy",
optimizer="adam",
metrics=["accuracy"])
return model
def main():
palm_data, lat_data, tip_data, spher_data, hook_data, cyl_data=loaddata('database1/female_3.mat')
palm_features=extractfeatures(palm_data)
lat_features=extractfeatures(lat_data)
tip_features=extractfeatures(tip_data)
hook_features=extractfeatures(hook_data)
spher_features=extractfeatures(spher_data)
cyl_features=extractfeatures(cyl_data)
x, y=combinfeatures(palm_features,lat_features,tip_features,hook_features,spher_features,cyl_features)
x=np.array(x).reshape((180,1,4))
y=np_utils.to_categorical(y, nb_classes=6)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33)
input_shape=x_train.shape[1:]
model = build_model(150, 100,input_shape)
print(model.summary())
model.fit(x_train, y_train, nb_epoch=200, batch_size=50, verbose=2)
scores = model.evaluate(x_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))
if __name__ == '__main__':
main()
| 318f51efb08e43b8f27a3aa966944743b62211a3 | [
"Python"
] | 1 | Python | mc0514/kerasEMG | 80da1e361dd1c2dd4808537f8278f5897d65f14c | d868ceb3c244a9e7d030f29238c5b345fa159da0 |
refs/heads/master | <repo_name>EricEon/mvc<file_sep>/Views/dashboard.view.php
<?php include 'header.php';
use Flux\Core\Helpers\Session;
?>
<div class="container">
<?php if(isset($_SESSION['message'])): ?>
<div class="alert alert-<?= $_SESSION['status'] ?>">
<p><?php Session::display()?></p>
</div>
<?php endif; ?>
<h3>WELCOME TO THE DASHBOARD</h3>
</div>
<?php include 'footer.php';?>
<file_sep>/Core/Database/QueryBuilder.php
<?php
namespace Flux\Core\Database;
use Flux\Core\Database\Connector as Db;
use Flux\Core\Helpers\Session;
class QueryBuilder implements DataQueryTrait
{
/**
* @var string $table
*/
public $table = '';
/**
* @var array $data
*/
public $data = [];
/**
* @var array $operators
*/
public $operators = ['=', '>', '<', '<=', '>=', 'LIKE'];
/**
* __construct.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Sunday, February 24th, 2019.
* @access public
* @param mixed $con Default: null
* @return void
*/
public function __construct($con = null)
{
// $pdo = new Connector();
$this->con = Db::connect();
}
/**
* table.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Sunday, February 24th, 2019.
* @access public
* @param string $table
* @return mixed
*/
public function table(String $table)
{
if (!is_string($table)) {
throw new \PDOException("Datatype must be of type String");
}
$this->table = $table;
return $this;
}
/**
* create.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Sunday, February 24th, 2019.
* @access public
* @param array $data
* @return void
*/
public function create(array $data)
{
$keys = [];
$values = [];
$prepKey = "";
$prepVal = array();
$email = $data['email'];
//var_dump($data);
if (!is_array($data) && empty($data)) {
$error = new \PDOException("Values passed must be of type array");
$error->getMessage();
}
/*
*The foreach loop splits the array given into key and value for each index.
* The keys are separated into a $keys array, the same is done to the values.
* A $prepKey array is used for the key binding needed by pdo for the data manipulation.
* A $prepVal array is used to store the $prepKey and values giving a :name => name Array.
*/
foreach ($data as $key => $value) {
$keys[] = $key;
$values[] = $value;
$prepKey = ":" . $key; //$prepKey is a variable that stores strings
$prepVal[$prepKey] = $value;
}
// var_dump($keys);
// var_dump($values);
// var_dump($prepVal);
/**
* Use implode not list to separate the array values into a string with a glue string joining them.
*/
$columns = implode(",", $keys);
$params = ":" . implode(",:", $keys);
// var_dump($columns);
// var_dump($params);
/**
* Resulting sql string should contain pdo named placeholder for values and normal string for the columns.
*/
$sql = "INSERT INTO {$this->table} ({$columns}) VALUES ({$params})";
// var_dump($sql);
//Prepare the sql statement for execution by pdo
$prep = $this->con->prepare($sql);
// var_dump($prep);
//Using foreach loop bind the values to their placeholders, represented by the key value pairs in the array.
foreach ($prepVal as $key => $value) {
$prep->bindValue($key, $value);
}
//$create;
try {
$create = $prep->execute();
Session::create('success', 'Data Saved!!');
return $create;
} catch (\Throwable $th) {
Session::create('danger', 'Unsuccessful Process');
}
}
/**
* where.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Saturday, March 9th, 2019.
* @access public
* @param string $column
* @param string $operator
* @param mixed $value
* @return array
*/
public function where(String $column, String $operator, $value)
{
$op = $this->isOperator($operator);
//if (!is_null($op)) {
$sql = "SELECT * FROM $this->table WHERE $column $op :$column";
//var_dump($value);
$prep = $this->con->prepare($sql);
//var_dump($prep);
$prep->bindValue(":$column",$value);
$prep->execute();
$result = $prep->fetchAll(2);
return $result;
//var_dump($result);
//}
}
/**
* isOperator.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Friday, March 8th, 2019.
* @access protected
* @param string $operator
* @return void
*/
protected function isOperator(String $operator)
{
try {
if (!is_string($operator)) {
throw new \TypeError();
} elseif (!in_array($operator, $this->operators, true)) {
throw new \Error("$operator is not a valid operation");
//$error->getMessage();
} else {
return $operator;
}
} catch (\Throwable $th) {
echo $th->getMessage();
}
}
}
<file_sep>/Controller/ActivationController.php
<?php
namespace Flux\Controller;
use Flux\Core\Http\Request;
use Flux\Controller\AuthController as Auth;
class ActivationController {
public function activate(){
Auth::activate(Request::all());
return view('activate');
}
}<file_sep>/Controller/RegistrationController.php
<?php
namespace Flux\Controller;
use Flux\Core\Http\Request;
use Flux\Controller\Controller;
use Flux\Controller\AuthController as Auth;
class RegistrationController extends Controller
{
public function register()
{
Auth::register('users',Request::all());
return view('register');
}
public function getActivateView($data){
return view('activate',compact('data'));
}
}<file_sep>/Views/index.view.php
<?php include 'header.php';
use Flux\Core\Helpers\Session;
?>
<div class="container">
<?php if(isset($_SESSION['message'])): ?>
<div class="alert alert-<?= $_SESSION['status'] ?>">
<p><?php Session::display()?></p>
</div>
<?php endif; ?>
<div class="row">
<div class="col">
<form action="/login" method="post">
<div class="form-group">
<label for="email">EMAIL</label>
<input type="text" name="email" id="email" required>
</div>
<div class="form-group">
<label for="password">PASSWORD</label>
<input type="<PASSWORD>" name="password" id="password" required>
</div>
<div class="form-group">
<input type="submit" value="Login" name="submit">
</div>
</form>
</div>
</div>
</div>
<?php include 'footer.php';?><file_sep>/Core/Database/Connection.php
<?php
return $mysql = array(
'db_driver' => 'mysql',
'db_host' => 'localhost',
'db_name' => 'loginoo',
'db_username' => 'root',
'db_password' => ''
);<file_sep>/Core/Database/Connector.php
<?php
namespace Flux\Core\Database;
use Flux\Helpers\FileLogger;
use Flux\Core\Helpers\Session;
class Connector
{
/**
* @return \PDO
*/
public static function connect()
{
//$dir = require "Connection.php";
$db_driver = $_ENV['DB_TYPE'];
$db_host = $_ENV['DB_HOST'];
$db_name = $_ENV['DB_NAME'];
$db_username = $_ENV['DB_USERNAME'];
$db_password = $_ENV['<PASSWORD>'];
try {
$db = new \PDO("$db_driver:host=$db_host;" . "dbname=$db_name", $db_username, $db_password,[]);
//var_dump($db);
$db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
if ($db) {
return $db;
}
} catch (\PDOException $e) {
//Send a generic message to the user
// echo $e->getMessage();
Session::create('warning',$e->getMessage());
FileLogger::debug($e->getMessage());
}
}
/**
*static function that calls the connect function
*/
public function connection()
{
(new Connector)->connect();
}
}
<file_sep>/Core/Helpers/Session.php
<?php
namespace Flux\Core\Helpers;
class Session
{
/**
* @var string $message
*/
public $message = "";
/**
* @var string $status
*/
public $status = "";
/**
* Get the value of message
*/
public function getMessage()
{
return $this->message;
}
/**
* Set the value of message
*
* @param String $message
* @return self
*/
public function setMessage(String $message)
{
$this->message = $message;
return $this;
}
/**
* Get the value of message
*/
public function getStatus()
{
return $this->status;
}
/**
* Set the value of status
*
* @param String $status
* @return self
*/
public function setStatus(String $status)
{
$this->status = $status;
return $this;
}
/**
*Display the session message.
*/
public function show()
{
if (isset($_SESSION['message'])) {
//echo $_SESSION['status'];
echo $_SESSION['message'];
//unset($_SESSION['message']);
//unset($_SESSION['status']);
session_destroy();
}
}
/**
* Set the message for the session
* @param String $message
*/
public function set(String $status, String $message)
{
$this->setStatus($status);
$this->setMessage($message);
if (!empty($this->getMessage())) {
$_SESSION['status'] = $this->status;
$_SESSION['message'] = $this->message;
}
}
/**
*Call the show function
*/
public static function display()
{
(new Session)->show();
}
/**
* Call the set function
* @param String $message
*/
public static function create(String $status, String $message)
{
(new Session)->set($status, $message);
}
}
<file_sep>/Controller/AuthController.php
<?php
namespace Flux\Controller;
use Flux\Core\Database\Connector;
use Flux\Core\Helpers\Mailer;
use Flux\Core\Helpers\Session;
use Flux\Core\Http\Request;
use Flux\Helpers\FileLogger;
class AuthController
{
/**
* register. Registers the user.
*
* @author Unknown
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Friday, February 8th, 2019.
* @version v1.0.1 Friday, March 1st, 2019.
* @access public static
* @param string $table
* @param array $data
* @return void
*/
public static function register(String $table, array $data)
{
$connect = Connector::connect();
$keys = [];
// $values = [];
$prepKey = "";
$prepVal = array();
$serverName = Request::host();
//$header = ["FROM" => "no-reply@loginoo.test"];
$email = $data['email'];
$name = $data['name'];
$header = 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html' . "\r\n";
//$header[] = 'MIME-Version: 1.0';
//$header[] = 'Content-type: text/html; charset=iso-8859-1';
//var_dump($data);
if (!is_array($data) && empty($data)) {
$error = new \PDOException("Values passed must be of type array");
$error->getMessage();
}
/**
* If the password from the password_confirm input matches the first password entered, then save password value to a variable and unset both password and password_confirm.
* Pass in new data using the unary array method, this makes the key value pair pushed to not have to be sorted.
* Hash the password and the activation data.
*/
if (array_key_exists('password_confirm', $data)) {
if ($data['password'] === $data['password_confirm']) {
$pass = $data['password'];
$activation_code = hash('sha512', $data['name']);
unset($data['password']);
unset($data['password_confirm']);
$data += ['password' => password_hash($pass, PASSWORD_DEFAULT)];
$data += ['activation_code' => $activation_code];
}
}
/*
*The foreach loop splits the array given into key and value for each index.
* The keys are separated into a $keys array, the same is done to the values.
* A $prepKey array is used for the key binding needed by pdo for the data manipulation.
* A $prepVal array is used to store the $prepKey and values giving a :name => name Array.
*/
foreach ($data as $key => $value) {
$keys[] = $key;
//$values[] = $value;
$prepKey = ":" . $key; //$prepKey is a variable that stores strings
$prepVal[$prepKey] = $value;
}
/**
* Use implode not list to separate the array values into a string with a glue string joining them.
*/
$columns = implode(",", $keys);
$params = ":" . implode(",:", $keys);
/**
* Resulting sql string should contain pdo named placeholder for values and normal string for the columns.
*/
$sql = "INSERT INTO {$table} ({$columns}) VALUES ({$params})";
//Prepare the sql statement for execution by pdo
$prep = $connect->prepare($sql);
//Using foreach loop bind the values to their placeholders, represented by the key value pairs in the array.
foreach ($prepVal as $key => $value) {
$prep->bindValue($key, $value);
}
try {
$create = $prep->execute();
//die(dump($create));
$message = "
<!DOCTYPE HTML PUBLIC '-//W3C//DTD XHTML 1.0 Transitional //EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office'>
<head>
<!--[if gte mso 9]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]-->
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta name='x-apple-disable-message-reformatting'>
<!--[if !mso]><!--><meta http-equiv='X-UA-Compatible' content='IE=edge'><!--<![endif]-->
<title></title>
<style type='text/css'>
body {
margin: 0;
padding: 0;
}
table, tr, td {
vertical-align: top;
border-collapse: collapse;
}
p, ul {
margin: 0;
}
.ie-container table, .mso-container table {
table-layout: fixed;
}
* {
line-height: inherit;
}
a[x-apple-data-detectors=true] {
color: inherit !important;
text-decoration: none !important;
}
.ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font, .ExternalClass td, .ExternalClass div {
line-height: 100%;
}
[owa] .email-row .email-col {
display: table-cell;
float: none !important;
vertical-align: top;
}
.ie-container .email-col-100, .ie-container .email-row, [owa] .email-col-100, [owa] .email-row { width: 500px !important; }
.ie-container .email-col-17, [owa] .email-col-17 { width: 85px !important; }
.ie-container .email-col-25, [owa] .email-col-25 { width: 125px !important; }
.ie-container .email-col-33, [owa] .email-col-33 { width: 165px !important; }
.ie-container .email-col-50, [owa] .email-col-50 { width: 250px !important; }
.ie-container .email-col-67, [owa] .email-col-67 { width: 335px !important; }
@media only screen and (min-width: 520px) {
.email-row { width: 500px !important; }
.email-row .email-col { vertical-align: top; }
.email-row .email-col-100 { width: 500px !important; }
.email-row .email-col-67 { width: 335px !important; }
.email-row .email-col-50 { width: 250px !important; }
.email-row .email-col-33 { width: 165px !important; }
.email-row .email-col-25 { width: 125px !important; }
.email-row .email-col-17 { width: 85px !important; }
}
@media (max-width: 520px) {
.hide-mobile { display: none !important; }
.email-row-container {
padding-left: 0px !important;
padding-right: 0px !important;
}
.email-row .email-col {
min-width: 320px !important;
max-width: 100% !important;
display: block !important;
}
.email-row { width: calc(100% - 40px) !important; }
.email-col { width: 100% !important; }
.email-col > div { margin: 0 auto; }
.no-stack .email-col { min-width: 0 !important; display: table-cell !important; }
.no-stack .email-col-50 { width: 50% !important; }
.no-stack .email-col-33 { width: 33% !important; }
.no-stack .email-col-67 { width: 67% !important; }
.no-stack .email-col-25 { width: 25% !important; }
.no-stack .email-col-17 { width: 17% !important; }
}
</style>
<!--[if mso]>
<style type='text/css'>
ul li {
list-style:disc inside;
mso-special-format:bullet;
}
</style>
<![endif]-->
</head>
<body class='clean-body' style='margin: 0;padding: 0;-webkit-text-size-adjust: 100%;background-color: #e4e4e4'>
<!--[if IE]><div class='ie-container'><![endif]-->
<!--[if mso]><div class='mso-container'><![endif]-->
<table class='nl-container' style='border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;min-width: 320px;Margin: 0 auto;background-color: #e4e4e4;width:100%' cellpadding='0' cellspacing='0'>
<tbody>
<tr style='vertical-align: top'>
<td style='word-break: break-word;border-collapse: collapse !important;vertical-align: top'>
<!--[if (mso)|(IE)]><table width='100%' cellpadding='0' cellspacing='0' border='0'><tr><td align='center' style='background-color: #e4e4e4;'><![endif]-->
<div class='email-row-container' style='padding: 10px;background-color: rgba(255,255,255,0)'>
<div style='Margin: 0 auto;min-width: 320px;max-width: 500px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: transparent;' class='email-row'>
<div style='border-collapse: collapse;display: table;width: 100%;background-color: transparent;'>
<!--[if (mso)|(IE)]><table width='100%' cellpadding='0' cellspacing='0' border='0'><tr><td style='padding: 10px;background-color: rgba(255,255,255,0);' align='center'><table cellpadding='0' cellspacing='0' border='0' style='width:500px;'><tr style='background-color: transparent;'><![endif]-->
<!--[if (mso)|(IE)]><td align='center' width='500' style='width: 500px;padding: 0px;border-top: 0px solid transparent;border-left: 0px solid transparent;border-right: 0px solid transparent;border-bottom: 0px solid transparent;' valign='top'><![endif]-->
<div class='email-col email-col-100' style='max-width: 320px;min-width: 500px;display: table-cell;vertical-align: top;'>
<div style='width: 100% !important;'>
<!--[if (!mso)&(!IE)]><!--><div style='padding: 0px;border-top: 0px solid transparent;border-left: 0px solid transparent;border-right: 0px solid transparent;border-bottom: 0px solid transparent;'><!--<![endif]-->
<table id='u_content_text_1' class='u_content_text' style='font-family:arial,helvetica,sans-serif;' role='presentation' cellpadding='0' cellspacing='0' width='100%' border='0'>
<tbody>
<tr>
<td style='overflow-wrap:break-word;word-break:break-word;padding:10px;font-family:arial,helvetica,sans-serif;' align='left'>
<div style='color: #000; line-height: 140%; text-align: left; word-wrap: break-word;'>
<p style='line-height: 140%; font-size: 14px;'><span style='font-size: 20px; line-height: 28px;'>Hello, $name</span></p>
</div>
</td>
</tr>
</tbody>
</table>
<table id='u_content_divider_1' class='u_content_divider' style='font-family:arial,helvetica,sans-serif;' role='presentation' cellpadding='0' cellspacing='0' width='100%' border='0'>
<tbody>
<tr>
<td style='overflow-wrap:break-word;word-break:break-word;padding:10px;font-family:arial,helvetica,sans-serif;' align='left'>
<table height='0px' align='center' border='0' cellpadding='0' cellspacing='0' width='100%' style='border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;border-top: 1px solid #BBBBBB;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%'>
<tbody>
<tr style='vertical-align: top'>
<td style='word-break: break-word;border-collapse: collapse !important;vertical-align: top;font-size: 0px;line-height: 0px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%'>
<span> </span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
</div>
</div>
<!--[if (mso)|(IE)]></td><![endif]-->
<!--[if (mso)|(IE)]></tr></table></td></tr></table><![endif]-->
</div>
</div>
</div>
<div class='email-row-container' style='padding: 8px;background-color: #e5e5e5'>
<div style='Margin: 0 auto;min-width: 320px;max-width: 500px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: #5e96a4;' class='email-row'>
<div style='border-collapse: collapse;display: table;width: 100%;background-color: #5e96a4;'>
<!--[if (mso)|(IE)]><table width='100%' cellpadding='0' cellspacing='0' border='0'><tr><td style='padding: 8px;background-color: #e5e5e5;' align='center'><table cellpadding='0' cellspacing='0' border='0' style='width:500px;'><tr style='background-color: #5e96a4;'><![endif]-->
<!--[if (mso)|(IE)]><td align='center' width='500' style='width: 500px;padding: 0px;border-top: 0px solid transparent;border-left: 0px solid transparent;border-right: 0px solid transparent;border-bottom: 0px solid transparent;' valign='top'><![endif]-->
<div class='email-col email-col-100' style='max-width: 320px;min-width: 500px;display: table-cell;vertical-align: top;'>
<div style='width: 100% !important;'>
<!--[if (!mso)&(!IE)]><!--><div style='padding: 0px;border-top: 0px solid transparent;border-left: 0px solid transparent;border-right: 0px solid transparent;border-bottom: 0px solid transparent;'><!--<![endif]-->
<table id='u_content_text_2' class='u_content_text' style='font-family:arial,helvetica,sans-serif;' role='presentation' cellpadding='0' cellspacing='0' width='100%' border='0'>
<tbody>
<tr>
<td style='overflow-wrap:break-word;word-break:break-word;padding:50px 10px;font-family:arial,helvetica,sans-serif;' align='left'>
<div style='color: #fffefe; line-height: 140%; text-align: center; word-wrap: break-word;'>
<p style='font-size: 14px; line-height: 140%;'>Click the link below to complete your registration.</p>
<a style='text-decoration:none;width:300px;' target='_blank' href='http://$serverName/activate/$email/$activation_code'>ACTIVATE</a>
<p style='font-size: 14px; line-height: 140%;'> </p>
</div>
</td>
</tr>
</tbody>
</table>
<!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
</div>
</div>
<!--[if (mso)|(IE)]></td><![endif]-->
<!--[if (mso)|(IE)]></tr></table></td></tr></table><![endif]-->
</div>
</div>
</div>
<!--[if (mso)|(IE)]></td></tr></table><![endif]-->
</td>
</tr>
</tbody>
</table>
<!--[if (mso)|(IE)]></div><![endif]-->
</body>
</html>
";
$mail = Mailer::send($email, "Click the button below to activate your account", $message, $header);
if ($mail) {
Session::create('success', 'ACTIVATION MAIL SENT, CHECK YOUR INBOX');
return $create;
}
} catch (\Throwable $th) {
FileLogger::error($th->getMessage());
Session::create('danger', 'Unsuccessful Registration!!');
}
}
/**
* @param array $data
*/
public static function activate(array $data)
{
$email = $data['email'];
$activation_code = $data['activation_code'];
$connect = Connector::connect();
try {
$sql = "SELECT id FROM users WHERE email=:email AND activation_code=:activation_code";
//dump($sql);
$user = $connect->prepare($sql);
//var_dump($user);
$user->execute(["email" => $email, "activation_code" => $activation_code]);
$count = $user->rowCount();
//dd($count);
if ($count > 0) {
$sql = "UPDATE users SET activation_confirm=1, activation_code=0 WHERE email=:email";
$user = $connect->prepare($sql);
//var_dump($user);
$user->execute(["email" => $email]);
$result = $user->rowCount();
//dd($count);
if ($result > 0) {
Session::create('success', 'You can now login to your account');
redirect('/');
}
} else {
Session::create('info', 'Email and Activation code not valid!!!!!');
FileLogger::info("Email and Activation code not valid");
}
} catch (\Throwable $th) {
//throw $th;
FileLogger::info($th->getMessage());
Session::create('danger', 'Unsuccessful Activation!!');
}
}
/**
* login.Returns true or false if credentials are not found in the database.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Wednesday, March 6th, 2019.
* @access public static
* @param string $table
* @param array $data
* @return void
*/
public static function login(String $table, array $data)
{
$connect = Connector::connect();
$email = $data['email'];
$password = $data['<PASSWORD>'];
if (!is_string($table)) {
throw new \PDOException("Datatype must be of type String");
}
if (!is_array($data) && empty($data)) {
throw new \PDOException("Values passed must be of type array");
//$error->getMessage();
}
try {
$sql = "SELECT `password` FROM $table WHERE email=:email";
//var_dump($sql);
$user = $connect->prepare($sql);
//var_dump($user);
$user->execute(["email" => $email]);
$password_confirm = $user->fetchColumn();
//dd($password_confirm);
$count = $user->rowCount();
//var_dump($count);
if ($count > 0) {
if (!password_verify($password, $password_confirm)) {
Session::create('warning', 'Check Password!!');
return redirect('/');
}
setcookie('loggedIn', 'true', time() + 3600);
return $count;
}
Session::create('warning', 'Check Email!!');
return redirect('/');
} catch (\PDOException $th) {
$th->getMessage();
}
}
/**
* logout.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Wednesday, March 13th, 2019.
* @access public static
* @return mixed
*/
public static function logout()
{
if (session_status() == PHP_SESSION_ACTIVE) {
session_destroy();
setcookie('loggedIn', 'true', 1);
//setcookie('email');
// unset($_SESSION['PHPSESSID']);
// unset($_COOKIE['email']);
//return redirect('/');
return true;
}
// return redirect('/');
}
}
<file_sep>/Core/Http/Request.php
<?php
namespace Flux\Core\Http;
class Request
{
/**
* uri. Returns the current request uri.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Wednesday, March 6th, 2019.
* @access public static
* @return mixed
*/
public static function uri()
{
return $_SERVER['REQUEST_URI'];
}
/**
* method. Returns the request method.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Wednesday, March 6th, 2019.
* @access public static
* @return mixed
*/
public static function method()
{
return $_SERVER['REQUEST_METHOD'];
}
/**
* all.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Wednesday, March 13th, 2019.
* @access public static
* @return mixed
*/
public static function all()
{
if (!isset($_POST['submit'])) {
echo "No Data";
exit;
}
$post = $_POST;
unset($post['submit']);
return $post;
}
/**
* host. Returns the server name
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Wednesday, March 6th, 2019.
* @access public static
* @return mixed
*/
public static function host()
{
return $_SERVER['SERVER_NAME'];
}
/**
* is. Check the request url and returns true or false if url given is the same as the actual url.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Wednesday, March 6th, 2019.
* @access public static
* @param string $url
* @return boolean
*/
public static function is(String $url)
{
if ($_SERVER['REQUEST_URI'] === $url) {
return true;
}
}
}
<file_sep>/Core/Interfaces/LoggerInterface.php
<?php
namespace Flux\Interfaces;
interface LoggerInterface
{
public static function warn(String $message);
public static function error(String $message);
public static function critical(String $message);
public static function debug(String $message);
public static function info(String $message);
}<file_sep>/Core/Router/Router.php
<?php
namespace Flux\Core\Router;
class Router
{
/**
* @var array
*/
public static $routes = [
'GET' => [],
'POST' => [],
];
/**
* load.
*
* @author Unknown
* @since v0.0.1
* @version v1.0.0 Saturday, February 9th, 2019.
* @access public static
* @param mixed $file
* @return mixed
*/
public static function load($file)
{
require $file;
$router = new static;
return $router;
}
/**
* get.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Saturday, February 23rd, 2019.
* @access public static
* @param mixed $uri
* @param mixed $controller
* @return mixed
*/
public static function get($uri, $controller)
{
return self::$routes['GET'][$uri] = [$controller];
}
/**
* post.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Saturday, February 23rd, 2019.
* @access public static
* @param mixed $uri
* @param mixed $controller
* @return mixed
*/
public static function post($uri, $controller)
{
return self::$routes['POST'][$uri] = [$controller];
}
/**
* parseRoute.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Sunday, February 24th, 2019.
* @access private
* @param string $uri
* @param mixed $method
* @return void
*/
private function parseRoute(String $uri, $method)
{
try {
$matches = array();
if (array_key_exists($uri, self::$routes[$method])) {
list($callMethod) = self::$routes[$method][$uri];
return $this->callControllerAction(
...explode('@', $callMethod)
);
echo "True";
} else {
foreach (self::$routes[$method] as $key => $val) {
$pattern = preg_replace('#\(/\)#', '/?', $key);
//var_dump("Pattern first pass is ". $pattern);
$pattern = "@^" . preg_replace('/{([a-zA-Z0-9\_\-]+)}/', '(?<$1>[a-zA-Z0-9\_\-\.\@]+)', $pattern) . "$@D";
///var_dump("Pattern second pass is ". $pattern);
preg_match($pattern, $uri, $matches);
//var_dump("Matched patterns are ". $matched);
array_shift($matches);
//var_dump($matches);
//print_r($matches);
if ($matches && isset($matches)) {
//print_r($val);
list($controllerAction) = $val;
//var_dump($controllerAction);
$getAction = explode('@', $controllerAction);
//var_dump($getAction);
//list($controller) = $getAction[0];
//var_dump($controller);
//list($action) = $getAction[1];
//var_dump($action);
$this->callControllerAction($getAction[0], $getAction[1], $matches);
}
}
} //code...
} catch (\Throwable $th) {
$th->getMessage();
//throw new \Exception('No route defined for this URI.');
}
}
/**
* resolve.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Saturday, February 9th, 2019.
* @access public
* @param mixed $uri
* @param mixed $requestMethod
* @return void
*/
public function resolve($uri, $method)
{
$this->parseRoute($uri, $method);
}
/**
* Calls the method on the controller if it exits. Controller is specified in the route.
* @param $controller
* @param $action
* @return mixed
*/
public function callControllerAction($controller, $action, $var = [])
{
$controller = "Flux\\Controller\\{$controller}";
$controller = new $controller;
//var_dump($controller);
if (!method_exists($controller, $action) && !empty($action)) {
echo "Method {$action} does not exist in {$controller}";
}
return $controller->$action($var);
}
}
<file_sep>/Controller/LoginController.php
<?php
namespace Flux\Controller;
use Flux\Controller\AuthController as Auth;
use Flux\Core\Helpers\Session;
use Flux\Core\Http\Request;
class LoginController
{
public function login()
{
$auth = Auth::login('users', Request::all());
if ($auth) {
Session::create('success', 'Log In Successful');
return redirect('/dashboard');
}
// Session::create('info','Cannot Login With Given Credentials');
// return redirect('/');
}
public function logout()
{
$logout = Auth::logout();
if($logout)
return redirect('/');
}
}
<file_sep>/Controller/SiteController.php
<?php
namespace Flux\Controller;
use Flux\Core\Helpers\Session;
use Flux\Controller\Controller;
class SiteController extends Controller
{
public function index()
{
return view('index');
}
public function getRegisterView()
{
return view('register');
}
public function about()
{
return view('about');
}
public function dashboard()
{
return view('dashboard');
}
public function where()
{
$where = $this->db->table('users')->where('id','=',117);
//dd($where);
if(empty($where)){
Session::create('warning','Row does not exist in database');
return redirect('/');
}
return view('find',$where);
}
}<file_sep>/Core/Helpers/Functions.php
<?php
/**
* The view that is shown to the user.
* @param String $file
*/
function view(String $file, $data = [])
{
extract($data);
require "./Views/" .$file. ".view.php";
}
/**Redirects to a specified page
* @param String $location
*/
function redirect(String $location, $refresh=1){
header("Location:".$location,"Refresh:".$refresh);
exit;
}
/**
* serverName.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Sunday, February 24th, 2019.
* @global
* @return void
*/
function serverName(){
$serverName = $_SERVER['SERVER_NAME'];
echo $serverName;
}
/**
* isLoggedIn.
*
* @author eonflux
* @since v0.0.1
* @version v1.0.0 Wednesday, March 13th, 2019.
* @global
* @return boolean
*/
function isLoggedIn(){
if(isset($_COOKIE['loggedIn']) ){
return true;
}
return false;
}
<file_sep>/Routes.php
<?php
use Flux\Core\Router\Router;
Router::get('/','SiteController@index');
Router::get('/dashboard','DashboardController@index');
Router::get('/register','SiteController@getRegisterView');
Router::get('/activate/{email}/{activation_code}','RegistrationController@getActivateView');
Router::get('/where','SiteController@where');
Router::post('/register','RegistrationController@register');
Router::post('/activate','ActivationController@activate');
Router::post('/login','LoginController@login');
Router::post('/logout','LoginController@logout');
<file_sep>/loginoo.sql
CREATE TABLE `users` (
`id` INT(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(50) NOT NULL,
`email` VARCHAR(50) NOT NULL UNIQUE,
`password` VARCHAR(255) NOT NULL,
`activation_code` VARCHAR(255) NULL,
`activatation_confirm` TINYINT NOT NULL DEFAULT '0',
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
COLLATE='latin1_swedish_ci'
;
<file_sep>/Views/header.php
<?php use Flux\Core\Http\Request;?>
<!Doctype html>
<html lang="en-US">
<head>
<title>Index Page</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="/public/main.css">
</head>
<body>
<nav class="navigation">
<ul class="nav-list">
<?php if(!isLoggedIn()):?>
<li class="nav-item"><a href="/">Login</a></li>
<li class="nav-item"><a href="/register">Register</a></li>
<?php endif;?>
<?php if (isLoggedIn()): ?>
<form action="/logout" method="post" style="padding: 0;margin:0;">
<input type="submit" value="Logout" name="submit" style="padding: 0;margin:0;">
</form>
<!-- <a href="/logout" class="btn">LOGOUT</a> -->
<?php endif;?>
</ul>
</nav><file_sep>/Controller/DashboardController.php
<?php
namespace Flux\Controller;
class DashboardController
{
public function index()
{
if(isLoggedIn()){
return view('dashboard');
}
return redirect('/');
}
}<file_sep>/Core/Helpers/FileLogger.php
<?php
namespace Flux\Helpers;
use Flux\Interfaces\LoggerInterface;
class FileLogger implements LoggerInterface
{
/**
* @var mixed $file
*/
public static $file;
public static function check(){
$file = $_ENV['LOG_FILE_DIR'];
if (file_exists($file)) {
FileLogger::$file = $file;
$Logger = new static;
return $Logger;
} else {
echo "The file $file does not exist";
}
}
public static function info($message){
//static::check();
self::check();
try {
$severity = "INFO";
$handle = fopen(FileLogger::$file,'a+');
//$error = FileLogger::$FileLogger->error($message);
fwrite($handle,date("Y-m-d H:i:s")." ".$severity." :: ".$message."\r\n");
} catch (\Exception $th) {
echo $th->getMessage();
}
}
public static function warn($message){
//static::check();
self::check();
try {
$severity = "WARN";
$handle = fopen(FileLogger::$file,'a+');
//$error = FileLogger::$FileLogger->error($message);
fwrite($handle,date("Y-m-d H:i:s")." ".$severity." :: ".$message."\r\n");
} catch (\Exception $th) {
echo $th->getMessage();
}
}
public static function debug($message){
//static::check();
self::check();
try {
$severity = "DEBUG";
$handle = fopen(FileLogger::$file,'a+');
//$error = FileLogger::$FileLogger->error($message);
fwrite($handle,date("Y-m-d H:i:s")." ".$severity." :: ".$message."\r\n");
} catch (\Exception $th) {
echo $th->getMessage();
}
}
public static function critical($message){
//static::check();
self::check();
try {
$severity = "CRITICAL";
$handle = fopen(FileLogger::$file,'a+');
//$error = FileLogger::$FileLogger->error($message);
fwrite($handle,date("Y-m-d H:i:s")." ".$severity." :: ".$message."\r\n");
} catch (\Exception $th) {
echo $th->getMessage();
}
}
public static function error($message){
//static::check();
self::check();
try {
$severity = "ERROR";
$handle = fopen(FileLogger::$file,'a+');
//$error = FileLogger::$FileLogger->error($message);
fwrite($handle,date("Y-m-d H:i:s")." ".$severity." :: ".$message."\r\n");
} catch (\Exception $th) {
echo $th->getMessage();
}
}
}<file_sep>/bootstrap.php
<?php
require "Core/Helpers/Functions.php";
ob_start();
session_start();
<file_sep>/Views/find.view.php
<?php include 'header.php';
use Flux\Core\Helpers\Session;
?>
<div class="container">
<?php if(isset($_SESSION['message'])): ?>
<div class="alert alert-<?= $_SESSION['status'] ?>">
<p>
<?php Session::display()?>
</p>
</div>
<?php endif; ?>
<div class="row">
<div class="col">
<table>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
<th>ACTIVATED</th>
<th>DATE CREATED</th>
</tr>
<?php foreach($data as $user):?>
<tr>
<td><?=$user['id']?></td>
<td><?=$user['name']?></td>
<td><?=$user['email']?></td>
<td>
<?php
if(intval($user['activation_confirm']) === 0):
?>
<i class="fas fa-times danger"></i>
<?php else: ?>
<i class="fas fa-check success"></i>
<?php endif; ?>
</td>
<td><?= gmdate('D:m:Y H:i',strtotime($user['date_created'])) ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div>
</div>
<?php include 'footer.php';?><file_sep>/index.php
<?php
require "bootstrap.php";
require "./vendor/autoload.php";
use Flux\Core\Http\Request;
use Flux\Core\Router\Router;
//use Flux\Helpers\FileLogger;
if ($dotenv = Dotenv\Dotenv::createUnsafeMutable(__DIR__)) {
$dotenv->load();
} else {
var_dump("Environment files have not been loaded.");
}
//$dotenv = Dotenv\Dotenv::createUnsafeMutable(__DIR__);
//$dotenv->load();
//$logger = new Logger();
// $logger->info("TESTING LOG CLASS",['status'=> 503]);
//$logger->log("TESTING THE LOGGER CLASS");
//FileLogger::error("TESTING LOG CLASS");
$router = new Router();
$router->load('Routes.php')->resolve(Request::uri(), Request::method());
<file_sep>/Core/Database/DataQueryTrait.php
<?php
/**
* Created by PhpStorm.
* User: Flux
* Date: 2/7/2019
* Time: 4:28 PM
*/
namespace Flux\Core\Database;
interface DataQueryTrait
{
public function create(Array $data);
}<file_sep>/Controller/Controller.php
<?php
namespace Flux\Controller;
use Flux\Core\Database\QueryBuilder as DB;
class Controller
{
public function __construct()
{
$this->db = new DB;
}
}<file_sep>/Views/activate.view.php
<?php include 'header.php';
use Flux\Core\Helpers\Session;
?>
<div class="container">
<?php if(isset($_SESSION['message'])): ?>
<div class="alert alert-<?= $_SESSION['status'] ?>">
<p><?php Session::display()?></p>
</div>
<?php endif; ?>
<div class="row">
<div class="col">
<form action="/activate" method="post" style="background-color: grey;">
<div class="form-group">
<?php if(isset($data)): ?>
<input type="text" value="<?= $data['email']; ?>" name="email" hidden>
<?php elseif(!isset($data)): ?>
<input type="text" value="" name="email" hidden>
<?php endif;?>
</div>
<div class="form-group">
<?php if(isset($data)): ?>
<input type="text" value="<?= $data['activation_code']; ?>" name="activation_code" hidden>
<?php elseif(!isset($data)): ?>
<input type="text" value="" name="activation_code" hidden>
<?php endif;?>
</div>
<div class="form-group">
<label for="activation">Activate User
</label>
<input type="submit" value="Activate" name="submit">
</div>
</form>
</div>
</div>
</div>
<?php include 'footer.php';?><file_sep>/Views/register.view.php
<?php
include 'header.php';
use Flux\Core\Helpers\Session;
?>
<div class="container">
<?php if(isset($_SESSION['message'])): ?>
<div class="alert alert-<?= $_SESSION['status'] ?>">
<p><?php Session::display()?></p>
</div>
<?php endif; ?>
<div class="row">
<div class="col">
<form action="#" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" id="email" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="<PASSWORD>" name="password" id="password" required>
</div>
<div class="form-group">
<label for="password">Confirm Password</label>
<input type="<PASSWORD>" name="password_confirm" id="password_confirm" required>
</div>
<div class="form-group">
<input type="submit" value="Submit" name="submit">
</div>
</form>
</div>
</div>
</div>
<?php include 'footer.php'; ?><file_sep>/README.md
# MVC
Simple mvc for learning and practise.
#
| fb98a56594730e0ae26b8364fb917a57dda90dc4 | [
"Markdown",
"SQL",
"PHP"
] | 28 | PHP | EricEon/mvc | dd8bfbc83215f2b31b111679188f0e17874c766e | ea338506bbdb189782c3661d23ea0778259d9855 |
refs/heads/master | <file_sep>import random
import pandas as pd
'''
CREATE TABLE employee(
UU_ID UUID PRIMARY KEY,
EMP_ID DECIMAL,
DEPT_TYPE TEXT,
RACE TEXT,
DAY_OF_WEEK TEXT,
CHECKIN_DATETIME TEXT,
CHECKOUT_DATETIME TEXT
)
'''
class DataGen:
dayOfWeekChoice = ['MON', "TUE", 'WED', 'THU', "FRI"]
workTimeChoice = [1, 2, 3, 4, 5, 6, 7, 8]
checkInTimeChoice = ["8:00", "8:30", "9:00",
"9:30", "10:00", "10:30", "11:00", "11:30", "12:00"]
departmentTypeChoice = ["1", "2", "3", "4", "5", "6"]
raceTypeChoice = ["1", "2", "3", "4", "5", "6"]
genderTypeChoice = ["male", "female"]
def __init__(self, n_data=2000, n_employee=50):
self.row = n_data
self.n_employee = n_employee
self.employeeID = []
self.departmentType = []
self.race = []
self.gender = []
self.dayOfWeek = []
self.checkInTime = []
self.workTime = []
def genData(self):
employee_dict = {}
for id in range(self.n_employee):
employee_dict[id] = [random.choice(
self.genderTypeChoice), random.choice(self.raceTypeChoice), random.choice(self.departmentTypeChoice)]
for _ in range(self.row//self.n_employee):
for id in range(self.n_employee):
_edata = employee_dict[id]
self.employeeID += [id]
self.departmentType += [_edata[2]]
self.race += [_edata[1]]
self.gender += [_edata[0]]
self.dayOfWeek += [random.choice(self.dayOfWeekChoice)]
self.checkInTime += [random.choice(self.workTimeChoice)]
self.workTime += [random.choice(self.checkInTimeChoice)]
def saveCSV(self, filename):
variables = [self.employeeID,
self.departmentType,
self.race,
self.gender,
self.dayOfWeek,
self.checkInTime,
self.workTime]
df = pd.DataFrame(variables).transpose()
df.columns = ["ID", "department", "race", "gender", "day of week",
"check in time", "work time"]
df.to_csv(filename, index=False)
if __name__ == '__main__':
dg = DataGen()
dg.genData()
dg.saveCSV("employeedata.csv")
<file_sep>import requests, sys, os
import logging as log, traceback
import random
from flask import Flask, request, jsonify
from flask_restful import Api
from cassandra.cluster import Cluster, DCAwareRoundRobinPolicy
import time
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
api = Api(app)
log.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
#HashMap
emp_dict = {}
hosp_dict = {}
first_call_result= {}
##################################################
def updateHashMap(wf, comp, order, ip_list):
h_key = {"order": order, "ips": ip_list}
if (wf.upper() == "EMPLOYEE"):
emp_dict[comp] = h_key
if (wf.upper() == "HOSPITAL"):
hosp_dict[comp] = h_key
def getComponentURL(n, ip_add):
url_string = "http://"
if n == "2":
url_string = url_string + ip_add + "/lgr/predict"
elif n == "3":
url_string = url_string + ip_add + "/svm/predict"
elif n == "4":
url_string = url_string + ip_add + "/put_result"
else:
msg = "DataLoader Error getComponentURL: Unable to find the service component, no Service component found with code: " + n
log.info(msg)
return url_string
#################################################
class DataLoader:
KEYSPACE=0
cluster=0
session=0
rec_cnt=2000
def __init__(self):
self.KEYSPACE = "<KEY>"
self.cluster = Cluster(contact_points=['10.176.67.91'], load_balancing_policy=DCAwareRoundRobinPolicy(local_dc='datacenter1'), port=9042, protocol_version=3)
self.session = self.cluster.connect()
self.session.set_keyspace(self.KEYSPACE)
def validation(self, usr_name):
result = 0
qry = "SELECT COUNT(*) FROM " + usr_name + " ALLOW FILTERING;"
try:
stat = self.session.prepare(qry)
x = self.session.execute(stat)
for row in x:
result = row.count
except Exception as e:
result = -1
log.info("DataLoader validation: No Table found in Cassandra database.")
return result
def employee_create_schema(self, usr_name):
status = 0
stat1 = "CREATE TABLE IF NOT EXISTS " + usr_name + """(
UU_ID UUID PRIMARY KEY,
EMP_ID DECIMAL,
DEPT_TYPE TEXT,
GENDER TEXT,
RACE TEXT,
DAY_OF_WEEK TEXT,
CHECKIN_DATETIME TEXT,
DURATION TEXT);"""
try:
cre_tbl = self.session.prepare(stat1)
self.session.execute(cre_tbl)
except Exception as e:
log.error(traceback.format_exc())
status = -1
self.session.shutdown()
return status
def employee_data_gen(self, usr_name):
# define constants
status = 0
dept1 = ["1", "2", "3", "4", "5", "6"]
gender1 = ["male", "female"]
race1 = ["1", "2", "3", "4", "5", "6"]
day1 = ["MON", "TUE", "WED", "THU", "FRI"]
checkin1 = ["8:00", "8:30", "9:00",
"9:30", "10:00", "10:30",
"11:00", "11:30", "12:00",
"12:30", "13:00", "13:30", "14:00"]
duration1 = ["1", "2", "3", "4", "5", "6", "7", "8"]
# Insert query format
ins_stat = "INSERT INTO " + usr_name + """(UU_ID, EMP_ID, DEPT_TYPE, GENDER, RACE, DAY_OF_WEEK, CHECKIN_DATETIME, DURATION)
VALUES (now(), ?, ?, ?, ?, ?, ?, ?)"""
try:
insert_q = self.session.prepare(ins_stat)
# generate data
for i in range(1, self.rec_cnt + 1):
empid = i
dept = random.choice(dept1)
gender = random.choice(gender1)
race = random.choice(race1)
day = random.choice(day1)
checkin = random.choice(checkin1)
duration = random.choice(duration1)
self.session.execute(insert_q, [empid, dept, gender, race, day, checkin, duration])
except Exception as e:
log.error(traceback.format_exc())
status = -1
self.session.shutdown()
return status
def employee_append_data(self, usr_name, data):
# define constants
status = 0
empid = data["emp_id"]
dept1 = data["dept_type"]
gender1 = data["gender"]
race1 = data["race"]
day1 = data["day_of_week"]
checkin1 = data["checkin_datetime"]
duration1 = data["duration"]
# Insert query format
ins_stat = "INSERT INTO " + usr_name + """(UU_ID, EMP_ID, DEPT_TYPE, GENDER, RACE, DAY_OF_WEEK, CHECKIN_DATETIME, DURATION)
VALUES (now(), ?, ?, ?, ?, ?, ?, ?)"""
try:
insert_q = self.session.prepare(ins_stat)
#generate data
self.session.execute(insert_q, [empid, dept1, gender1, race1, day1, checkin1, duration1])
except Exception as e:
log.error(traceback.format_exc())
status = -1
self.session.shutdown()
return status
def hospital_create_schema(self, usr_name):
status = 0
stat1 = "CREATE TABLE IF NOT EXISTS " + usr_name + """(
uu_id UUID PRIMARY KEY,
hadm_id DECIMAL,
hospital_expire_flag DECIMAL,
insurance DECIMAL,
duration TEXT,
num_in_icu DECIMAL,
amount DECIMAL,
rate DECIMAL,
total_items DECIMAL,
value DECIMAL,
dilution_value DECIMAL,
abnormal_count DECIMAL,
item_distinct_abnormal DECIMAL,
checkin_datetime TEXT,
day_of_week TEXT);"""
try:
cre_tbl = self.session.prepare(stat1)
self.session.execute(cre_tbl)
except Exception as e:
log.error(traceback.format_exc())
status = -1
self.session.shutdown()
return status
# hospital Data generator
def hospital_data_gen(self, usr_name):
# define constants
status = 0
hospital_expire_flag1 = [1, 2]
insurance1 = [1, 2, 3, 4, 5]
day1 = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]
duration1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"]
checkin_time1 = ["00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00",
"06:30","07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30"]
# Insert query format
ins_stat = "INSERT INTO " + usr_name + """ (uu_id, hadm_id, hospital_expire_flag, insurance, duration, num_in_icu,
amount, rate, total_items, value, dilution_value, abnormal_count, item_distinct_abnormal, checkin_datetime, day_of_week)
VALUES (now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
try:
insert_q = self.session.prepare(ins_stat)
#generate data
for i in range(1000, self.rec_cnt + 1000):
hadm_id = i
hospital_expire_flag = random.choice(hospital_expire_flag1)
insurance = random.choice(insurance1)
duration = random.choice(duration1)
num_in_icu = random.randint(1, 40)
amount = random.uniform(-0.013434843, 1)
rate = random.uniform(0, 1)
total_items = random.uniform(0.093117409, 1)
value = random.uniform(0.000110609, 1)
dilution_value = random.uniform(0, 1)
abnormal_count = random.uniform(0.001908852, 1)
item_distinct_abnormal = random.uniform(0.059405941, 1)
checkin_datetime = random.choice(checkin_time1)
day_of_week = random.choice(day1)
self.session.execute(insert_q,
[hadm_id, hospital_expire_flag, insurance, duration, num_in_icu, amount, rate,
total_items, value, dilution_value, abnormal_count, item_distinct_abnormal, checkin_datetime, day_of_week])
except Exception as e:
log.error(traceback.format_exc())
status = -1
self.session.shutdown()
return status
def hospital_append_data(self, usr_name, data):
# define constants
status = 0
# Insert query format
ins_stat = "INSERT INTO " + usr_name + """ (uu_id, hadm_id, hospital_expire_flag, insurance, duration, num_in_icu,
amount, rate, total_items, value, dilution_value, abnormal_count, item_distinct_abnormal, checkin_datetime, day_of_week)
VALUES (now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
try:
insert_q = self.session.prepare(ins_stat)
#generate data
hadm_id = data["hadm_id"]
hospital_expire_flag = data["hospital_expire_flag"]
insurance = data["insurance"]
duration = data["duration"]
num_in_icu = data["num_in_icu"]
amount = data["amount"]
rate = data["rate"]
total_items = data["total_items"]
value = data["value"]
dilution_value = data["dilution_value"]
abnormal_count = data["abnormal_count"]
item_distinct_abnormal = data["item_distinct_abnormal"]
checkin_datetime = data["checkin_datetime"]
day_of_week = data["day_of_week"]
self.session.execute(insert_q,
[hadm_id, hospital_expire_flag, insurance, duration, num_in_icu, amount, rate,
total_items, value, dilution_value, abnormal_count, item_distinct_abnormal, checkin_datetime, day_of_week])
except Exception as e:
log.error(traceback.format_exc())
status = -1
self.session.shutdown()
return status
def __del__(self):
self.session.shutdown()
log.info("Object Destroyed")
@app.route("/dataloader", methods=['POST', 'GET'])
def dataloader():
start = time.time()
#get request parameters
req = request.get_json()
workflow = req["workflow"]
comp_name = req["client_name"]
order = list(req["workflow_specification"])
ip_list = req["ips"]
log.info("*********** DATALOADER API REQUEST PARAMETERS *************")
log.info("workflow = " + workflow)
log.info("comp_name = " + comp_name)
log.info("workflow_specification = " + str(order))
log.info("ips = " + str(ip_list))
if len(order) == 1: order.append(["4"])
res = 0
status1 = status2 = -1
#start workflow
log.info("DataLoader - Starting workflow: " + workflow)
db1 = DataLoader()
#Check if company name is already exist if yes then get records count
tbl_name = workflow + "_" + comp_name
res = db1.validation(tbl_name)
if res <= 0:
res = db1.rec_cnt
log.info("DataLoader - Creating a new table for the client: " + comp_name)
#Workflow check - Hospital flow or Employee flow and switch to the corresponding block of code
if (workflow.upper() == "EMPLOYEE"):
status1 = db1.employee_create_schema(tbl_name)
if status1 == 0:
log.info("DataLoader - A new Table created successfully: " + db1.KEYSPACE + "." + tbl_name)
log.info("DataLoader - Progressing initial data loading.......")
status2 = db1.employee_data_gen(tbl_name)
if status2 == 0:
log.info("DataLoader - Data Loaded Successfully. Total Number of records: " + str(res))
else:
msg = {"DataLoader employee_data_gen ERROR": "Failed in Data generation, No records added."}
log.info(msg)
return jsonify(dataloader), 400
# end of if status2 == 0:
else:
msg = {"DataLoader employee_create_schema ERROR": "Cassandra failed to create a new table."}
log.info(msg)
return jsonify(dataloader), 404
# end of if status1 == 0:
elif (workflow.upper() == "HOSPITAL"):
status1 = db1.hospital_create_schema(tbl_name)
if status1 == 0:
log.info("DataLoader - A new Table created successfully: " + db1.KEYSPACE + "." + tbl_name)
log.info("DataLoader - Progressing initial data loading.......")
status2 = db1.hospital_data_gen(tbl_name)
if status2 == 0:
log.info("DataLoader - Data Loaded Successfully. Total Number of records: " + str(res))
else:
msg = {"DataLoader hospital_data_gen ERROR": "Failed in Data generation, No records added."}
log.info(msg)
return jsonify(dataloader), 400
# end of if status2 == 0:
else:
msg = {"DataLoader hospital_create_schema ERROR": "Cassandra failed to create a new table."}
log.info(msg)
return jsonify(dataloader), 404
# end of if status1 == 0:
else:
msg = {"DataLoader ERROR": "Wrong Workflow Name in Request - " + workflow}
log.info(msg)
return jsonify(msg), 404
#end of if (workflow.upper() == "EMPLOYEE"):
else:
log.info("DataLoader - User/Company name already active: " + comp_name)
# end of if res <= 0:
db1.session.shutdown()
#update hashmap with workflow
updateHashMap(workflow, comp_name, order, ip_list)
log.info("DataLoader - HashMap Update complete for the new Key: (" + workflow + ", " + comp_name + ")")
if (workflow.upper() == "EMPLOYEE"):
log.info(str(emp_dict[comp_name]))
if (workflow.upper() == "HOSPITAL"):
log.info(str(hosp_dict[comp_name]))
end = time.time()
t = end - start
if (first_call_result["comp_name"] == comp_name) and (first_call_result["workflow"] == workflow):
dataloader = first_call_result["dataloader"]
else:
dataloader = {"start_time": start, "end_time": end, "elapsed_time": t, "record_count": res}
return jsonify(dataloader), 200
@app.route("/dataflow_append", methods=['POST', 'GET'])
def dataflow_append():
start = time.time()
# get request parameters
req = request.get_json()
workflow = req["workflow"]
comp_name = req["client_name"]
data = req["data"]
log.info("*********** DATALOADER APPEND API REQUEST PARAMETERS *************")
log.info("workflow = " + workflow)
log.info("comp_name = " + comp_name)
log.info("data = " + str(data))
res = 0
status = -1
tbl_name = workflow + "_" + comp_name
# start workflow
log.info("DataLoader Append - Starting data addition process for: " + workflow)
db1 = DataLoader()
# Workflow check - Hospital flow or Employee flow and switch to the corresponding block of code
if (workflow.upper() == "EMPLOYEE"):
#get the workflow and list
order = emp_dict[comp_name]["order"]
ip_list = emp_dict[comp_name]["ips"]
log.info("DataLoader Append - Appending new data to the table.......")
status = db1.employee_append_data(tbl_name, data)
if status == 0:
res = db1.validation(tbl_name)
log.info("DataLoader Append - New record added Successfully. Total Number of records in table : " + str(res))
else:
msg = {"DataLoader Append employee_append_data ERROR": "Failed in data addition, No new records added."}
log.info(msg)
return jsonify(msg), 420
# end of if status == 0:
elif (workflow.upper() == "HOSPITAL"):
# get the workflow and list
order = hosp_dict[comp_name]["order"]
ip_list = hosp_dict[comp_name]["ips"]
log.info("DataLoader Append - Appending new data to the table.......")
status = db1.hospital_append_data(tbl_name, data)
if status == 0:
res = db1.validation(tbl_name)
log.info("DataLoader Append - New record added Successfully. Total Number of records in table : " + str(res))
else:
msg = {"DataLoader Append hospital_append_data ERROR": "Failed in data addition, No new records added."}
log.info(msg)
return jsonify(msg), 420
# end of if status == 0:
else:
msg = {"DataLoader Append ERROR": "Wrong Workflow Name in Request - " + workflow}
log.info(msg)
return jsonify(msg), 404
# end of if (workflow.upper() == "EMPLOYEE"):
db1.session.shutdown()
end = time.time()
t = end - start
#Prepare forward request Json
for_req = {}
analytics = [{"start_time": start, "end_time": end, "elapsed_time": t, "record_count": res}]
msg = {"start_time": start, "end_time": end, "elapsed_time": t, "record_count": res}
for_req = req
for_req["analytics"] = analytics
log.info("DataLoader: Forwarding a request to the next component.......")
log.info(for_req)
# redirect
log.info("DataLoader: Work flow next component list: " + str(order[1]))
for i in order[1]:
FWD_URL = getComponentURL(str(i), ip_list[str(i)])
if FWD_URL != "http://":
log.info("--------------------------------------------------------------")
log.info("DataLoader: Calling API for the component: " + str(i))
log.info(FWD_URL)
fw_res = requests.post(FWD_URL, headers={'content-type': 'application/json'}, json=for_req, timeout=120)
if fw_res.status_code != 200:
log.info(str(fw_res.json()))
log.info("DataLoader ERROR: Fail in API call, requested service is not available: \n" + FWD_URL)
else:
log.info("DataLoader: API call is successful for component :" + str(i))
return jsonify(msg), 200
def Dataloader_Launch(req):
start = time.time()
#get request parameters
workflow = req["workflow"]
comp_name = req["client_name"]
log.info("*********** DATALOADER LAUNCH API REQUEST PARAMETERS *************")
log.info("workflow = " + workflow)
log.info("comp_name = " + comp_name)
res = 0
status1 = status2 = -1
#start workflow
log.info("DataLoader Launch - Starting workflow: " + workflow)
db1 = DataLoader()
#Check if company name is already exist if yes then get records count
tbl_name = workflow + "_" + comp_name
res = db1.validation(tbl_name)
if res <= 0:
res = db1.rec_cnt
log.info("DataLoader Launch - Creating a new table for the client: " + comp_name)
#Workflow check - Hospital flow or Employee flow and switch to the corresponding block of code
if (workflow.upper() == "EMPLOYEE"):
status1 = db1.employee_create_schema(tbl_name)
if status1 == 0:
log.info("DataLoader Launch - A new Table created successfully: " + db1.KEYSPACE + "." + tbl_name)
log.info("DataLoader Launch - Progressing initial data loading.......")
status2 = db1.employee_data_gen(tbl_name)
if status2 == 0:
log.info("DataLoader Launch - Data Loaded Successfully. Total Number of records: " + str(res))
else:
msg = {"status": 400, "dataloader": {"Dataloader_Launch ERROR": "employee_data_gen - Failed in Data generation, No records added."}}
log.info(msg)
return msg
# end of if status2 == 0:
else:
msg = {"status": 404, "dataloader": {"Dataloader_Launch ERROR": "employee_create_schema - Cassandra failed to create a new table."}}
log.info(msg)
return msg
# end of if status1 == 0:
elif (workflow.upper() == "HOSPITAL"):
status1 = db1.hospital_create_schema(tbl_name)
if status1 == 0:
log.info("DataLoader Launch - A new Table created successfully: " + db1.KEYSPACE + "." + tbl_name)
log.info("DataLoader Launch - Progressing initial data loading.......")
status2 = db1.hospital_data_gen(tbl_name)
if status2 == 0:
log.info("DataLoader Launch - Data Loaded Successfully. Total Number of records: " + str(res))
else:
msg = {"status": 400, "dataloader": {"Dataloader_Launch ERROR": "hospital_data_gen - Failed in Data generation, No records added."}}
log.info(msg)
return msg
# end of if status2 == 0:
else:
msg = {"status": 404, "dataloader": {"Dataloader_Launch ERROR": "hospital_create_schema - Cassandra failed to create a new table."}}
log.info(msg)
return msg
# end of if status1 == 0:
else:
msg = {"status": 404, "dataloader": {"Dataloader_Launch ERROR": "Wrong Workflow Name in Request - " + workflow}}
log.info(msg)
return msg
#end of if (workflow.upper() == "EMPLOYEE"):
else:
log.info("DataLoader Launch - User/Company name already active: " + comp_name)
# end of if res <= 0:
db1.session.shutdown()
end = time.time()
t = end - start
msg = {"status": 200, "workflow": workflow, "comp_name": comp_name, "dataloader": {"start_time": start, "end_time": end, "elapsed_time": t, "record_count": res}}
return msg
if __name__ == "__main__":
workflow = os.environ['workflow']
client_name = os.environ['client_name']
log.info("DataLoader: initializing the process.......")
content = {"client_name": client_name, "workflow": workflow}
with app.app_context():
st = Dataloader_Launch(content)
if st["status"] == 200:
log.info("DataLoader: started successfully.")
log.info(st)
first_call_result = st
app.run(debug=True, host="0.0.0.0", port=303)
else:
log.info("DataLoader ERROR: DataLoader Failed to start application")
log.info(str(st))
sys.exit(1)
<file_sep>## SVM
<file_sep>cassandra-driver
Flask==1.1.2
Flask-Jsonpify==1.5.0
Flask-RESTful==0.3.8
Flask-SQLAlchemy==2.4.4
PyJWT==1.7.1
pyrsistent==0.17.3
Python-EasyConfig==0.1.7
pytz==2020.1
PyYAML==5.3.1
requests==2.24.0
Resource==0.2.1
six==1.15.0
SQLAlchemy==1.3.20
twilio==6.46.0
urllib3==1.25.10
Werkzeug==1.0.1
<file_sep>Flask==1.0.2
flask-cors
pandas
numpy
requests
scikit-learn==0.22.2
cassandra-driver<file_sep># set base image (host OS)
FROM python:3.7-slim as base
# Pull small size base image
FROM base as builder
# Create libraries install layer
RUN mkdir /install
WORKDIR /install
# install dependencies
COPY requirements.txt /requirements.txt
RUN pip install --prefix=/install -r /requirements.txt
# start from base layer
FROM base
# Copy installed libraries
COPY --from=builder /install /usr/local
# Copy actual application
COPY . /app
WORKDIR /app
# command to run on container start
CMD [ "python3", "main.py" ]
<file_sep>
class timeParser:
def __init__(self, timestring):
sp = timestring.split(':')
if len(sp) == 2:
self.hour = float(sp[0])
self.min = float(sp[1])
else:
self.hour = float(timestring)
self.min = 0.0
def __lt__(self, other):
return self.hour + self.min < other.hour + other.min
def __le__(self, other):
return self.hour + self.min <= other.hour + other.min
def __gt__(self, other):
return self.hour + self.min > other.hour + other.min
def __ge__(self, other):
return self.hour + self.min >= other.hour + other.min
def __eq__(self, other):
return self.hour + self.min == other.hour + other.min
def __ne__(self, other):
return self.hour + self.min != other.hour + other.min
def __add__(self, other):
return timeParser(str(int(self.hour + other.hour)) + ':' + str(int(self.min + other.min)))
def __sub__(self, other):
return timeParser(str(int(self.hour - other.hour)) + ':' + str(int(self.min - other.min)))
<file_sep>from flask import request
class requestHandler:
# workflow ID is formed in following manner
# <workflow name>#<company name>
def __init__(self, selfID):
# selfID : "1" data loader
# "2" logistic regression
# "3" SVM
# "4" analytic
self.ID = selfID
self.workflowmap = {}
def parseReq(self, body, reqType):
if reqType == "nwf":
name = body["client_name"]
workflowName = body["workflow"]
seq = body["workflow_specification"]
IPs = body["ips"]
self._newWorkFlow(workflowName+"#"+name, seq, IPs)
return (workflowName+"#"+name, None, None)
elif reqType == "pred":
name = body["client_name"]
workflowName = body["workflow"]
data = body["data"]
analytics = body["analytics"]
return (workflowName+"#"+name, data, analytics)
def _newWorkFlow(self, workFlowID, sequence, IPs):
'''
IPs = {
"1":<IP>,
"2":<IP>,
"3":<IP>,
"4":<IP>
}
'''
idx = 0
for i in range(len(sequence)):
if self.ID in sequence[i]:
idx = i
if workFlowID not in self.workflowmap:
if i < len(sequence):
# next will be the next index
self.workflowmap[workFlowID] = IPs[sequence[idx+1]]
else:
# last component in workflow
self.workflowmap[workFlowID] = IPs["4"]
def getNextAddress(self, key):
if key not in self.workflowmap.keys():
return "error"
return self.workflowmap[key]
def getNextRequest(self, workFlowID):
pass
<file_sep>import os
from sklearn import svm
from sklearn.linear_model import SGDRegressor
from sklearn.externals import joblib
class support_vector_machine:
_model = None
def __init__(self):
self._model = SGDRegressor()
def train(self, data_x, data_y):
self._model.fit(data_x, data_y)
joblib.dump(self._model, 'svm_model.pickle')
def predict(self, X):
ret = self._model.predict(X)
return ret
def score(self, X, y):
score = self._model.score(X, y)
return score
def load_model(self, path):
path = os.path.join(os.path.dirname(
os.path.abspath(__file__)), path)
print(path)
self._model = joblib.load(path)
return self._model
def get_model(self):
return self._model
<file_sep>from cassandra.cluster import Cluster, DCAwareRoundRobinPolicy
from timeParser import timeParser
import pandas as pd
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
import numpy as np
import random
# for testing
import csv
from sklearn.feature_extraction import DictVectorizer
import time
class DataPreprocessor:
timeChoice = ["8:00", "8:30", "9:00",
"9:30", "10:00", "10:30", "11:00",
"11:30", "12:00", "12:30", "13:00",
"13:30", "14:00", "14:30", "15:00",
"15:30", "16:00", "16:30",
"17:00", "17:30", "18:00",
"18:30", "19:00", "19:30", '20:00']
timeencodeDict = {"8:00": 0, "8:30": 1, "9:00": 2,
"9:30": 3, "10:00": 4, "10:30": 5, "11:00": 6,
"11:30": 7, "12:00": 8, "12:30": 9, "13:00": 10,
"13:30": 11, "14:00": 12, "14:30": 13, "15:00": 14,
"15:30": 15, "16:00": 16, "16:30": 17,
"17:00": 18, "17:30": 19, "18:00": 20,
"18:30": 21, "19:00": 22, "19:30": 23, '20:00': 24}
dayencodeDict = {
"MON": 0, "TUE": 1, "WED": 2, "THU": 3, "FRI": 4, "SAT": 5, "SUN": 6
}
def __init__(self):
self.le_dict = {}
self.cluster = Cluster(contact_points=['10.176.67.91'], load_balancing_policy=DCAwareRoundRobinPolicy(
local_dc='datacenter1'), port=9042, protocol_version=3)
self.session = self.cluster.connect(
'ccproj_db', wait_for_all_pools=True)
self.session.execute('USE ccproj_db')
def getData(self, client):
self._countByGroup(client)
# dayOfWeek = []
# time = []
features = []
count = []
for r in self.group_count.keys():
# print("message : "+r)
sp = r.split('#')
dayrow = [0]*7
dayrow[self.dayencodeDict[sp[0]]] = 1
# dayOfWeek += dayrow
timeRow = [0]*25
timeRow[self.timeencodeDict[sp[1]]] = 1
# time += [sp[1]]
features.append(dayrow+timeRow)
count += [self.group_count[r]]
train_data = np.array(features)
target = np.array(count)
return (train_data, target)
def transform_test(self, dayOfWeek, time):
# going random if not valid input
try:
dayidx = self.dayencodeDict[dayOfWeek]
except KeyError:
dayidx = random.randint(0, 4)
try:
timeidx = self.timeencodeDict[time]
except KeyError:
timeidx = random.randint(0, 24)
dayrow = [0]*7
dayrow[dayidx] = 1
timeRow = [0]*25
timeRow[timeidx] = 1
test_data = dayrow+timeRow
# [1,2,3,4,5]
return np.array(test_data).reshape(1, -1)
def _countByGroup(self, client):
self.group_count = {}
# rows = self.session.execute('SELECT * FROM employee')
rows = self.session.execute(
'SELECT * FROM ' + client+" ALLOW FILTERING;")
# with open('employeedata.csv', newline='\n') as csvfile:
# rows = csv.reader(csvfile, delimiter=',', quotechar='|')
# next(rows)
for row in rows:
# print(row)
for t in self.timeChoice:
# key = row.DAY_OF_WEEK + ':' + t
key = row.day_of_week + '#' + t
try:
outTime = timeParser(str(row.checkin_datetime)) + \
timeParser(str(row.duration))
except ValueError:
continue
# outTime = timeParser(row[5]) + \
# timeParser(row[6])
if outTime > timeParser(t):
if key not in self.group_count.keys():
self.group_count[key] = 1
else:
self.group_count[key] += 1
def oneHotEncode2(self, df, le_dict={}):
# don't work this way
if not le_dict:
columnsToEncode = list(df.select_dtypes(
include=['category', 'object']))
train = True
else:
columnsToEncode = le_dict.keys()
train = False
for feature in columnsToEncode:
if train:
le_dict[feature] = LabelEncoder()
try:
if train:
df[feature] = le_dict[feature].fit_transform(df[feature])
else:
df[feature] = le_dict[feature].transform(df[feature])
df = pd.concat([df,
pd.get_dummies(df[feature]).rename(columns=lambda x: feature + '_' + str(x))], axis=1)
df = df.drop(feature, axis=1)
except:
print('Error encoding '+feature)
#df[feature] = df[feature].convert_objects(convert_numeric='force')
df[feature] = df[feature].apply(pd.to_numeric, errors='coerce')
return (df, le_dict)
<file_sep>flask==1.1.2
flask-cors==3.0.9
pandas
requests
numpy
cassandra-driver
scikit-learn
category-encoders<file_sep>from flask import Flask, request, jsonify, render_template
import pandas as pd
import sys
import json
import time
from io import BytesIO
import numpy as np
import requests
# from HospitalDataPreprocessor import HospitalDataPreprocessor
from svm import support_vector_machine
from DataPreprocessor import DataPreprocessor
from sklearn.model_selection import train_test_split
from requestHandler import *
import os
import sys
app = Flask(__name__)
# CORS(app)
# {name : model}
model = {}
preprocessor = {}
requestHandler = requestHandler("3")
train_start_time = 0.0
train_end_time = 0.0
@app.route("/svm/append-ip", methods=['POST'])
def append_ip():
global train_start_time
global train_end_time
global requestHandler
jsondata = request.get_json()
app.logger.info("json data : " + str(jsondata))
name = requestHandler.appendIP(jsondata)
app.logger.info("start time : " + str(train_start_time) +
" end time : " + str(train_end_time))
res = {"start_time": train_start_time, "end_time": train_end_time}
return jsonify(res)
@app.route("/svm/train", methods=['POST'])
def build_model():
'''
request body{
name: model name,
path: path to model
}
'''
global model
global preprocessor
global requestHandler
global train_start_time
global train_end_time
jsondata = request.get_json()
app.logger.info("json data : " + str(jsondata))
name, _, __ = requestHandler.parseReq(jsondata, "nwf")
# name, _, __ = requestHandler.parseReq(initReq, "fwf")
# name = jsondata["workflow"]+"#"+jsondata["client_name"]
_client = jsondata["client_name"]
_workflow = jsondata["workflow"]
client = _workflow+"_"+_client
if name not in model.keys():
_model = support_vector_machine()
model[name] = _model
app.logger.info("name key error ")
if name not in preprocessor.keys():
_preprocessor = DataPreprocessor()
preprocessor[name] = _preprocessor
app.logger.info("name key error ")
train_start_time = time.time()
app.logger.info("model start training")
dataX, datay = DataPreprocessor().getData(client)
trainX, testX, trainy, testy = train_test_split(
dataX, datay, test_size=0.2)
model[name].train(trainX, trainy)
app.logger.info("training success")
score = model[name].score(testX, testy)
train_end_time = time.time()
# payload = {"test R square": str(score),
# "result": "success",
# }
res = {"start_time": train_start_time, "end_time": train_end_time}
return jsonify(res)
def init_model(workflow, client):
global train_start_time
global train_end_time
initReq = workflow+"#"+client
name, _, __ = requestHandler.parseReq(initReq, "fwf")
print("whrkflow name : "+name)
if name not in model.keys():
_model = support_vector_machine()
model[name] = _model
if name not in preprocessor.keys():
_preprocessor = DataPreprocessor()
preprocessor[name] = _preprocessor
train_start_time = time.time()
dataX, datay = preprocessor[name].getData(workflow+"_"+client)
trainX, testX, trainy, testy = train_test_split(
dataX, datay, test_size=0.2)
model[name].train(trainX, trainy)
train_end_time = time.time()
score = model[name].score(testX, testy)
print("test score : " + str(score))
@app.route("/svm/predict", methods=['POST'])
def predict():
'''
request body{
"client_name": "amazon",
"workflow": "employee"
“data” : {"emp_id":"1","dept_type":"1",
"gender" : "male", "race": "2",
"day_of_week":"MON",
"checkin_datetime" : "8:00",
"time":"14:00"}
"analytics": [{"start_time":123,"end_time":130, “pred”: 100}]
}
'''
global model
global preprocessor
global requestHandler
jsondata = request.get_json()
app.logger.info("json data : " + str(jsondata))
name, data, analytics = requestHandler.parseReq(jsondata, "pred")
app.logger.info("name : " + str(name))
tic = time.time()
try:
dayOfWeek = data['day_of_week']
datatime = data['time']
except:
app.logger.info("wrong data format")
return "wrong data format"
if name not in model.keys():
app.logger.info("model not exist")
return "model not exist"
else:
fitmodel = model[name]
prepro = preprocessor[name]
data = prepro.transform_test(dayOfWeek, datatime)
app.logger.info(data)
pred = fitmodel.predict(data)
tok = time.time()
nextComponents = requestHandler.getNextAddress(name)
app.logger.info("next component : " + str(nextComponents))
app.logger.info("pred : " + str(pred))
analytics.append({"start_time": tic, "end_time": tok, "pred": pred[0]})
jsondata["analytics"] = analytics
for addr in nextComponents:
app.logger.info("sending request to : " + addr)
res = requests.post("http://"+addr, json=jsondata)
# app.logger.info('response :', res.text)
# except:
# app.logger.info("error in sending request")
# return "error in sending request"
# return 200 ok
return jsonify(success=True)
if __name__ == '__main__':
workflow = os.environ['workflow']
table = ""
if os.environ['client_name'] is not None:
table = os.environ['client_name']
else:
print("Provide env variables")
sys.exit(1)
# _client = jsondata["client_name"]
# _workflow = jsondata["workflow"]
# client = workflow+"_"+table
print('*loading SVM model...')
# init_model(data)
init_model(workflow, table)
print('*starting flask app...')
# host='0.0.0.0', port=8765
app.run(debug=True, host="0.0.0.0", port=8765)
<file_sep>import requests
import logging as log
import random
from flask import Flask, request, jsonify
from flask_restful import Api
from cassandra.cluster import Cluster
from timeit import default_timer as timer
from datetime import timedelta
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
api = Api(app)
##################################################
def getComponentURL(n, ip_add):
url_string = "http://"
if n == "2":
url_string = url_string + ip_add + "/lgr/predict"
elif n == "3":
url_string = url_string + ip_add + "/lgr/predict" #"/svm/predict"
elif n == "4":
url_string = url_string + ip_add + "/lgr/predict" #"/analytics"
else:
msg = "DataLoader Error getComponentURL: Unable to find the service component, no Service component found with code: " + n
log.info(msg)
print(msg)
return url_string
#################################################
class DataLoader:
KEYSPACE=0
cluster=0
session=0
rec_cnt=100
def __init__(self):
self.KEYSPACE = "ccproj_db"
self.cluster = Cluster(['10.176.67.91'])
self.session = self.cluster.connect()
self.session.set_keyspace(self.KEYSPACE)
def validation(self, usr_name):
result = 0
qry = "SELECT COUNT(*) FROM " + usr_name + ";"
try:
stat = self.session.prepare(qry)
x = self.session.execute(stat)
for row in x:
result = row.count
except:
result = -1
log.info("DataLoader validation: No Table found in Cassandra database.")
print("DataLoader validation: No Table found in Cassandra database.")
return result
def employee_create_schema(self, usr_name):
status = 0
stat1 = "CREATE TABLE IF NOT EXISTS " + usr_name + """(
UU_ID UUID PRIMARY KEY,
EMP_ID DECIMAL,
DEPT_TYPE TEXT,
GENDER TEXT,
RACE TEXT,
DAY_OF_WEEK TEXT,
CHECKIN_DATETIME TEXT,
DURATION TEXT);"""
try:
cre_tbl = self.session.prepare(stat1)
self.session.execute(cre_tbl)
except:
status = -1
self.session.shutdown()
return status
def employee_data_gen(self, usr_name):
# define constants
status = 0
dept1 = ["1", "2", "3", "4", "5", "6"]
gender1 = ["male", "female"]
race1 = ["1", "2", "3", "4", "5", "6"]
day1 = ['MON', "TUE", 'WED', 'THU', "FRI"]
checkin1 = ["8:00", "8:30", "9:00",
"9:30", "10:00", "10:30",
"11:00", "11:30", "12:00",
"12:30", "13:00", "13:30", "14:00"]
duration1 = ["1", "2", "3", "4", "5", "6", "7", "8"]
# Insert query format
ins_stat = "INSERT INTO " + usr_name + """(UU_ID, EMP_ID, DEPT_TYPE, GENDER, RACE, DAY_OF_WEEK, CHECKIN_DATETIME, DURATION)
VALUES (now(), ?, ?, ?, ?, ?, ?, ?)"""
try:
insert_q = self.session.prepare(ins_stat)
# generate data
for i in range(1, self.rec_cnt + 1):
empid = i
dept = random.choice(dept1)
gender = random.choice(gender1)
race = random.choice(race1)
day = random.choice(day1)
checkin = random.choice(checkin1)
duration = random.choice(duration1)
self.session.execute(insert_q, [empid, dept, gender, race, day, checkin, duration])
except:
status = -1
self.session.shutdown()
return status
def employee_append_data(self, usr_name, data):
# define constants
status = 0
empid = data["emp_id"]
dept1 = data["dept_type"]
gender1 = data["gender"]
race1 = data["race"]
day1 = data["day_of_week"]
checkin1 = data["checkin_datetime"]
duration1 = data["duration"]
# Insert query format
ins_stat = "INSERT INTO " + usr_name + """(UU_ID, EMP_ID, DEPT_TYPE, GENDER, RACE, DAY_OF_WEEK, CHECKIN_DATETIME, DURATION)
VALUES (now(), ?, ?, ?, ?, ?, ?, ?)"""
try:
insert_q = self.session.prepare(ins_stat)
#generate data
self.session.execute(insert_q, [empid, dept1, gender1, race1, day1, checkin1, duration1])
except:
status = -1
self.session.shutdown()
return status
def hospital_create_schema(self, usr_name):
status = 0
stat1 = "CREATE TABLE IF NOT EXISTS " + usr_name + """(
uu_id UUID PRIMARY KEY,
hadm_id DECIMAL,
hospital_expire_flag DECIMAL,
insurance DECIMAL,
total_time_icu DECIMAL,
num_in_icu DECIMAL,
amount DECIMAL,
rate DECIMAL,
total_items DECIMAL,
value DECIMAL,
dilution_value DECIMAL,
abnormal_count DECIMAL,
item_distinct_abnormal DECIMAL,
checkin_time TEXT);"""
try:
cre_tbl = self.session.prepare(stat1)
self.session.execute(cre_tbl)
except:
status = -1
self.session.shutdown()
return status
# hospital Data generator
def hospital_data_gen(self, usr_name):
# define constants
status = 0
hospital_expire_flag1 = [1, 2]
insurance1 = [1, 2, 3, 4, 5]
checkin_time1 = ["00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00",
"06:30","07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30"]
# Insert query format
ins_stat = "INSERT INTO " + usr_name + """ (uu_id, hadm_id, hospital_expire_flag, insurance, total_time_icu, num_in_icu,
amount, rate, total_items, value, dilution_value, abnormal_count, item_distinct_abnormal, checkin_time)
VALUES (now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
try:
insert_q = self.session.prepare(ins_stat)
#generate data
for i in range(1000, self.rec_cnt + 1000):
hadm_id = i
hospital_expire_flag = random.choice(hospital_expire_flag1)
insurance = random.choice(insurance1)
total_time_icu = random.uniform(0.002428259, 1)
num_in_icu = random.uniform(0.142857143, 1)
amount = random.uniform(-0.013434843, 1)
rate = random.uniform(0, 1)
total_items = random.uniform(0.093117409, 1)
value = random.uniform(0.000110609, 1)
dilution_value = random.uniform(0, 1)
abnormal_count = random.uniform(0.001908852, 1)
item_distinct_abnormal = random.uniform(0.059405941, 1)
checkin_time = random.choice(checkin_time1)
self.session.execute(insert_q,
[hadm_id, hospital_expire_flag, insurance, total_time_icu, num_in_icu, amount, rate,
total_items, value, dilution_value, abnormal_count, item_distinct_abnormal, checkin_time])
except:
status = -1
self.session.shutdown()
return status
def hospital_append_data(self, usr_name, data):
# define constants
status = 0
# Insert query format
ins_stat = "INSERT INTO " + usr_name + """ (uu_id, hadm_id, hospital_expire_flag, insurance, total_time_icu, num_in_icu,
amount, rate, total_items, value, dilution_value, abnormal_count, item_distinct_abnormal, checkin_time)
VALUES (now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
try:
insert_q = self.session.prepare(ins_stat)
#generate data
hadm_id = data["hadm_id"]
hospital_expire_flag = data["hospital_expire_flag"]
insurance = data["insurance"]
total_time_icu = data["total_time_icu"]
num_in_icu = data["num_in_icu"]
amount = data["amount"]
rate = data["rate"]
total_items = data["total_items"]
value = data["value"]
dilution_value = data["dilution_value"]
abnormal_count = data["abnormal_count"]
item_distinct_abnormal = data["item_distinct_abnormal"]
checkin_time = data["checkin_time"]
self.session.execute(insert_q,
[hadm_id, hospital_expire_flag, insurance, total_time_icu, num_in_icu, amount, rate,
total_items, value, dilution_value, abnormal_count, item_distinct_abnormal, checkin_time])
except:
status = -1
self.session.shutdown()
return status
def __del__(self):
self.session.shutdown()
print("Object Destroyed")
class DLError(Exception):
"""Custom exception class to be thrown when local error occurs."""
def __init__(self, message, status, payload=None):
self.message = message
self.status = status
self.payload = payload
@app.errorhandler(DLError)
def handle_bad_request(error):
"""Catch BadRequest exception globally, serialize into JSON, and respond with 400."""
payload = dict(error.payload or ())
payload['status'] = error.status
payload['message'] = error.message
return jsonify(payload), error.status
@app.route("/dataloader", methods=['POST', 'GET'])
def dataloader():
start = timer()
#get request parameters
req = request.get_json()
workflow = req["workflow"]
comp_name = req["client_name"]
order = list(req["workflow_specification"])
ip_list = req["ips"]
res = 0
status1 = status2 = -1
#start workflow
log.info("DataLoader: Starting workflow: " + workflow)
db1 = DataLoader()
#Check if company name is already exist if yes then get records count
res = db1.validation(comp_name)
if res <= 0:
res = db1.rec_cnt
log.info("DataLoader: Creating a new table for the client: " + comp_name)
print("DataLoader: Creating a new table for the client: " + comp_name)
#Workflow check - Hospital flow or Employee flow and switch to the corresponding block of code
if (workflow.upper() == "EMPLOYEE"):
status1 = db1.employee_create_schema(comp_name)
if status1 == 0:
log.info("DataLoader: A new Table created successfully: " + db1.KEYSPACE + "." + comp_name)
print("DataLoader: A new Table created successfully: " + db1.KEYSPACE + "." + comp_name)
log.info("DataLoader: Progressing initial data loading.......")
print("DataLoader: Progressing initial data loading.......")
status2 = db1.employee_data_gen(comp_name)
if status2 == 0:
log.info("DataLoader: Data Loaded Successfully. Total Number of records: " + str(res))
print("DataLoader: Data Loaded Successfully. Total Number of records: " + str(res))
else:
log.info("DataLoader ERROR: Failed in Data generation, No records added.")
print("DataLoader ERROR: Failed in Data generation, No records added.")
raise DLError('DataLoader ERROR - Failed in Data generation, No records added.', 400, { 'ext': 1 })
# end of if status2 == 0:
else:
log.info("DataLoader ERROR: Cassandra failed to create a new table.")
print("DataLoader Error: Cassandra failed to create a new table.")
raise DLError('DataLoader ERROR - Cassandra failed to create a new table.', 404, { 'ext': 1 })
# end of if status1 == 0:
elif (workflow.upper() == "HOSPITAL"):
status1 = db1.hospital_create_schema(comp_name)
if status1 == 0:
log.info("DataLoader: A new Table created successfully: " + db1.KEYSPACE + "." + comp_name)
print("DataLoader: A new Table created successfully: " + db1.KEYSPACE + "." + comp_name)
log.info("DataLoader: Progressing initial data loading.......")
print("DataLoader: Progressing initial data loading.......")
status2 = db1.hospital_data_gen(comp_name)
if status2 == 0:
log.info("DataLoader: Data Loaded Successfully. Total Number of records: " + str(res))
print("DataLoader: Data Loaded Successfully. Total Number of records: " + str(res))
else:
log.info("DataLoader ERROR: Failed in Data generation, No records added.")
print("DataLoader ERROR: Failed in Data generation, No records added.")
raise DLError('DataLoader ERROR - Failed in Data generation, No records added.', 400, {'ext': 1})
# end of if status2 == 0:
else:
log.info("DataLoader ERROR: Cassandra failed to create a new table.")
print("DataLoader Error: Cassandra failed to create a new table.")
raise DLError('DataLoader ERROR - Cassandra failed to create a new table.', 404, {'ext': 1})
# end of if status1 == 0:
else:
log.info("DataLoader ERROR: Wrong Workflow Name in Request: " + workflow)
print("DataLoader ERROR: Wrong Workflow Name in Request: " + workflow)
raise DLError('DataLoader ERROR - Wrong Workflow Name in Request', 404, {'ext': 1})
#end of if (workflow.upper() == "EMPLOYEE"):
else:
log.info("DataLoader: User/Company name already active: " + comp_name)
print("DataLoader: User/Company name already active: " + comp_name)
# end of if res <= 0:
db1.session.shutdown()
end = timer()
t = str(timedelta(seconds=end - start))
dataloader = "start_time:" + str(start) + ", end_time:" + str(end) + ", elapsed_time:" + str(t) + ", records_added:" + str(res)
raise DLError(dataloader, 200, {'ext': 0})
@app.route("/dataflow_append", methods=['POST', 'GET'])
def dataflow_append():
start = timer()
# get request parameters
req = request.get_json()
workflow = req["workflow"]
comp_name = req["client_name"]
order = list(req["workflow_specification"])
ip_list = req["ips"]
data = req["data"]
res = 0
status = -1
# start workflow
log.info("DataLoader: Starting workflow: " + workflow)
db1 = DataLoader()
# Workflow check - Hospital flow or Employee flow and switch to the corresponding block of code
if (workflow.upper() == "EMPLOYEE"):
log.info("DataLoader: Appending new data to the table.......")
print("DataLoader: Appending new data to the table.......")
status = db1.employee_append_data(comp_name, data)
if status == 0:
res = db1.validation(comp_name)
log.info("DataLoader: new record added Successfully. Total Number of records in table : " + str(res))
print("DataLoader: new record added Successfully. Total Number of records in table : " + str(res))
else:
log.info("DataLoader ERROR: Failed in data addition, No new records added.")
print("DataLoader ERROR: Failed in data addition, No new records added.")
raise DLError('DataLoader ERROR - Failed in data addition, No new records added.', 400, {'ext': 1})
# end of if status == 0:
elif (workflow.upper() == "HOSPITAL"):
log.info("DataLoader: Appending new data to the table.......")
print("DataLoader: Appending new data to the table.......")
status = db1.hospital_append_data(comp_name, data)
if status == 0:
res = db1.validation(comp_name)
log.info("DataLoader: new record added Successfully. Total Number of records in table : " + str(res))
print("DataLoader: new record added Successfully. Total Number of records in table : " + str(res))
else:
log.info("DataLoader ERROR: Failed in data addition, No new records added.")
print("DataLoader ERROR: Failed in data addition, No new records added.")
raise DLError('DataLoader ERROR - Failed in data addition, No new records added.', 400, {'ext': 1})
# end of if status == 0:
else:
log.info("DataLoader ERROR: Wrong Workflow Name in Request: " + workflow)
print("DataLoader ERROR: Wrong Workflow Name in Request: " + workflow)
raise DLError('DataLoader ERROR - Wrong Workflow Name in Request', 404, {'ext': 1})
# end of if (workflow.upper() == "EMPLOYEE"):
db1.session.shutdown()
end = timer()
t = str(timedelta(seconds=end - start))
msg = "start_time:" + str(start) + ", end_time:" + str(end) + ", elapsed_time:" + str(t) + ", records_added:" + str(res)
db1.session.shutdown()
end = timer()
t = str(timedelta(seconds=end - start))
#Prepare forward request Json
for_req = {}
analytics = [{"start_time": start, "end_time": end, "elapsed_time": t, "record_count": res}]
for_req["request"] = req
for_req["analytics"] = analytics
log.info("DataLoader: Forwarding a request to the next component.......")
print("DataLoader: Forwarding a request to the next component.......")
print(for_req)
# redirect
for i in order[1]:
print("order " + str(i))
FWD_URL = getComponentURL(str(i), ip_list[str(i)])
if FWD_URL != "http://":
requests.post(FWD_URL, headers={'content-type': 'application/json'}, json=for_req)
log.info("DataLoader is forwarding a request to the next component:")
log.info(FWD_URL)
print("DataLoader is forwarding a request to the next component:")
print(FWD_URL)
raise DLError(msg, 200, {'ext': 0})
#api.add_resource(employee_dataloader, "/employee_dataloader")
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=303)
<file_sep>FROM python:3.7-slim as base
FROM base as builder
RUN mkdir /install
WORKDIR /install
COPY requirement.txt /requirement.txt
RUN pip install --prefix=/install -r /requirement.txt
FROM base
COPY --from=builder /install /usr/local
COPY . /app
WORKDIR /app
ENV workflow=${workflow}
ENV client_name=${client_name}
CMD [ "python3", "model.py" ]
<file_sep># logisticregression-docker-image<file_sep>### Analytics Component Ports
#### PORTS
Define 6 dedicated ports for analytics please avoid these six ports for other components.
- 12340,12341,12342,12343,12344,12345
Routes
- http://10.176.67.91/:12340/analytics_0
- http://10.176.67.91/:12341/analytics_1
- http://10.176.67.91/:12342/analytics_2
- http://10.176.67.91/:12343/analytics_3
- http://10.176.67.91/:12344/analytics_4
- http://10.176.67.91/:12345/analytics_5
#### APIs
1.
```
/get_name
```
Get workflow name and client name and workflow specification.
2.
```
/analytics_init
```
Initilzes analytics component call with workflow start request.
3.
```
/put_result
```
Send result to analytics call with prediction request.
4.
```
/get_result
```
Get all prediction result call by client.
<file_sep># set base image (host OS)
FROM python:3.8 as base
FROM base as builder
ENV workflow=${workflow}
ENV client_name=${client_name}
# set the working directory in the container
WORKDIR /usr/src/app
# copy the content of the local src directory to the working directory
COPY src/ .
COPY requirements.txt .
# install dependencies
RUN pip install --no-cache-dir -r requirements.txt
# command to run on container start
CMD [ "python", "./DataLoader.py" ]
<file_sep>from flask import Flask, request
import requests
import subprocess
import sys
import time
import json
from flask_cors import CORS
import logging
import threading
app = Flask(__name__)
CORS(app)
@app.route('/')
def index():
return 'Server is alive!!'
# http://d925019d0b9d.ngrok.io/graph?g0.expr=(1%20-%20avg(irate(node_cpu_seconds_total%7Bmode%3D%22idle%22%2Cinstance%3D~%2210.*%22%7D%5B10m%5D))%20by%20(instance))%20*%20100&g0.tab=0&g0.stacked=0&g0.range_input=1h&g1.expr=100%20*%20(1%20-%20((avg_over_time(node_memory_MemFree_bytes%7Binstance%3D~%2210.*%22%7D%5B1m%5D)%20%2B%20avg_over_time(node_memory_Cached_bytes%7Binstance%3D~%2210.*%22%7D%5B1m%5D)%20%2B%20avg_over_time(node_memory_Buffers_bytes%7Binstance%3D~%2210.*%22%7D%5B1m%5D))%20%2F%20avg_over_time(node_memory_MemTotal_bytes%7Binstance%3D~%2210.*%22%7D%5B1m%5D)))&g1.tab=0&g1.stacked=0&g1.range_input=1h&g2.expr=sum(irate(node_network_transmit_bytes_total%7Binstance%3D~%2210.*%22%2C%20device!~%22lo%7Cbr.*%7Cveth.*%22%7D%5B1m%5D))%20by%20(instance)&g2.tab=0&g2.stacked=0&g2.range_input=1h&g3.expr=sum(irate(node_network_receive_bytes_total%7Binstance%3D~%2210.*%22%2C%20device!~%22lo%7Cbr.*%7Cveth.*%22%7D%5B1m%5D))%20by%20(instance)&g3.tab=0&g3.stacked=0&g3.range_input=1h
# CPU
# (1 - avg(irate(node_cpu_seconds_total{mode="idle",instance=~"10.*"}[10m])) by (instance)) * 100
# Memory
# 100 * (1 - ((avg_over_time(node_memory_MemFree_bytes{instance=~"10.*"}[1m]) + avg_over_time(node_memory_Cached_bytes{instance=~"10.*"}[1m]) + avg_over_time(node_memory_Buffers_bytes{instance=~"10.*"}[1m])) / avg_over_time(node_memory_MemTotal_bytes{instance=~"10.*"}[1m])))
# Network
# sum(irate(node_network_transmit_bytes_total{instance=~"10.*", device!~"lo|br.*|veth.*"}[1m])) by (instance)
# sum(irate(node_network_receive_bytes_total{instance=~"10.*", device!~"lo|br.*|veth.*"}[1m])) by (instance)
# sudo docker service ls --format {{.ID}} | while read line ; do sudo docker service ps $line | sed '1 d'; done;
# sudo docker service ls --format {{.ID}} | while read line ; do sudo docker service rm $line; done;
# command="docker service create --restart-condition=none -qd --name " + name + " busybox sleep 100"
#
# /opt/cassandra/bin/cqlsh
# SELECT * FROM system_schema.keyspaces;
# SELECT * FROM system_schema.tables WHERE keyspace_name = 'ccproj_db';
# DELETE FROM system_schema.tables WHERE keyspace_name = 'ccproj_db' AND table_name = 'client1';
# sudo docker service ls --format {{.ID}} | while read line ; do sudo docker service ps $line -f desired-state=Running | sed '1 d';done;
# sudo docker node ps -f desired-state=running managernode
ipList = {'managernode': '10.176.67.91', 'workernode2':'10.176.67.93', 'workernode1':'10.176.67.92'}
workflowInstances = {
'employee': dict(),
'hospital': dict(),
'ipsHashMap' : {'employee': dict(), 'hospital': dict()}
}
noReuseWorkflowInstances = {'employee': dict(), 'hospital': dict()}
isDbAlreadyLaunched = False
def isDBRunning():
global isDbAlreadyLaunched
return isDbAlreadyLaunched
def setDBToRunning():
global isDbAlreadyLaunched
isDbAlreadyLaunched = True
currAnalystPorCount=-1
anaylstPortList = [12340,12341,12342,12343,12344,12345,12346,12347,12348,12349]
def getAnalystPort():
global currAnalystPorCount
currAnalystPorCount = currAnalystPorCount + 1
return str(anaylstPortList[currAnalystPorCount])
glPort = 4000
def getPort():
global glPort
glPort = glPort + 1
return str(glPort)
@app.route('/noreuse/request', methods=['GET', 'POST'])
def initWorkflow1():
jsonContent = request.get_json()
workflow = jsonContent["workflow"]
client_name = jsonContent["client_name"]
seq = jsonContent["workflow_specification"]
if clientExists(workflow, client_name):
logging.warning("Deployment request is already done for " + workflow + ":" + client_name)
return "FAILED\n"
if (workflow == "employee") | (workflow == "hospital"):
noReuseWorkflowInstances[workflow][client_name] = dict()
for i, li in enumerate(seq):
for j, item in enumerate(li):
if (launchContainer(item, workflow ,client_name, getPort(),"NOREUSE") == False):
killContainers(workflow ,client_name,seq, i, j,"REUSE")
noReuseWorkflowInstances[workflow].pop(client_name,None)
logging.warning(noReuseWorkflowInstances)
return "FAILED\n"
launchAnalyst("4", workflow, client_name, getAnalystPort(),"NOREUSE")
noReuseWorkflowInstances[workflow][client_name]["seq"] = seq
makeAPIRequestToSendIPs(workflow,client_name, seq,"NOREUSE")
logging.warning("Internal noreuse HashMap: " + json.dumps(noReuseWorkflowInstances))
return noReuseWorkflowInstances[workflow][client_name]["4"]
else:
logging.warning("Invalid workflow specified")
return "FAILED\n"
@app.route('/reuse/request', methods=['GET', 'POST'])
def initWorkflow2():
jsonContent = request.get_json()
workflow = jsonContent["workflow"]
client_name = jsonContent["client_name"]
seq = jsonContent["workflow_specification"]
if clientExists(workflow, client_name):
logging.warning("Deployment request is already done for " + workflow + ":" + client_name)
return "FAILED\n"
if (workflow == "employee") | (workflow == "hospital"):
if len(workflowInstances['ipsHashMap'][workflow]) == 0:
workflowInstances[workflow][client_name] = dict()
for i, li in enumerate(seq):
for j, item in enumerate(li):
if (launchContainer(item, workflow ,client_name, getPort(), "REUSE") == False):
killContainers(workflow ,client_name,seq, i, j,"REUSE")
workflowInstances[workflow].pop(client_name,None)
workflowInstances['ipsHashMap'][workflow] = dict()
logging.warning(workflowInstances)
return "FAILED\n"
launchAnalyst("4", workflow, client_name, getAnalystPort(),"REUSE")
workflowInstances[workflow][client_name]["seq"] = seq
makeAPIRequestToSendIPs(workflow,client_name, seq,"REUSE")
else:
workflowInstances[workflow][client_name] = dict()
launchAnalyst("4", workflow, client_name, getAnalystPort(),"REUSE")
workflowInstances[workflow][client_name]["seq"] = seq
if makeAPIRequestToTrain(seq,workflow,client_name,"REUSE") == False:
KillAnalyst(workflow, client_name,"REUSE")
workflowInstances[workflow].pop(client_name,None)
logging.warning(workflowInstances)
return "FAILED\n"
logging.warning("Internal reuse HashMap: " + json.dumps(workflowInstances))
return workflowInstances[workflow][client_name]["4"]
else:
logging.warning("Invalid workflow specified")
return "FAILED\n"
def clientExists(workflow, client_name):
if client_name in workflowInstances[workflow]:
return True
if client_name in noReuseWorkflowInstances[workflow]:
return True
return False
def makeAPIRequestToSendIPs(request,wflowname,seq,deploymentType):
pd = formData(request, wflowname,deploymentType)
analyticsArr = []
flat_list = [item for sublist in seq for item in sublist]
for i,component in enumerate(flat_list):
if component == "1":
logging.warning("Making API request for sending IPs to Component DL Data: " + json.dumps(pd))
resp = requests.post(url = "http://" + getIP(request,wflowname,"1",deploymentType) + "/dataloader", headers={'content-type': 'application/json'}, json = pd)
if resp.status_code == 200:
analyticsArr.append(resp.json())
else:
logging.warning("Error: API response code is NON-200 when sending IP's to dataloader")
elif component == "2":
logging.warning("Making API request for sending IPs to Component LR Data: " + json.dumps(pd))
resp = requests.post(url = "http://" + getIP(request,wflowname,"2",deploymentType) + "/lgr/ipwfspec", headers={'content-type': 'application/json'}, json = pd)
if resp.status_code == 200:
analyticsArr.append(resp.json())
else:
logging.warning("Error: API response code is NON-200 when sending IP's to Logistic regression")
elif component == "3":
logging.warning("Making API request for sending IPs to Component SVM Data: " + json.dumps(pd))
resp = requests.post(url = "http://" + getIP(request,wflowname,"3",deploymentType) + "/svm/append-ip", headers={'content-type': 'application/json'}, json = pd)
if resp.status_code == 200:
analyticsArr.append(resp.json())
else:
logging.warning("Error: API response code is NON-200 when sending IP's to SVM")
pd["analytics"] = analyticsArr
pd["requestID"] = 1
logging.warning("Making API request to send details to Analytics component with Data: " + json.dumps(pd))
requests.post(url = "http://" + getIP(request,wflowname,"4",deploymentType) + "/put_result", headers={'content-type': 'application/json'}, json = pd)
def getIP(request,wflowname,item,deploymentType):
if deploymentType == "REUSE":
if item == "1":
return workflowInstances['ipsHashMap'][request]["1"]
elif item == "2":
return workflowInstances['ipsHashMap'][request]["2"]
elif item == "3":
return workflowInstances['ipsHashMap'][request]["3"]
elif item == "4":
return workflowInstances[request][wflowname]["4"]
else:
if item == "1":
return noReuseWorkflowInstances[request][wflowname]["1"]
elif item == "2":
return noReuseWorkflowInstances[request][wflowname]["2"]
elif item == "3":
return noReuseWorkflowInstances[request][wflowname]["3"]
elif item == "4":
return noReuseWorkflowInstances[request][wflowname]["4"]
def makeAPIRequestToTrain(seq,request,wflowname,deploymentType):
pd = formData(request, wflowname,deploymentType)
analyticsArr = []
for i, li in enumerate(seq):
for j, item in enumerate(li):
if (item == "1"):
logging.warning("Making API request for start training to Component DL Data: " + json.dumps(pd))
resp = requests.post(url = "http://" + getIP(request,wflowname,"1",deploymentType) + "/dataloader", headers={'content-type': 'application/json'}, json = pd)
# resp = requests.post(url = 'https://c0cbf714b395e1ce81b2f6c804ee2b35.m.pipedream.net', headers={'content-type': 'application/json'}, json = pd)
if resp.status_code != 200:
logging.warning("Error: API response code is NON-200 when training request made to dataloader")
return False
analyticsArr.append(resp.json())
elif (item == "2"):
logging.warning("Making API request for start training to Component LR Data: " + json.dumps(pd))
resp = requests.post(url = "http://" + getIP(request,wflowname,"2",deploymentType) + "/lgr/train", headers={'content-type': 'application/json'}, json = pd)
if resp.status_code != 200:
logging.warning("Error: API response code is NON-200 when training request made to logistic regression")
return False
analyticsArr.append(resp.json())
elif (item == "3"):
logging.warning("Making API request for start training to Component SVM Data: " + json.dumps(pd))
resp = requests.post(url = "http://" + getIP(request,wflowname,"3",deploymentType) + "/svm/train", headers={'content-type': 'application/json'}, json = pd)
if resp.status_code != 200:
logging.warning("Error: API response code is NON-200 when training request made to SVM")
return False
analyticsArr.append(resp.json())
pd["analytics"] = analyticsArr
pd["requestID"] = 1
logging.warning("Making API request for start training to Analytics component with Data: " + json.dumps(pd))
requests.post(url = "http://" + getIP(request,wflowname,"4",deploymentType) + "/put_result", headers={'content-type': 'application/json'}, json = pd)
return True
def formData(request,wflowname,deploymentType):
data = dict()
data['client_name'] = wflowname
data['workflow'] = request
if deploymentType == "NOREUSE":
data['workflow_specification'] = noReuseWorkflowInstances[request][wflowname]["seq"]
data['ips'] = noReuseWorkflowInstances[request][wflowname]
else:
data['workflow_specification'] = workflowInstances[request][wflowname]["seq"]
data['ips'] = workflowInstances['ipsHashMap'][request]
data['ips']['4'] = workflowInstances[request][wflowname]["4"]
return data
def killContainers(request,wflowname,seq, k, l,deploymentType):
for i in range(k+1):
for j in range(len(seq[i])):
if i == k & j == l:
killContainer(request,wflowname,seq[i][j],deploymentType)
break
killContainer(request,wflowname,seq[i][j],deploymentType)
def killContainer(request,wflowname,item,deploymentType):
if (item == "1"):
return KillDBAndDL(request,wflowname,deploymentType)
elif (item == "2"):
return KillLR(request,wflowname,deploymentType)
elif (item == "3"):
return KillSVM(request,wflowname,deploymentType)
elif (item == "4"):
return KillAnalyst(request,wflowname,deploymentType)
def KillDBAndDL(request,wflowname,deploymentType):
# TODO
# subprocess.Popen("docker service rm db", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
name = getContainerName("dataloader",request,wflowname,deploymentType)
subprocess.Popen("docker service rm "+name, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def KillLR(request,wflowname,deploymentType):
name = getContainerName("logisticregression",request,wflowname,deploymentType)
subprocess.Popen("docker service rm "+name, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def KillSVM(request,wflowname,deploymentType):
name = getContainerName("svm",request,wflowname,deploymentType)
subprocess.Popen("docker service rm "+name, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def KillAnalyst(request,wflowname,deploymentType):
name = getContainerName("analyst",request,wflowname,deploymentType)
subprocess.Popen("docker stop "+name, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
subprocess.Popen("docker rm "+name, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def launchContainer(item,request,wflowname, port, deploymentType):
if (item == "1"):
return launchDBAndDL(item,request,wflowname, port, deploymentType)
elif (item == "2"):
return launchLR(item,request,wflowname, port, deploymentType)
elif (item == "3"):
return launchSVM(item,request,wflowname, port, deploymentType)
def launchDBAndDL(item,request,wflowname, port, deploymentType):
if isDBRunning() == False:
command = "docker stack deploy -c cassandra-compose.yml cassandra"
logging.warning("Initializing Cassandra database, waiting for 90sec..")
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
time.sleep(90)
logging.warning("Cassandra database initialization is done.")
setDBToRunning()
else:
logging.warning("Cassandra database initialization is already done.")
name = getContainerName("dataloader",request,wflowname,deploymentType)
command ="docker service create -p " + port + ":303" + " --restart-condition=none -qd --env workflow=" + request + " --env client_name=" + wflowname + " --name " + name + " ayutiwari/data_loader:2.0"
logging.warning("Initializing data loader, waiting for 20sec..")
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if not ((error == None) | (error.decode().strip() == "")):
logging.warning("Error while running command: '{}'. Error: '{}'".format(command, error.decode()))
logging.warning("Above command output: " + output.decode())
return False
time.sleep(20)
if (checkStatus(item,request,wflowname,output.decode(), port, deploymentType) == False):
logging.warning("Error while running command: '{}'. Error: '{}'".format(command, error.decode()))
logging.warning("Above command output: " + output.decode())
return False
logging.warning("Data loader initialization is done.")
return True
def launchLR(item,request,wflowname, port, deploymentType):
name = getContainerName("logisticregression",request,wflowname,deploymentType)
logging.warning("Initializing Logistic regression model, waiting for 20sec..")
command ="docker service create -p " + port + ":50" + " --restart-condition=none -qd --env workflow=" + request + " --env client_name=" + wflowname + " --name " + name + " gaderut/cc4_lgr:1.0"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if not ((error == None) | (error.decode().strip() == "")):
logging.warning("Error while running command: '{}'. Error: '{}'".format(command, error))
logging.warning("Above command output: " + output.decode())
return False
time.sleep(20)
if (checkStatus(item,request,wflowname,output.decode(), port,deploymentType) == False):
logging.warning("Error while running command: '{}'. Error: '{}'".format(command, error.decode()))
logging.warning("Above command output: " + output.decode())
return False
logging.warning("Logistic regression model initialization is done.")
return True
def launchSVM(item,request,wflowname, port, deploymentType):
name = getContainerName("svm",request,wflowname,deploymentType)
logging.warning("Initializing SVM model, waiting for 20sec..")
command ="docker service create -p " + port + ":8765" + " --restart-condition=none -qd --env workflow=" + request + " --env client_name=" + wflowname + " --name " + name + " conradyen/svm-component"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if not ((error == None) | (error.decode().strip() == "")):
logging.warning("Error while running command: '{}'. Error: '{}'".format(command, error.decode()))
logging.warning("Above command output: " + output.decode())
return False
time.sleep(20)
if (checkStatus(item,request,wflowname,output.decode(), port,deploymentType) == False):
logging.warning("Error while running command: '{}'. Error: '{}'".format(command, error.decode()))
logging.warning("Above command output: " + output.decode())
return False
logging.warning("SVM model initialization is done.")
return True
def launchAnalyst(item,request,wflowname, port, deploymentType):
name = getContainerName("analyst",request,wflowname,deploymentType)
logging.warning("Initializing Analyst, waiting for 20sec..")
command = "docker run -d -p "+port+":12345" + " --name " + name + " --env WORKFLOW=" + request + " --env CLIENT_NAME=" + wflowname+ " conradyen/analytics"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if not ((error == None) | (error.decode().strip() == "")):
logging.warning("Error while running command: '{}'. Error: '{}'".format(command, error.decode()))
logging.warning("Above command output: " + output.decode())
return False
time.sleep(20)
if (containerExist(name) == False):
return False
if deploymentType == "NOREUSE":
noReuseWorkflowInstances[request][wflowname][item] = "10.176.67.91:"+port
else:
workflowInstances[request][wflowname][item] = "10.176.67.91:"+port
logging.warning("Analyst initialization is done.")
return True
def getContainerName(suffix, request,wflowname,deploymentType):
if suffix == "analyst":
return request+"-"+wflowname+"-"+suffix
if deploymentType == "REUSE":
return request+"-"+suffix
return request+"-"+wflowname+"-"+suffix
def checkStatus(item,request,wflowname,uid, port, deploymentType):
command = 'sudo docker service ps --format {{.Node}},{{.DesiredState}} ' + uid
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if not ((error == None) | (error.decode().strip() == "")):
logging.warning("Error during checkStatus command: '{}', Error: '{}'".format(command, error.decode()))
logging.warning("Above command output: " + output.decode())
return False
res = output.decode().strip().split(",")
if (res[1].lower() == "running"):
if deploymentType == "NOREUSE":
noReuseWorkflowInstances[request][wflowname][item] = ipList[res[0]]+":"+port
else:
workflowInstances['ipsHashMap'][request][item] = ipList[res[0]]+":"+port
return True
logging.warning("Error component is not running: '{}'".format(output.decode()))
return False
def containerExist(containerName):
bashCommand = "docker ps --filter name={}| sed '1 d'".format(containerName)
process = subprocess.Popen(bashCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if not ((error == None) | (error.decode().strip() == "")):
logging.warning("Error analyst did not launch for: " + containerName)
logging.warning("Error: " + error.decode())
logging.warning("Output: " + output.decode())
return False
if (len(output) > 0):
return True
logging.warning("Error analyst did not launch for: " + containerName)
return False
@app.route('/predict', methods=['GET', 'POST'])
def predict():
jsonContent = request.get_json()
workflow = jsonContent["workflow"]
client_name = jsonContent["client_name"]
logging.warning("Making prediction request to Dataloader with data: " + json.dumps(jsonContent))
url = ""
if client_name in workflowInstances[workflow]:
url = workflowInstances['ipsHashMap'][workflow]["1"]
elif client_name in noReuseWorkflowInstances[workflow]:
url = noReuseWorkflowInstances[workflow][client_name]["1"]
else:
logging.warning("Error: There is not Deployment found for " + workflow + ":" + client_name)
return ""
requests.post(url = "http://" + url + "/dataflow_append", headers={'content-type': 'application/json'}, json = jsonContent)
return "Request forwarded to Data loader"
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s --> %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
app.run(host="0.0.0.0", port=5000)<file_sep>import logging as log
from cassandra.cluster import Cluster
from flask import Flask, request, jsonify
from flask_cors import CORS
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import pandas as pd
import time
import requests
import sys
import os
app = Flask(__name__)
CORS(app)
workflowdata = None
model = None
client = None
workflowType = None
workflowId = None
ipaddressMap = None
workflowspec = None
lgr_analytics = {}
log.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
@app.route("/lgr/ipwfspec", methods=['POST'])
def readIPs():
global workflowdata, client, ipaddressMap, workflowspec, workflowType
workflowdata = request.get_json()
client = workflowdata["client_name"]
workflowType = workflowdata["workflow"]
workflowspec = workflowdata["workflow_specification"]
ipaddressMap = workflowdata["ips"]
ipaddressMap[workflowType + "#" + client] = ipaddressMap["4"]
lgr_analytics["prediction_LR"] = "lgr"
return jsonify(lgr_analytics), 200
# Model Training at Launch
def modeltrain(x_train, y_train):
global model, lgr_analytics
print("model training started *************************")
lg_clf = LogisticRegression(class_weight='balanced', solver='liblinear', C=0.1, max_iter=10000)
model = lg_clf.fit(x_train, y_train)
lgr_analytics["end_time"] = time.time()
lgr_analytics["prediction_LR"] = "lgr"
print("model training complete*********************")
# Model Training
@app.route("/lgr/train", methods=['POST'])
def trainModel():
# first read data from manager
global workflowdata, client, model, lgr_analytics, ipaddressMap, workflowType, workflowspec
lgr_analytics["start_time"] = time.time()
workflowdata = request.get_json()
client = workflowdata["client_name"]
workflowType = workflowdata["workflow"]
workflowspec = workflowdata["workflow_specification"]
newipadd = workflowdata["ips"]
ipaddressMap[workflowType+"#"+client] = newipadd["4"]
# then read training data from database
log.info("calling function to read training data from database *************************")
print("calling function to read training data from database *************************")
x_train, y_train, resultt = readTrainingData(client,workflowType)
log.info("model training started *************************")
print("model training started *************************")
# then train the model
log.info("model training started *************************")
print("model training started *************************")
lg_clf = LogisticRegression(class_weight='balanced', solver='liblinear', C=0.1, max_iter=10000)
model = lg_clf.fit(x_train, y_train)
lgr_analytics["end_time"] = time.time()
lgr_analytics["prediction_LR"] = "lgr"
log.info("model training complete*********************")
print("model training complete*********************")
if resultt == -1:
return jsonify(lgr_analytics), 400
else:
return jsonify(lgr_analytics), 200
def pandas_factory(colnames, rows):
return pd.DataFrame(rows, columns=colnames)
def readTrainingData(tablename, workflow):
global client, workflowType, lgr_analytics
# record training start time
lgr_analytics["start_time"] = time.time()
client = tablename
workflowType = workflow
clientTable = workflowType+"_"+client
# connect to Cassandra
cluster = Cluster(['10.176.67.91']) # Cluster(['0.0.0.0'], port=9042) #Cluster(['10.176.67.91'])
log.info("setting DB keyspace . . .")
session = cluster.connect('ccproj_db', wait_for_all_pools=True)
session.row_factory = pandas_factory
session.execute('USE ccproj_db')
result = 0
qry = "SELECT COUNT(*) FROM " + clientTable + ";"
try:
stat = session.prepare(qry)
x = session.execute(stat)
for row in x:
result = row.count
except:
result = -1
log.info("Table does not exists in Cassandra, shutting down Logistic regression component")
rows = session.execute('SELECT * FROM ' + clientTable)
df = rows._current_rows
if 'emp_id' in df.columns:
data = encodeEmployee(df)
x = data.drop(['uu_id', 'emp_id', 'duration'], axis=1).to_numpy()
y = data['duration'].to_numpy()
else:
print("hospital data")
data = encodeHospital(df)
x = data.drop(['uu_id', 'hadm_id', 'num_in_icu'], axis=1).to_numpy()
y = data['num_in_icu'].to_numpy()
y = y.astype('int')
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.50, random_state=42)
session.shutdown()
return x_train, y_train, result
def encodeEmployee(df, onehot=True):
if onehot:
timeencodeDict = {"8:00": 0, "8:30": 1, "9:00": 2,
"9:30": 3, "10:00": 4, "10:30": 5, "11:00": 6,
"11:30": 7, "12:00": 8, "12:30": 9, "13:00": 10,
"13:30": 11, "14:00": 12, "14:30": 13, "15:00": 14,
"15:30": 15, "16:00": 16, "16:30": 17,
"17:00": 18, "17:30": 19, "18:00": 20,
"18:30": 21, "19:00": 22, "19:30": 23, '20:00': 24}
dayencodeDict = {
'MON': 0, "TUE": 1, 'WED': 2, 'THU': 3, "FRI": 4
}
genderencodeDict = {
'male': 0, "female": 1
}
for i, row in df.iterrows():
df.at[i, 'checkin_datetime'] = timeencodeDict[row['checkin_datetime']]
df.at[i, 'day_of_week'] = dayencodeDict[row['day_of_week']]
df.at[i, 'gender'] = genderencodeDict[row['gender']]
return df
def encodeHospital(df, onehot=True):
if onehot:
timeencodeDict = {"00:00" : 0, "00:30" : 1, "01:00" : 2, "01:30" : 3,
"02:00" : 4, "02:30" : 5, "03:00" : 6, "03:30" : 7,
"04:00" : 8, "04:30" : 9, "05:00" : 10, "05:30" : 11,
"06:00" : 12, "06:30" : 13, "07:00" : 13, "07:30" : 14,
"08:00" : 15, "08:30" : 16, "09:00" : 17, "09:30" : 18,
"10:00": 19, "10:30" : 20, "11:00": 21,
"11:30" : 21, "12:00": 22, "12:30" : 23}
dayencodeDict = {
'MON': 0, "TUE": 1, 'WED': 2, 'THU': 3, "FRI": 4, "SAT": 5, "SUN": 6
}
for i, row in df.iterrows():
df.at[i, 'checkin_datetime'] = timeencodeDict[row['checkin_datetime']]
df.at[i, 'day_of_week'] = dayencodeDict[row['day_of_week']]
return df
@app.route("/lgr/predict", methods=['POST'])
def predict():
if request.method == 'POST':
log.info("***********prediction started*************")
global lgr_analytics, workflowdata
lgr_analytics["start_time"] = time.time()
workflowdata = request.get_json()
data = workflowdata['data']
if "emp_id" in data:
featureListEmployee = ['dept_type', 'gender', 'race', 'day_of_week', 'checkin_datetime']
newdata = {}
for i in featureListEmployee:
newdata[i] = data[i]
df = pd.json_normalize(newdata)
predict_data = encodeEmployee(df)
else:
featureListHospital = ['hospital_expire_flag', 'insurance', 'duration', 'amount', 'rate', 'total_items',
'value', 'dilution_value', 'abnormal_count', 'item_distinct_abnormal', 'checkin_datetime', 'day_of_week']
newdata = {}
for i in featureListHospital:
newdata[i] = data[i]
df = pd.json_normalize(newdata)
predict_data = encodeHospital(df)
log.info("start prediction*******************************************")
y_pred = model.predict(predict_data)
y_pred = list(y_pred)
timedcodeDict = {0: "8:00", 1: "8:30", 2: "9:00",
3: "9:30", 18: "10:00", 19: "10:30", 20: "11:00",
7: "11:30", 8: "12:00", 9: "12:30", 10: "13:00",
11: "13:30", 12: "14:00", 13: "14:30", 14: "15:00",
15: "15:30", 16: "16:00", 17: "16:30",
4: "17:00", 5: "17:30", 6: "18:00",
21: "18:30", 22: "19:00", 23: "19:30", 24: "20:00"}
lgr_analytics["end_time"] = time.time()
if "emp_id" in data:
lgr_analytics["prediction_LR"] = timedcodeDict[int(y_pred[0])]
else:
log.info("The hospital prediction is")
log.info(int(y_pred[0]))
lgr_analytics["prediction_LR"] = int(y_pred[0])
log.info("********** calling nextFire() in predict **********")
nextFire()
return jsonify(lgr_analytics), 200
def nextFire():
global client, workflowType
print("*******in nextFire ***********")
client = workflowdata["client_name"]
workflowType = workflowdata["workflow"]
for i, lst in enumerate(workflowspec):
for j, component in enumerate(lst):
if component == "2":
indexLR = i
if indexLR+1 < len(workflowspec):
nextComponent = workflowspec[indexLR + 1][0]
else:
nextComponent = "4"
workflowdata["analytics"].append(lgr_analytics)
log.info(workflowdata)
if nextComponent == "3": # svm
nextIPport = ipaddressMap[nextComponent]
ipp = nextIPport.split(":")
ipaddress = ipp[0]
port = ipp[1]
log.info("making request to SVM Component")
log.info(ipp)
r1 = requests.post(url="http://" + ipaddress + ":" + port + "/svm/predict",
headers={'content-type': 'application/json'}, json=workflowdata, timeout = 60)
elif nextComponent == "4":
log.info(nextComponent)
nextIPport = ipaddressMap[workflowType+"#"+client]
ipp = nextIPport.split(":")
ipaddress = ipp[0]
port = ipp[1]
log.info("making request to Analytics")
log.info(ipp)
r1 = requests.post(url="http://" + ipaddress + ":" + port + "/put_result",
headers={'content-type': 'application/json'}, json=workflowdata, timeout = 60)
else:
return jsonify(success=False)
if __name__ == '__main__':
# Read env variables of workflow type and client_name
workflowtype = os.environ['workflow']
table = ""
if os.environ['client_name'] is not None:
table = os.environ['client_name']
else:
log.error("Include variable client_name in docker swarm command")
sys.exit(1)
log.info("read data from Database")
rs = 0
x_data, y_data, rs = readTrainingData(table,workflowtype)
if rs == -1:
sys.exit(1)
log.info("start training model on container launch")
modeltrain(x_data, y_data)
log.info("**** start listening ****")
app.run(debug=True, host="0.0.0.0", port=50)
| 6ba594795a70f18a2c774a7b52f578329c404853 | [
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 19 | Python | gaderut/CloudComputing-docker | cd03cde512d59662fb23c662b2285f706d574968 | a4adde94293cacc800ed467b85ac0e8089548482 |
refs/heads/master | <file_sep>$(document).ready(function() {
$(".container").center();
$("#submitSignIn").click(function() {
userdata = JSON.stringify({
username: $("#username").val().toLowerCase(),
password: <PASSWORD>").val()
});
$.ajax({
type: "POST",
url: "/signin",
data: userdata,
success: function() {
$("#signInText").text("signed in");
$("#signInText").css("display", "block");
$(".container").center();
},
statusCode: {
400: function() {
$("#signInText").text("bad request");
$("#signInText").css("display", "block");
$(".container").center();
},
401: function() {
$("#signInText").text("invalid password");
$("#signInText").css("display", "block");
$(".container").center();
},
404: function() {
$("#signInText").text("user not found");
$("#signInText").css("display", "block");
$(".container").center();
}
}
})
});
$("#submitSignUp").click(function() {
userdata = JSON.stringify({
username: $("#newUsername").val().toLowerCase(),
password: <PASSWORD>").val()
});
$.ajax({
type: "POST",
url: "/signup",
data: userdata,
success: function() {
$("#signUpText").text("account created");
$("#signUpText").css("display", "block");
$(".container").center();
},
statusCode: {
400: function() {
$("#signUpText").text("bad request");
$("#signUpText").css("display", "block");
$(".container").center();
},
409: function() {
$("#signUpText").text("username taken");
$("#signUpText").css("display", "block");
$(".container").center();
}
}
})
});
})
$(window).on('resize', function(){
$(".container").center();
});
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}<file_sep># photos
Web app for uploading and organizing photos and creating slideshows.
<file_sep>package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"golang.org/x/crypto/bcrypt"
)
// A User is a user.
type User struct {
Username string
Password string
}
var collection *mongo.Collection
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/html/index.html")
})
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.HandleFunc("/signin", Signin)
http.HandleFunc("/signup", Signup)
/* Connecting to MongoDB */
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection = client.Database("test").Collection("users")
/*
max := User{"max", "bruh"}
insertResult, err := collection.InsertOne(context.TODO(), max)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult.InsertedID)
filter := bson.D{primitive.E{Key: "username", Value: "max"}}
var result User
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)
*/
log.Fatal(http.ListenAndServe(":80", nil))
}
// Signin handles signins.
func Signin(w http.ResponseWriter, r *http.Request) {
// Parse and decode the request body into a new `User` instance
user, err := parseToUser(w, r)
if err != nil {
// If there is something wrong with the request body, return a 400 status
w.WriteHeader(http.StatusBadRequest)
return
}
// Check if a user with the given username exists
filter := bson.D{primitive.E{Key: "username", Value: user.Username}}
var result User
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
// If the user doesn't exist, return a 404 status
w.WriteHeader(http.StatusNotFound)
return
}
// Compare the stored hashed password and the given password
if err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(user.Password)); err != nil {
// If the password is wrong, return a 401 status
w.WriteHeader(http.StatusUnauthorized)
return
}
}
// Signup handles signups.
func Signup(w http.ResponseWriter, r *http.Request) {
// Parse and decode the request body into a new `User` instance
user, err := parseToUser(w, r)
if err != nil {
// If there is something wrong with the request body, return a 400 status
w.WriteHeader(http.StatusBadRequest)
return
}
// Salt and hash the password using the bcrypt algorithm
// The second argument is the cost of hashing, which we arbitrarily set as 8 (this value can be more or less, depending on the computing power you wish to utilize)
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), 8)
// Checking that the username is unique
filter := bson.D{primitive.E{Key: "username", Value: user.Username}}
var result User
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err == nil {
w.WriteHeader(http.StatusConflict)
return
}
// Writing to the database
insertResult, err := collection.InsertOne(context.TODO(), &User{user.Username, string(hashedPassword)})
if err != nil {
log.Fatal(err)
}
fmt.Println("New user registered: ", insertResult.InsertedID)
}
func parseToUser(w http.ResponseWriter, r *http.Request) (*User, error) {
user := &User{}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return user, err
}
err = json.Unmarshal(b, &user)
if err != nil {
return user, err
}
return user, nil
}
| 547926facb8378adac5c00f23c0ffae89746a60d | [
"JavaScript",
"Go",
"Markdown"
] | 3 | JavaScript | max-jardetzky/photos | 323d2ee2ce70590eb836047c462e8a3bcab09acd | 7bb70b98b4eeefd7ab1dc12b6053ca08e04f1bed |
refs/heads/master | <repo_name>longfoo/react_app_01<file_sep>/src/hooks/useFetch.js
import { useEffect, useState } from "react";
// 사용자정의 생성된 훅 useFetch
// useEffect와 useState를 사용한다.
// 하나의 기능을 여러 컴포넌트에서 동일하게 사용할 경우, 코드의 사용성을 높일 수 있다.
export default function useFetch(url) {
const [data, setData] = useState([]);
useEffect(() => {
fetch(url)
.then((res) => {
return res.json();
})
.then((data) => {
setData(data);
});
}, [url]);
return data;
}
<file_sep>/README.md
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## 코딩 참조
이 프로그램은 유튜브 코딩앙마의 <React js 강좌> 동영상을 따라 만들었습니다.
https://www.youtube.com/playlist?list=PLZKTXPmaJk8J_fHAzPLH8CJ_HO_M33e7-
| 4a4554127b0d96c8facecc981ea608d68ad69f89 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | longfoo/react_app_01 | ae580ce04b04ec3ce768ceca72fccc00213f48b1 | 05d2997c7a8e6a6477bacff0ab14c0e3a7296b6b |
refs/heads/main | <file_sep>from os import environ
from process_credit_sales_file import process_credit_sales_file
from process_debit_sales_file import process_debit_sales_file
from process_financial_file import process_financial_file
from process_outstanding_balance_file import process_outstanding_balance_file
from s3Service import get_object, put_object, move_object
BUCKET_GLOBAL = environ['BUCKET_GLOBAL']
BUCKET_GLOBAL_BACKUP = environ['BUCKET_GLOBAL_BACKUP']
BUCKET_PENDING_PROCESS = environ['BUCKET_PENDING_PROCESS']
def process(bucket, key):
# read all data from this file
lines = get_data_file_from_payload(bucket=bucket, key=key)
# validate first line after recover file type
file_type, line = validate_first_line(lines)
if file_type in ['EEVC', 'NNVC', 'NEVC']:
process_credit_sales_file(header=line, lines=lines[1:], prefix='EEVC')
elif file_type in ['EEVD', 'NNVD', 'NEVD']:
process_debit_sales_file(header=line, lines=lines[1:], prefix='EEVD')
elif file_type in ['EEFI', 'NNFI', 'NEFI']:
process_financial_file(header=line, lines=lines[1:], prefix='EEFI')
elif file_type in ['EESA', 'NNSA', 'NESA']:
process_outstanding_balance_file(header=line, lines=lines[1:], prefix='EESA')
move_object(bucket_origin=BUCKET_GLOBAL, key_origin=key,
bucket_destination=BUCKET_GLOBAL_BACKUP, key_destination=key)
def get_data_file_from_payload(bucket, key):
file = get_object(bucket, key)
if file is None:
raise Exception('None file to be processed')
file = file['Body']
file = file.read().decode('utf8')
return file.split('\n')
def validate_first_line(lines):
if lines[0][19:20] == '@': # entao eh cabecalho com tipo de arquivo
file_type = lines[0][48:52]
if file_type not in ['EEVC', 'NNVC', 'NEVC',
'EEVD', 'NNVD', 'NEVD',
'EEFI', 'NNFI', 'NEFI',
'EESA', 'NNSA', 'NESA']:
raise Exception('File type not treated in this process')
return file_type, lines[0]
<file_sep>from os import environ, remove
import boto3
# environ['ACCESS_KEY'] = '1234567890'
# environ['SECRET_KEY'] = '1234567890'
# environ['ENDPOINT_URL'] = 'http://localhost:4566'
# environ['REGION'] = 'us-east-1'
# environ['BUCKET_GLOBAL'] = 'fl2-statement-global'
# environ['BUCKET_GLOBAL_BACKUP'] = 'fl2-statement-global-bkp'
# environ['BUCKET_TRANSFER'] = 'fl2-statement-transfer'
# environ['BUCKET_PENDING_PROCESS'] = 'fl2-statement-pending-process'
ACCESS_KEY = environ['ACCESS_KEY']
SECRET_KEY = environ['SECRET_KEY']
ENDPOINT_URL = environ['ENDPOINT_URL']
REGION = environ['REGION']
BUCKET_GLOBAL = environ['BUCKET_GLOBAL']
BUCKET_GLOBAL_BACKUP = environ['BUCKET_GLOBAL_BACKUP']
BUCKET_TRANSFER = environ['BUCKET_TRANSFER']
BUCKET_PENDING_PROCESS = environ['BUCKET_PENDING_PROCESS']
def __get_client():
return boto3.client(
's3',
region_name=REGION,
endpoint_url=ENDPOINT_URL,
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY)
def get_object(bucket_name, key):
client = __get_client()
return client.get_object(Bucket=bucket_name,
Key=key)
def move_object(bucket_origin, key_origin, bucket_destination, key_destination):
client = __get_client()
client.copy_object(Bucket=bucket_destination,
Key=key_destination,
CopySource={
'Bucket': bucket_origin,
'Key': key_origin
})
delete_object(bucket_name=bucket_origin, key=key_origin)
def delete_object(bucket_name, key):
client = __get_client()
return client.delete_object(Bucket=bucket_name,
Key=key)
def put_object(bucket_name, key, file):
client = __get_client()
return client.put_object(Bucket=bucket_name,
Key=key,
Body=file)
def list_all_buckets():
client = __get_client()
response = client.list_buckets()
# print(response)
return response['Buckets']
if __name__ == '__main__':
pass
# file = open('EEVC.TXT', mode='rb')
# put_object(BUCKET_GLOBAL, 'EEVC.TXT', file) # OK
#
# file = get_object(BUCKET_GLOBAL, 'EEVC.TXT')
# if file is not None:
# file = file['Body']
# file = file.read().decode('ascii')
# else:
# exit(1)
#
# lines = file.split('\n')
# file_type = None
# current_establishment = None
# building_file = None
#
# for line in lines:
# if line[19:20] == '@': # entao eh cabecalho com tipo de arquivo
# file_type = line[48:52]
# continue
#
# if file_type not in ['EEVC', 'NNVC', 'NEVC', 'EEVD', 'NNVD', 'NEVD', 'EEFI',
# 'NNFI', 'NEFI', 'EESA', 'NNSA', 'NESA']:
# raise Exception('File type not treated in this process')
#
# if file_type is not None:
#
# # if register_type in ['EEVC', 'NNVC', 'NEVC']:
#
# register_type = line[19:22]
# if register_type == '002': # entao eh cabecalho da matriz
# current_establishment = line[75:82]
# file_name = f'{current_establishment}.TXT'
# building_file = open(file_name, mode='wb')
# building_file.write(f'{line[19:]}\n'.encode())
# continue
# elif not register_type == '028': # se for registros do bloco, continuar gravando no arquivo
# building_file.write(f'{line[19:]}\n'.encode())
# continue
# elif register_type == '028': # eh fim de bloco, salvar arquivo, enviar para bucket e ir para proxima linha
# building_file.write(f'{line[19:]}\n'.encode())
# building_file.close()
# send_file = open(file_name, 'rb')
# put_object(BUCKET_PENDING_PROCESS, file_name, send_file) # OK
# send_file.close()
# remove(file_name)
# file_type = None
# current_establishment = None
# building_file = None
# continue
#
# delete_object(BUCKET_GLOBAL, 'EEVC.TXT')
# put_object(BUCKET_GLOBAL, 'EEVC.TXT', file) # OK
# list_all_buckets() # OK
<file_sep>#!/usr/bin/env bash
export ENDPOINT_URL='http://localhost:4566'
export SQS_QUEUE_NAME='FL2-StatementFiles'
ENDPOINT_URL=http://localhost:4566
# brew install jq
SQS_URL=$(aws sqs --endpoint $ENDPOINT_URL get-queue-url --queue-name $SQS_QUEUE_NAME | jq -r '.QueueUrl')
echo "SQS_URL: >> '${SQS_URL}' <<"
if [ -z "${SQS_URL}" ]
then
echo 'vazio'
else
# DELETE SQS
echo 'Deleting SQS'
aws sqs --endpoint $ENDPOINT_URL delete-queue --queue-url "${SQS_URL}"
fi
# CREATE SQS
echo 'Creating SQS'
aws sqs --endpoint $ENDPOINT_URL create-queue --queue-name $SQS_QUEUE_NAME
<file_sep>#!/usr/bin/env bash
sh ./setup_s3.sh
sh ./setup_sqs.sh
DEFAULT_REGION='us-east-1'
LAMBDA_STATEMENT_SPLIT_BLOCK='lambda-statement-split-block'
LAMBDA_PROCESSING_STATEMENT='lambda-processing-statement'
export ACCESS_KEY='1234567890'
export SECRET_KEY='1234567890'
export ENDPOINT_URL='http://localhost:4566'
export REGION=$DEFAULT_REGION
export BUCKET_GLOBAL='fl2-statement-global'
export BUCKET_GLOBAL_BACKUP='fl2-statement-global-bkp'
export BUCKET_TRANSFER='fl2-statement-transfer'
export BUCKET_PENDING_PROCESS='fl2-statement-pending-process'
ENDPOINT_URL=http://localhost:4566
echo $ENDPOINT_URL
echo "CHECK IF LAMBDA EXISTS "
LAMBDA_EXISTS=$(aws lambda --endpoint $ENDPOINT_URL function-exists --function-name ${LAMBDA_STATEMENT_SPLIT_BLOCK})
echo "LAMBDA EXISTS >> '${LAMBDA_EXISTS}' << "
if [ -z "${LAMBDA_EXISTS}" ]
then
echo "Lambda ${LAMBDA_STATEMENT_SPLIT_BLOCK} nao existente"
else
# DELETE LAMBDA
echo 'Deleting Lambda'
aws lambda --endpoint $ENDPOINT_URL delete-function --function-name ${LAMBDA_STATEMENT_SPLIT_BLOCK}
fi
#
# PWD=$(pwd)
# FILE='lambda.zip'
# if test -f "$FILE"; then
# rm lambda.zip
# fi
# zip -r lambda.zip "${PWD}"/*.py
#
#
# # CREATE LAMBDA
# echo 'Creating Lambda'
# aws lambda --endpoint $ENDPOINT_URL create-function \
# --region ${DEFAULT_REGION} \
# --function-name ${LAMBDA_STATEMENT_SPLIT_BLOCK} \
# --runtime python3.7 \
# --role irrelevant \
# --handler main.execute \
# --zip-file fileb://lambda.zip
#fi
#
#python3 s3Service.py<file_sep>#!/usr/bin/env bash
DEFAULT_REGION='us-east-1'
LAMBDA_STATEMENT_SPLIT_BLOCK=lambda-statement-split-block
LAMBDA_PROCESSING_STATEMENT=lambda-processing-statement
export ACCESS_KEY='1234567890'
export SECRET_KEY='1234567890'
export ENDPOINT_URL='http://localhost:4566'
export REGION=$DEFAULT_REGION
export BUCKET_GLOBAL='fl2-statement-global'
export BUCKET_GLOBAL_BACKUP='fl2-statement-global-bkp'
export BUCKET_TRANSFER='fl2-statement-transfer'
export BUCKET_PENDING_PROCESS='fl2-statement-pending-process'
ENDPOINT_URL=http://localhost:4566
echo $ENDPOINT_URL
#function does_lambda_exist() {
# aws lambda get-function --function-name $1 > /dev/null 2>&1
# if [ 0 -eq $? ]; then
#
# echo "Lambda '$1' exists"
# # DELETE LAMBDA
# echo "Deleting Lambda '$1'"
aws lambda --endpoint $ENDPOINT_URL delete-function --function-name $LAMBDA_STATEMENT_SPLIT_BLOCK
#aws lambda --endpoint $ENDPOINT_URL delete-function --function-name $LAMBDA_PROCESSING_STATEMENT
# else
# echo "Lambda '$1' does not exist"
# fi
#}
#does_lambda_exist ${LAMBDA_STATEMENT_SPLIT_BLOCK}
#
#does_lambda_exist ${LAMBDA_PROCESSING_STATEMENT}
aws iam --endpoint $ENDPOINT_URL delete-role --role-name lambda-role
LAMBDA_ROLE=$(aws iam --endpoint $ENDPOINT_URL create-role --role-name lambda-role \
--assume-role-policy-document file://role.json | jq -r ".Role.Arn" )
echo "$LAMBDA_ROLE"
PWD=$(pwd)
FILE="${PWD}/lambda.zip"
if test -f "$FILE"; then
echo 'Deleting zip file'
rm lambda.zip
fi
echo 'Ziping file'
zip -r lambda.zip "${PWD}"/*.py
# CREATE LAMBDA
echo "Creating Lambda '${LAMBDA_STATEMENT_SPLIT_BLOCK}'"
LAMBDA_ARN=$(aws lambda --endpoint $ENDPOINT_URL create-function \
--function-name $LAMBDA_STATEMENT_SPLIT_BLOCK \
--role lambda-role \
--runtime python3.7 \
--zip-file fileb://lambda.zip \
--environment "Variables={ACCESS_KEY=${ACCESS_KEY},
SECRET_KEY=${SECRET_KEY},
ENDPOINT_URL=${ENDPOINT_URL},
REGION=${REGION},
BUCKET_GLOBAL=${BUCKET_GLOBAL},
BUCKET_GLOBAL_BACKUP=${BUCKET_GLOBAL_BACKUP},
BUCKET_TRANSFER=${BUCKET_TRANSFER},
BUCKET_PENDING_PROCESS=${BUCKET_PENDING_PROCESS}}" \
| jq -r ".FunctionArn")
echo $LAMBDA_ARN
aws s3api --endpoint $ENDPOINT_URL put-bucket-notification-configuration \
--bucket ${BUCKET_GLOBAL} \
--notification-configuration file://s3-lambda-notification.json
<file_sep>from os import environ
from process import process
from s3Service import put_object
environ['ACCESS_KEY'] = '1234567890'
environ['SECRET_KEY'] = '1234567890'
environ['ENDPOINT_URL'] = 'http://localhost:4566'
environ['REGION'] = 'us-east-1'
environ['BUCKET_GLOBAL'] = 'fl2-statement-global'
environ['BUCKET_GLOBAL_BACKUP'] = 'fl2-statement-global-bkp'
environ['BUCKET_TRANSFER'] = 'fl2-statement-transfer'
environ['BUCKET_PENDING_PROCESS'] = 'fl2-statement-pending-process'
BUCKET_GLOBAL = environ['BUCKET_GLOBAL']
# def test():
#
# file = open('EEVC.TXT', mode='rb')
# put_object(BUCKET_GLOBAL, 'EEVC.TXT', file) # OK
#
# file = open('EEVD.TXT', mode='rb')
# put_object(BUCKET_GLOBAL, 'EEVD.TXT', file) # OK
#
# file = open('EEFI.TXT', mode='rb')
# put_object(BUCKET_GLOBAL, 'EEFI.TXT', file) # OK
#
# file = open('EESA.TXT', mode='rb')
# put_object(BUCKET_GLOBAL, 'EESA.TXT', file) # OK
def execute(event, context):
print(event)
pass
# payload = {'Bucket': BUCKET_GLOBAL, 'Key': 'EEVC.TXT'}
# process(bucket=payload['Bucket'], key=payload['Key'])
#
# payload = {'Bucket': BUCKET_GLOBAL, 'Key': 'EEVD.TXT'}
# process(bucket=payload['Bucket'], key=payload['Key'])
#
# payload = {'Bucket': BUCKET_GLOBAL, 'Key': 'EEFI.TXT'}
# process(bucket=payload['Bucket'], key=payload['Key'])
#
# payload = {'Bucket': BUCKET_GLOBAL, 'Key': 'EESA.TXT'}
# process(bucket=payload['Bucket'], key=payload['Key'])
# Press the green button in the gutter to run the script.
# if __name__ == '__main__':
# test()
# execute(None, None)
<file_sep>#!/usr/bin/env bash
export ENDPOINT_URL='http://localhost:4566'
export BUCKET_GLOBAL='fl2-statement-global'
export BUCKET_GLOBAL_BACKUP='fl2-statement-global-bkp'
export BUCKET_TRANSFER='fl2-statement-transfer'
export BUCKET_PENDING_PROCESS='fl2-statement-pending-process'
ENDPOINT_URL=http://localhost:4566
# DELETE BUCKET
# Delete bucket global
echo 'Delete bucket global'
aws s3 --endpoint $ENDPOINT_URL rb s3://$BUCKET_GLOBAL --force
# Delete bucket backup of global
echo 'Delete bucket backup of global'
aws s3 --endpoint $ENDPOINT_URL rb s3://$BUCKET_GLOBAL_BACKUP --force
# Delete bucket that will store data from blocks
echo 'Delete bucket that will store data from blocks'
aws s3 --endpoint $ENDPOINT_URL rb s3://$BUCKET_PENDING_PROCESS --force
# Delete bucket with files that will be transfered to the conciliator
echo 'Delete bucket with files that will be transfered to the conciliator'
aws s3 --endpoint $ENDPOINT_URL rb s3://$BUCKET_TRANSFER --force
# CREATE BUCKET
# Create bucket global
echo 'Create bucket global'
aws s3 --endpoint $ENDPOINT_URL mb s3://$BUCKET_GLOBAL
# Create bucket backup of global
echo 'Create bucket backup of global'
aws s3 --endpoint $ENDPOINT_URL mb s3://$BUCKET_GLOBAL_BACKUP
# Create bucket that will store data from blocks
aws s3 --endpoint $ENDPOINT_URL mb s3://$BUCKET_PENDING_PROCESS
# Create bucket with files that will be transfered to the conciliator
aws s3 --endpoint $ENDPOINT_URL mb s3://$BUCKET_TRANSFER
| 2ffeb793385563e6f5f2759aa15f7300b99e27b4 | [
"Python",
"Shell"
] | 7 | Python | BrunoIstvan/localstack-aws-lambda-s3-sqs | 443f7bce362d01ca98dff41ea99f661757031560 | e2602d203158eb4dec6bf842dfbb3168a6ce78d0 |
refs/heads/master | <file_sep>(function(){
var President = function(name, votes) {
this.name = name;
this.votes = votes;
}
var omalley = new President("OMalley", 8);
var cruz = new President("Cruz", 1);
var webb = new President("Webb", 2);
var rubio = new President("Rubio", 2);
var clinton = new President("Clinton", 5);
var paul = new President("Paul", 2);
function presChartVotes(pres1votes, pres2votes, pres3votes, pres4votes, pres5votes, pres6votes) {
var data = {
labels: ["OMalley", "Cruz", "Webb", "Rubio", "Clinton", "Paul"],
datasets: [
{
label: "Candidates",
fillColor: "rgba(22,57,255,0.5)",
strokeColor: "rgba(22,57,255,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [pres1votes, pres2votes, pres3votes, pres4votes, pres5votes, pres6votes]
}
]
};
var options = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 1,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
};
var ctx = document.getElementById("presChart").getContext("2d");
var myPresChart = new Chart(ctx).Bar(data,options);
}
var img1 = $('<img>').attr({
id: 'imgOne',
src: "../Images/OMalley.jpg"
});
var img2 = $('<img>').attr({
id: 'imgTwo',
src: "../Images/Cruz.jpg"
});
var img3 = $('<img>').attr({
id: 'imgThree',
src: "../Images/Webb.jpg"
});
var img4 = $('<img>').attr({
id: 'imgFour',
src: "../Images/Rubio.jpg"
});
var img5 = $('<img>').attr({
id: 'imgFive',
src: "../Images/Clinton.jpg"
});
var img6 = $('<img>').attr({
id: 'imgSix',
src: "../Images/Paul.jpg"
});
var $presDiv = $('#presDiv').empty();
$presDiv.append(img1, img2, img3, img4, img5, img6);
$('#imgOne').on('click', function() {
$(this).css("border", "5px solid yellow");
omalley.votes++;
presChartVotes(omalley.votes, cruz.votes, webb.votes, rubio.votes, clinton.votes, paul.votes);
});
$('#imgTwo').on("click", function() {
$(this).css("border", "5px solid yellow");
cruz.votes++;
presChartVotes(omalley.votes, cruz.votes, webb.votes, rubio.votes, clinton.votes, paul.votes);
});
$('#imgThree').on("click", function() {
$(this).css("border", "5px solid yellow");
webb.votes++;
presChartVotes(omalley.votes, cruz.votes, webb.votes, rubio.votes, clinton.votes, paul.votes);
});
$('#imgFour').on("click", function() {
$(this).css("border", "5px solid yellow");
rubio.votes++;
presChartVotes(omalley.votes, cruz.votes, webb.votes, rubio.votes, clinton.votes, paul.votes);
});
$('#imgFive').on("click", function() {
$(this).css("border", "5px solid yellow");
clinton.votes++;
presChartVotes(omalley.votes, cruz.votes, webb.votes, rubio.votes, clinton.votes, paul.votes);
});
$('#imgSix').on("click", function() {
$(this).css("border", "5px solid yellow");
paul.votes++;
presChartVotes(omalley.votes, cruz.votes, webb.votes, rubio.votes, clinton.votes, paul.votes);
});
}());
<file_sep>$('#flag').animate({
marginLeft: '+=' + $('#background').width()/2.4
}, 10000, function() {
});
$('#flag').click(function() {
window.location = "candidates.html";
})
$('#flag2').click(function() {
window.location = 'vote.html';
})
$('#flag3').click(function() {
window.location = 'wheel.html';
})
$(function() {
$('#omalley').dialog({
autoOpen:false,
width:500,
height:500,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}});
$(".flex-item-1").click(function(e) {
e.preventDefault();
$('#omalley').dialog('open');
});
});
$(function() {
$('#cruz').dialog({
autoOpen:false,
width:500,
height:500,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}});
$(".flex-item-2").click(function(e) {
e.preventDefault();
$('#cruz').dialog('open');
});
});
$(function() {
$('#webb').dialog({
autoOpen:false,
width:500,
height:500,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}});
$(".flex-item-3").click(function(e) {
e.preventDefault();
$('#webb').dialog('open');
});
});
$(function() {
$('#webb').dialog({
autoOpen:false,
width:500,
height:500,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}});
$(".flex-item-3").click(function(e) {
e.preventDefault();
$('#webb').dialog('open');
});
});
$(function() {
$('#rubio').dialog({
autoOpen:false,
width:500,
height:500,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}});
$(".flex-item-4").click(function(e) {
e.preventDefault();
$('#rubio').dialog('open');
});
});
$(function() {
$('#clinton').dialog({
autoOpen:false,
width:500,
height:500,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}});
$(".flex-item-5").click(function(e) {
e.preventDefault();
$('#clinton').dialog('open');
});
});
$(function() {
$('#paul').dialog({
autoOpen:false,
width:500,
height:500,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}});
$(".flex-item-6").click(function(e) {
e.preventDefault();
$('#paul').dialog('open');
});
});
<file_sep>This is for the President Tracker made by: <NAME>, <NAME>, and <NAME>.
We would like to credit the following people/websites: Wikipedia, Chart.js, <NAME>, Daft Punk, Stack Overflow, the United States Marine Core Band, Codepen.io, CSStricks.com, our Code Fellows instructors, and our fellow classmates. God bless America.
| 1f29afaefc9bb41867ea2e8732d450a5a02306b6 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | kristenbriggs/president_tracker | fdaa1e751a5c99647ebff4df8cdc7933846f5305 | 5d3d86099ebc112a9b35b12f6d812289051c9abe |
refs/heads/main | <repo_name>JRicardo11/Forecasting_Time_Series<file_sep>/README.md
# Forecasting_Time_Series
Forecasting quarterly earnings per share of Coca-Cola Company from the first quarter of 1983 to the third quarter of 2009. Forecasting time series in R (R Studio)
<file_sep>/Group C - Homework 2.R
# Set the folder (path) that contains this R file as the working directory
dir <- dirname(rstudioapi::getActiveDocumentContext()$path);
setwd(dir);
library(fBasics);
library(forecast);
## Adjust plotting area
par(mfrow = c(3, 1));
#### SERIES 1 ####
data <- read.csv("coca_cola_earnings.csv", header=TRUE, sep = ";", dec = ",");
x <- data[,2];
length(x);
x <- data[1:83,2];
val <- data[84:107,2];
## 1) Visually check the data for mean and variance stationarity
ts.plot(x); ## The data is not stationary in variance, neither mean
## 2) Transform data to logarithmic scale to make variance stationary
y <- log(x);
ts.plot(y);
## 3) Tests to check how many differences do we need to take
ndiffs(y, alpha = 0.05, test = "adf"); ## First difference = 1
nsdiffs(y, m = 4, test = c("ocsb")); ## Seasonal difference = 1
z <- diff(y);
## 4) Visually check new data for stationarity
ts.plot(z); ## Stationary in both mean and variance
## 5) Check lags out of bounds on ACF and PACF
acf(z, lag.max = 20); ## Clearly seasonal - 2, 4, 6, 8, etc. out of bounds
pacf(z, lag.max = 20); ## 2, 3, 4, 5, 8, 9 out of bounds
## 6) Fit model and check residuals
#### MODEL 1 - a, b, c ####
fit_a <- arima(y, order = c(0, 1, 1), seasonal = list(order = c(0, 1, 1), period = 4)); ## Option 1
fit_a; ## MA1 and SMA1 are significant - 0 is out of range
ts.plot(fit_a$residuals);
## 7) Check if residuals have lags out of bounds
acf(fit_a$residuals, lag.max = 20); ## 1 lag out of bounds #5
pacf(fit_a$residuals, lag.max = 20); ## 1 lag out of bounds #5
Box.test(fit_a$residuals, lag = 5); ## P-value on lag 5 is higher than 0.05, we can consider the lag out of bounds as WN and proceed with this model
## 8) Shapiro test to check if the residuals are normally distributed, confirming White Noise
Box.test(fit_a$residuals); ## P-value is higher than 0.05, meaning residuals are WN
shapiro.test(fit_a$residuals) ## P-value is not higher than 0.05, meaning the residuals are not GWN - we need to check real Z values for interval predictions
## 9) Predictions
a.pred <- predict(fit_a, n.ahead = 24);
a.pred_pred <- exp(a.pred$pred); ## Transforming data back from logarithmic scale
b.pred <- exp(a.pred$pred)
ts.plot(c(x, b.pred));
lines(b.pred, col = "green");
#### MODEL 2 - j, k, l ####
fit_j <- arima(y, order = c(2, 1, 2), seasonal = list(order = c(0, 1, 2), period = 4)); ## Option 2
fit_j; ## AR2, MA2 and SMA2 are significant - 0 is out of range
ts.plot(fit_j$residuals);
## 7) Check if residuals have lags out of bounds
acf(fit_j$residuals, lag.max = 20); ## No lags out of bounds
pacf(fit_j$residuals, lag.max = 20); ## No lags out of bounds
## 8) Shapiro test to check if the residuals are normally distributed, confirming White Noise
Box.test(fit_j$residuals); ## P-value is higher than 0.05, meaning residuals are WN
shapiro.test(fit_j$residuals) ## P-value is not higher than 0.05, meaning the residuals are not GWN - we need to check real Z values for interval predictions
## 9) Predictions
j.pred <- predict(fit_j, n.ahead = 24);
j.pred_pred <- exp(j.pred$pred); ## Transforming data back from logarithmic scale
k.pred <- exp(j.pred$pred)
ts.plot(c(x, k.pred));
lines(k.pred, col = "green");
## 10) Model evaluation & selection
mape_option1 <- round(mean(abs((a.pred_pred - val)/val))*100, 4);
mape_option2 <- round(mean(abs((j.pred_pred - val)/val))*100, 4);
mape_option1;
mape_option2;
msfe_option1 <- round(mean((a.pred_pred - val)^2), 4);
msfe_option2 <- round(mean((j.pred_pred - val)^2), 4);
msfe_option1;
msfe_option2;
models <- c("Model", "(0,1,1)(0,1,1)[4]", "(2,1,2)(0,1,2)[4]")
model_selection <- data.frame();
header <- c("Model", "MAPE", "MSFE");
model_selection <- as.data.frame(models);
model_selection <- cbind(model_selection, c("MAPE", mape_option1, mape_option2));
model_selection <- cbind(model_selection, c("MSFE", msfe_option1, msfe_option2));
colnames(model_selection) <- header;
model_selection <- model_selection[2:3,];
View(model_selection)
## Based on these results, we would pick Model 1 - SARIMA (0,1,1)(0,1,1)[4]
| d0a708d99d5978924d8a3e04570528465e224502 | [
"Markdown",
"R"
] | 2 | Markdown | JRicardo11/Forecasting_Time_Series | d461a06bb803781e323c57e1a14aacb6c9ece306 | 1a9f3028cb2d6f7467ed03efd7d7ab90e74484e6 |
refs/heads/master | <repo_name>sammartfrank/chatreact<file_sep>/src/reducers/userIdReducer.js
import {
SIGN_OK
} from '../constants/actionTypes.js'
const initialState = ''
const userIdReducer = (state=initialState,action) => {
switch (action.type) {
case SIGN_OK:
return action.id
default:
return state
}
}
export default userIdReducer<file_sep>/src/components/SignUp/SignUp.js
import React from 'react'
import SignUpForm from './SignUpForm'
import { Redirect } from 'react-router-dom'
const logcss = {
minHeight: "100vh",
justifyContent: 'center',
alignItems: 'center',
display: 'flex',
alignText: 'center',
backgroundColor: '#2F2342'
}
const jumsty = {
minWidth : "75%",
background: 'linear-gradient(135deg,#352D4D 0%,#921099 48%,#7e4ae8 100%)',
}
const SignUp = ({ token }) => {
if ( !token ) {
return <div className="container-fluid" style={logcss} >
<div className='jumbotron jumbotron-fluid' style={jumsty} >
<div className='container'>
<h1 className="display-4" style={{color:'orange',fontFamily:'Helvetica'}}>Welcome</h1>
<SignUpForm />
</div>
</div>
</div>
}
else {
return (
<Redirect to='/login' />
)
}
}
export default SignUp
<file_sep>/src/components/Rutas/Routes.js
import React from 'react'
import { Switch, Route, withRouter } from 'react-router-dom'
import LoginContainer from '../../containers/LoginContainer'
import ChatRoomContainer from '../../containers/ChatRoomContainer'
import LobbyContainer from '../../containers/LobbyContainer'
import SignUpContainer from '../../containers/SignUpContainer'
import NotFound from '../NotFound'
import PrivateRoute from './PrivateRoute'
const Routes = ({isLogged}) => (
<Switch>
<Route exact path="/" component={ SignUpContainer } />
<Route path="/login" component={ LoginContainer } />
<Route path="/lobby" component={ LobbyContainer } />
<PrivateRoute path="/chatroom" isLogged={ isLogged } component={ ChatRoomContainer }/>
<Route component={ NotFound }/>
</Switch>
)
export default withRouter(Routes)
<file_sep>/src/services/ChatApi.js
import axios from 'axios'
class ChatApi {
constructor(props){
this.axios = axios.create({
baseURL: '/api',
})
}
getMessages = ( id, token) => (
this.axios.get(`/mensajes/${id}`, {
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer" + token
}
}).then( response => response.data)
);
//login
login = ( values ) => console.log( 'values', values ) || (
this.axios.post( '/auth',
{
"username": values.username,
"password": <PASSWORD>
}
)
.then( response => response.data )
.catch( () => (error) => {
console.error(error)
})
);
// Sign up
register = ( values ) => console.log( 'values', values ) || (
this.axios.post('/users',
{
"username":values.username,
"password":<PASSWORD>,
"email":values.email
})
.then( response => response.data )
.catch( () => ( error ) => {
console.log( error )
})
);
checkUser = ( id, token ) => console.log( 'user id', id ) || (
this.axios.head(`/users/${id}`, {
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer" + token
}
}).then( response => response.data )
);
getMember = ( id, token ) => (
this.axios.get(`/users/${id}`, {
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer" + token
}
}).then( response => response.data)
);
addMessage = ( values ) => console.log( 'values', values) || (
this.axios.post( '/message')
)
}
export default ChatApi
<file_sep>/src/components/Rutas/PrivateRoute.js
import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import ChatRoomContainer from '../../containers/ChatRoomContainer'
const PrivateRoute = ( { path, component, isLogged } ) => {
return(
<div>
{ isLogged ? <Route path={ path } component={ChatRoomContainer} /> : <Redirect to="/" /> }
</div>
)
}
export default PrivateRoute;<file_sep>/src/components/SignUp/SignUpForm.js
import React from 'react'
import { Redirect } from 'react-router-dom'
import { register } from '../../actions'
import { reduxForm, Field, SubmissionError } from 'redux-form'
import validate from './validate'
import { Link } from 'react-router-dom'
const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<input { ...input } placeholder={ label } type={ type }/>
<div>
{ touched && error && <span style={{ color:'goldenrod' }}>{ error }</span>}
</div>
</div>
)
let SignUpForm = ({ handleSubmit, submitSucceeded, pristine, reset, submitting, error }) =>
submitSucceeded ? (
<Redirect to="/login" />
) : (
<div>
<form onSubmit={ handleSubmit } autoComplete="off">
<div>
<label htmlFor="username" style={{color:'white', fontSize:'20px'}} >Username</label>
<Field name="username" component={ renderField } type="text" />
<label htmlFor="email" style={{color:'white', fontSize:'20px'}} >Email</label>
<Field name="email" component={ renderField } type="email" />
<label htmlFor="password" style={{color:'white', fontSize:'20px'}} >Password</label>
<Field name="password" component={ renderField } type="password" required autoComplete="current-password" />
<label htmlFor="Rpassword" style={{color:'white', fontSize:'20px'}} >Repeat Password</label>
<Field name="Rpassword" component={ renderField } type="password" required />
</div>
<div>
{ error && <strong style={{color:'coral'}}>{ error }</strong> }
</div>
<br></br>
<button type="submit" disabled={ pristine || submitting } className="btn btn-outline-primary btn-lg">SIGN UP</button>
</form>
<br></br>
<div>
<label htmlFor="Link" style={{color:'goldenrod'}}>already registered?</label>
<br></br>
<Link to='/login' className="btn btn-outline-alert btn-lg">LOGIN</Link>
</div>
</div>
)
export default SignUpForm = reduxForm({
form: 'SignUp',
validate,
onSubmit: ( values, dispatch ) => {
return dispatch(register( values )).catch( err => {
throw new SubmissionError({
_error: 'SignUp Failed',
password: '<PASSWORD>',
Rpassword: '<PASSWORD>',
email: 'Enter a valid Email please'
})
})
}
})( SignUpForm )<file_sep>/src/components/Chatroom/ChatRoom.js
import React from 'react'
import './messageSty.css'
const chatSty = {
backgroundColor: '#2F2342',
minHeight: "100vh",
display: 'flex',
alignItems: 'center',
justifyContent:'center'
}
const inputS = {
backgroundColor:'transparent',
border: '0px Solid',
color: 'goldenrod',
fontSize: '15px',
alignItems: 'center',
}
const ChatRoom = ({members, messageDraft, messages, onSendMessage, onLogOut, onMessageChange, onClickDestroy, isLogged}) => (
<div className="container-fluid" style={chatSty}>
<div className="row">
<div className='.col-'>
{/*users*/}
<h3 style={{color:'white'}}>Users Online</h3>
<div className="jumbotron">
{!members.length ? (<p className='lead'>No Members on display</p>):(members.map(member => (<li key={member} className='list-group-item'><span><img src="https://vignette.wikia.nocookie.net/thewwcbritishwildlife/images/5/50/Green_dot.png/revision/latest?cb=20120329111716" alt="Online" style={{height:'10px'}}></img></span>{member}</li>)))}
<br></br>
<div className='col'>
{/*BOTON LOGOUT*/}
<button
className="btn btn-outline-danger btn-lg"
onClick={ e => {
e.preventDefault()
onLogOut()
}}
>Log Out
</button>
</div>
</div>
</div>
{/*Messages*/}
<div className="col-md">
<h3 style={{color:'white'}}>Messages</h3>
<div className='jumbotron' style={{backgroundColor:'#921099'}}>
{!messages.length ? (<p className='lead' style={{color:'orange',fontWeight: 'bold'}}>No messages on display</p>):(messages.map(message => (<li key={message.id} style={{backgroundColor:'rgba(0,0,0,0.2)', color:'orange', border: 'none'}} onClick={e => onClickDestroy(message.id)} className='list-group-item'>{message.text}<span><img style={{height:'10px'}} alt="destroy" src="https://image.flaticon.com/icons/svg/69/69381.svg"></img></span></li>)))}
<br></br>
{/*SEND*/}
<div className='form-group'>
<form onSubmit={e =>{ e.preventDefault();onSendMessage(messageDraft)}}>
<input type="text"
onChange={e=> onMessageChange(e.target.value)}
value={messageDraft}
className='form-control'
placeholder="Write your Message Here"
required
style={inputS}
/>
<br></br>
<br></br>
<button className='btn btn-outline-warning btn-lg'>Send</button>
</form>
</div>
</div>
</div>
</div>
</div>
)
export default ChatRoom
<file_sep>/src/components/Lobby/index.js
import Lobby from './Lobby'
export default Lobby<file_sep>/src/components/SignUp/validate.js
const validate = values => {
const errors = {}
if ( !values.username) {
errors.username = 'Username is required'
}
if ( !values.password ) {
errors.password = 'The password is required'
}
if ( !values.email ) {
errors.email = 'The email field is required'
}
return errors
}
export default validate<file_sep>/src/containers/SignUpContainer.js
import SignUp from '../components/SignUp'
import { changeDraft } from '../actions' //me estoy trayendo un Action Creator
import { register } from '../actions' //Armando el selector para no hardcodear el state
import { getDraft } from '../selectors' //Armando el selector para no hardcodear el state
import { getToken } from '../selectors' //Armando el selector para no hardcodear el state
import { getUserId } from '../selectors' //Armando el selector para no hardcodear el state
import { connect } from 'react-redux'
const mapStateToProps = state => ({
draft: getDraft( state ),
token: getToken( state ),
userId: getUserId( state )
})
const mapDispatchToProps = dispatch => ({
onDraftChange: ( draftValue ) => {
dispatch( changeDraft( draftValue ) );
},
onSetUser: ( username, email, password ) => {
dispatch( register( username, email, password ) );
},
})
export default connect( mapStateToProps, mapDispatchToProps )( SignUp );<file_sep>/src/components/Chatroom/index.js
import ChatRoom from './ChatRoom'
export default ChatRoom<file_sep>/src/reducers/messagesReducer.js
import {
ADD_MESSAGE,
DELETE_MESSAGE,
LOG_OUT
} from '../constants/actionTypes.js'
const initialState = []
const messagesReducer = (state=initialState, action) => {
switch (action.type) {
case ADD_MESSAGE:
return [
...state, {
id: action.id,
text: action.value
}
]
case DELETE_MESSAGE:
return state.filter(t=> t.id !== action.id)
case LOG_OUT:
return []
default:
return state
}
}
export default messagesReducer<file_sep>/src/reducers/isLoggedReducer.js
import {
SAVE_TOKEN,
LOG_OUT
} from '../constants/actionTypes.js'
const initialStaste = false
const isLoggedReducer = (state=initialStaste,action) => {
switch (action.type) {
case SAVE_TOKEN:
return true
case LOG_OUT:
return false
default:
return state
}
}
export default isLoggedReducer<file_sep>/src/reducers/messagesIdReducer.js
import {
ADD_MESSAGE,
LOG_OUT
} from '../constants/actionTypes.js'
const initialState = ''
const messagesIdReducer = ( state= initialState, action ) => {
switch (action.type) {
case ADD_MESSAGE:
return action.id
case LOG_OUT:
return ''
default:
return state
}
}
export default messagesIdReducer<file_sep>/src/constants/actionTypes.js
//CONSTANTS
export const GET_USERS = 'GET_USERS'
export const ADD_USER = 'ADD_USER'
export const ADD_MEMBER = 'ADD_MEMBER'
export const AUTH_USER = 'AUTH_USER'
export const CHANGE_DRAFT = 'CHANGE_DRAFT'
export const MESSAGE_CHANGE_DRAFT = 'MESSAGE_CHANGE_DRAFT'
export const GET_MESSAGES = 'GET_MESSAGES'
export const ADD_MESSAGE = 'ADD_MESSAGE'
export const DELETE_MESSAGE = 'DELETE_MESSAGE'
export const TURN_ON_LOADER = 'TURN_ON_LOADER'
export const TURN_OFF_LOADER = 'TURN_OFF_LOADER'
export const IS_LOGGED = 'IS_LOGGED'
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'
export const LOG_OUT = 'LOG_OUT'
export const SAVE_TOKEN = "SAVE_TOKEN"
export const ER_TOKEN = "ER_TOKEN"
export const SIGN_OK = "SIGN_OK"
<file_sep>/src/selectors/index.js
//Selectores = buscar puntualmente el state de un component puntual
export const getDraft = state => state.loginDraft
export const getMessageDraft = state => state.messageDraft
export const getMessageId = state => state.messageId
export const getUserId = state => state.userId
export const getMembers = state => state.members
export const getMessages = state => state.messages
export const getisLogged = state => !!state.token
export const getToken = state => state.token
export const getChannels = state => state.channels<file_sep>/src/components/Login/LoginForm.js
import React from 'react'
import { Redirect } from 'react-router-dom'
import { login } from '../../actions'
import { reduxForm, Field, SubmissionError } from 'redux-form'
import validate from './validate'
const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<div>
<input {...input} placeholder={label} type={type}/>
<div style={{color:'goldenrod'}}>
{touched && error && <span>{error}</span>}
</div>
</div>
</div>
)
let LoginForm = ({ handleSubmit, submitSucceeded, pristine, reset, submitting, error }) =>
submitSucceeded ? (
<Redirect to="/chatroom" />
) : (
<div>
<form onSubmit={handleSubmit} autoComplete="off">
<div>
<label htmlFor="username" style={{color:'white', fontSize:'20px'}} >Username</label>
<Field name="username" component={ renderField } type="text" placeholder="Username" />
</div>
<div>
<label htmlFor="password" style={{color:'white', fontSize:'20px'}} >Password</label>
<Field name="password" component={ renderField } type="password" placeholder="<PASSWORD>" required autoComplete="current-password" />
</div>
{error && <div style={{color:'coral'}}>{error}</div>}
<br></br>
<button type="submit" disabled={ pristine || submitting } className="btn btn-outline-primary btn-lg">JOIN</button>
</form>
</div>
)
export default LoginForm = reduxForm({
form: 'login',
validate,
onSubmit: ( values, dispatch ) => {
return dispatch(login( values )).catch( err => {
throw new SubmissionError({
_error: 'Login Failed',
username: 'That User is Invalid',
password: '<PASSWORD>'
})
})
}
})(LoginForm)<file_sep>/src/reducers/membersReducer.js
import {
SAVE_TOKEN,
LOG_OUT
} from '../constants/actionTypes.js'
const membersReducer = ( state=[], action ) => {
switch (action.type) {
case SAVE_TOKEN:
return [
...state,
action.username
]
case LOG_OUT:
return []
default:
return state
}
}
export default membersReducer | cd605839a0f4b0d04b6d80dd2eb0a16315ac5d94 | [
"JavaScript"
] | 18 | JavaScript | sammartfrank/chatreact | 9385584561ea25896ce0eb8f0a92869eb87131be | fe214738e674a203349f3c0e442875da48f702e0 |
refs/heads/master | <file_sep>$(document).ready(function(){
var sessionLength = 25;//default
var breakLength = 5;//default
var start = "START";
var minutesLeft;
var secondsLeft;
var timeInterval;
$("#session").text(sessionLength);
$("#break").text(breakLength);
$(".timer-txt h1").text(start);
//decrease session time
$("#dec1").on("click", function(event) {
if(sessionLength > 0) {
sessionLength -= 1;
$("#session").text(sessionLength);
}
}); //end decrease session time
//increase session time
$("#inc1").on("click", function(event) {
sessionLength += 1;
$("#session").text(sessionLength);
}); //end increase session time
//decrease break time
$("#dec2").on("click", function(event) {
if(breakLength > 0) {
breakLength -= 1;
$("#break").text(breakLength);
}
}); //end decrease break time
//increase break time
$("#inc2").on("click", function(event) {
breakLength += 1;
$("#break").text(breakLength);
}); //end increase break time
//session timer function
var sessionCount = function() {
timeInterval = setInterval(function() {
if(minutesLeft > 0 && secondsLeft == 0) {
minutesLeft -= 1;
secondsLeft = 59;
$("#timer-btn h1").text(minutesLeft + ":" + secondsLeft);
} else if(minutesLeft > 0 && secondsLeft > 10) {
secondsLeft -= 1;
$("#timer-btn h1").text(minutesLeft + ":" + secondsLeft);
} else if(minutesLeft > 0 && secondsLeft <= 10 && secondsLeft > 1) {
secondsLeft -= 1;
$("#timer-btn h1").text(minutesLeft + ":0" + secondsLeft);
} else if(minutesLeft > 0 && secondsLeft == 1) {
minutesLeft -= 1;
secondsLeft = 59;
$("#timer-btn h1").text(minutesLeft + ":" + secondsLeft);
} else if(minutesLeft == 0 && secondsLeft > 10) {
secondsLeft -= 1;
$("#timer-btn h1").text(minutesLeft + "0:" + secondsLeft);
} else if(minutesLeft == 0 && secondsLeft <= 10 && secondsLeft >= 1) {
secondsLeft -= 1;
$("#timer-btn h1").text(minutesLeft + "0:0" + secondsLeft);
} else if(minutesLeft == 0 && secondsLeft == 0) {
clearInterval(timeInterval);
$(".alert").trigger('play');
breakCount();
}
}, 1000);
};
//end session timer function
//session timer function
var breakCount = function() {
minutesLeft = breakLength;
secondsLeft = 0;
timeInterval = setInterval(function() {
if(minutesLeft > 0 && secondsLeft == 0) {
minutesLeft -= 1;
secondsLeft = 59;
$("#timer-btn h1").text(minutesLeft + ":" + secondsLeft);
} else if(minutesLeft > 0 && secondsLeft > 10) {
secondsLeft -= 1;
$("#timer-btn h1").text(minutesLeft + ":" + secondsLeft);
} else if(minutesLeft > 0 && secondsLeft <= 10 && secondsLeft > 1) {
secondsLeft -= 1;
$("#timer-btn h1").text(minutesLeft + ":0" + secondsLeft);
} else if(minutesLeft > 0 && secondsLeft == 1) {
minutesLeft -= 1;
secondsLeft = 59;
$("#timer-btn h1").text(minutesLeft + ":" + secondsLeft);
} else if(minutesLeft == 0 && secondsLeft > 10) {
secondsLeft -= 1;
$("#timer-btn h1").text(minutesLeft + "0:" + secondsLeft);
} else if(minutesLeft == 0 && secondsLeft <= 10 && secondsLeft >= 1) {
secondsLeft -= 1;
$("#timer-btn h1").text(minutesLeft + "0:0" + secondsLeft);
} else if(minutesLeft == 0 && secondsLeft == 0) {
clearInterval(timeInterval);
$(".alert").trigger('play');
sessionCount();
}
}, 1000);
};
//end session timer function
//start button
$("#timer-btn").on("click", function(event){
$("#timer-btn").fadeOut("slow", function(){
start = sessionLength;
minutesLeft = sessionLength;
secondsLeft = 0;
$("#timer-btn h1").text(minutesLeft + ":0" + secondsLeft).css({"font-size": "112px", "margin-top": "16%"});
$("#timer-btn").removeClass("timer-txt")
.addClass("timer-start")
.fadeIn("slow", function(){
});//end animation
sessionCount();
});
});//end start button click event
//pause/resume button
$(".stop").on("click", function(event){
if($(".stop").hasClass("pause")) {
clearInterval(timeInterval);
$("#toggle").text("RESUME");
$(".stop").removeClass("pause");
$(".stop").addClass("resume");
} else if($(".stop").hasClass("resume")) {
$("#toggle").text("PAUSE");
sessionCount();
$(".stop").removeClass("resume");
$(".stop").addClass("pause");
}
});
//end pause/resume button
//reset button
$(".reset").on("click", function(){
minutesLeft = sessionLength;
secondsLeft = 0;
$("#timer-btn h1").text(minutesLeft + ":0" + secondsLeft);
$("#toggle").text("START");
});
//end reset button
}); //end document<file_sep># pomodoro
The pomodoro timer project from the FreeCodeCamp Curriculum
| 31a9ce877dddce12f683ed1488e501caea69e1f4 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | trevawhateva/pomodoro | d8b1eec1018aea46a413aad4999c32a0c3b2384b | 7d4bb73f8b9f7be44878a5d56943bd015b80bd1d |
refs/heads/main | <file_sep>#! /usr/bin/env python3
import cgitb, cgi
from libs import tags
cgitb.enable(display=0, logdir="./")
DISPLAY_FLEX_CENTER_COLUMN = "display: flex;align-items: center;justify-content: center;flex-direction: column;"
DISPLAY_FLEX_CENTER_ROW = "display: flex;align-items: center;justify-content: center;flex-direction: row;"
tags.enc_print(
tags.init_html(
inside= tags.head(
inside="<meta charset='UTF-8'>"+
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>"+
"<meta http-equiv='X-UA-Compatible' content='IE=edge'>"+
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"+
"""
<style>
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
</style>
"""
,
title="Cadastro"
) +
tags.body(
inside= tags.div(
styles= DISPLAY_FLEX_CENTER_COLUMN + "min-height: 100%;",
inside= tags.form(
tags.div(
styles= DISPLAY_FLEX_CENTER_ROW,
inside=tags.input_tag(
label=True,
label_text="Nome: ",
placeholder="Digite seu nome",
id="name",
div_margin=3
)+
tags.input_tag(
label=True,
label_text="Email: ",
placeholder="Digite seu email",
id="email",
div_margin=3
)
)+
tags.br(1)+
tags.div(
styles= DISPLAY_FLEX_CENTER_ROW,
inside=tags.input_tag(
label=True,
label_text="Peso(Kg): ",
placeholder="Digite seu peso",
id="weight",
div_margin=3
)+
tags.input_tag(
label=True,
label_text="Altura(m): ",
placeholder="Digite seu altura",
id="height",
div_margin=3
)
)+
tags.br(1)+
tags.div(
styles= DISPLAY_FLEX_CENTER_ROW + "width: 100%;",
inside=tags.input_tag(
label=True,
label_text="Data de Nasciemnto: ",
placeholder="Digite sua data de nascimento",
id="birth_date",
type="date",
styles="width: 100%;",
div_width="100%"
)
)+
tags.br(1)+
tags.div(
styles= DISPLAY_FLEX_CENTER_ROW,
inside=tags.input_tag(
label=True,
label_text="Senha: ",
placeholder="Digite sua senha",
type="<PASSWORD>",
id="password",
div_margin=3
)+
tags.input_tag(
label=True,
label_text="Confirmação de senha: ",
label_styles="display:absolute;",
placeholder="Redigite sua senha",
type="password",
id="confirm_password",
div_margin=3
)
)+
tags.button(
inside="Cadastro",
type="submit",
styles="margin-top:17px;"
),
id="form",
method= "post",
styles= DISPLAY_FLEX_CENTER_COLUMN
)+
tags.p(
"Já cadastrado?"+
tags.a(
text="Realizar login",
href="./sign_in.py"
),
styles="margin-top:0px;"
)
)+
tags.div(
id= "myModal",
classes= "modal",
inside= tags.div(
classes= "modal-content",
inside=tags.p(
inside= "",
id= "modal-text"
)+
tags.div(
styles= DISPLAY_FLEX_CENTER_ROW,
inside= tags.button(
styles= "margin: 5px",
id= "confirm",
inside="Confirmar"
)+
tags.button(
styles= "margin: 5px",
id= "cancel",
inside= "Cancelar"
)
)
)
)+
tags.script(
inside="""$(document).ready(function(){
var email_input = $('#email');
var weight_input = $('#weight');
var birth_date_input = $('#birth_date');
var height_input = $('#height');
var name_input = $('#name');
var password_input = $('#password');
var confirm_password_input = $('#confirm_password');
var modal = document.getElementById("myModal");
var confirm = document.getElementById("confirm");
var cancel = document.getElementById("cancel");
var modalText = document.getElementById("modal-text");
function setModalText(){
modalText.innerHTML = '<h3> Confirme os seus dados</h3>'+
'Nome: '+ name_input.val() + '<br>' +
'Email: ' + email_input.val() + '<br>' +
'Peso: ' + weight_input.val() + '<br>' +
'Altura: ' + height_input.val() + '<br>' +
'Data de nasciemnto: ' + birth_date_input.val() + '<br>';
}
$('#form').submit(function(e){
e.preventDefault();
setModalText();
modal.style.display = "block";
});
function clearForm() {
email_input.val('');
weight_input.val('');
birth_date_input.val('');
height_input.val('');
name_input.val('');
password_input.val('');
confirm_password_input.val('');
}
// When the user clicks the button, open the modal
confirm.onclick = function() {
$.ajax({
type: 'POST',
url: 'controllers/users_controller.py',
data: {
action: 'sign_up',
email: email_input.val(),
weight: weight_input.val(),
birth_date: birth_date_input.val(),
height: height_input.val(),
name: name_input.val(),
password :<PASSWORD>(),
confirm_password: confirm_password_input.val()
},
success:function(res){
if(res['status'] == 'success'){
alert('O seu cadastro foi efetuado com sucesso');
clearForm();
}else if(res['status'] == 'error'){
alert('Ocorreu um erro durante seu cadastro: '+res['message']);
} else {
alert('Ocorreu um erro imprevisto.')
}
modal.style.display = "none";
},
error:function(xhr,errmsg,err){
alert(xhr.status + ': ' + xhr.responseText);
modal.style.display = "none";
}
});
}
cancel.onclick = function closeModal() {
modal.style.display = "none";
}
});"""
)
)
)
)
<file_sep>import sys
def a(href="#",text="",classes="",id="",styles=""):
return(
"<a href='"+href+"' class='"+classes+"' id='"+id+"' style='"+styles+"'>"+
text+
"</a>"
)
def body(inside,classes="",id="",styles=""):
return(
"<body class='"+classes+"' id='"+id+"' style='"+styles+"'>"+
inside+
"</body>"
)
def br(repeat=1):
return "<br>"*repeat
def button(inside,type="",onClick="",classes="",id="",styles=""):
return(
"<button class='"+classes+"' id='"+id+"' style='"+styles+"' onClick='"+onClick+"' >"+
inside+
"</button>"
)
def div(inside,classes="",id="",styles=""):
return(
"<div class='"+classes+"' id='"+id+"' style='"+styles+"'>"+
inside+
"</div>"
)
def enc_print(string='', encoding='utf8'):
sys.stdout.buffer.write(string.encode(encoding) + b'\n')
def form(inside,action="",method="",classes="",id="",styles=""):
return(
"<form action='"+action+"' method='"+method+"' class='"+classes+"' id='"+id+"' style='"+styles+"'>"+
inside+
"</form>"
)
def h1(inside,classes="",id="",styles=""):
return(
"<h1 class='"+classes+"' id='"+id+"' style='"+styles+"'>"+
inside+
"</h1>"
)
def head(inside,title=""):
return(
"<head>"+
"<title>"+title+"</title>"+
inside +
"</head>"
)
def init_html(inside,classes="",id="",styles=""):
print("Content-type:text/html; charset=utf-8\r\n\r\n")
return (
"<html>"+
inside +
"</html>"
)
def input_tag(value="",div_margin=0,div_width="",label=False,label_text="",type="text",label_classes="",label_id="",label_styles="",classes="",id="",styles="",placeholder=""):
string = ""
if label:
string += "<div style='margin: "+str(div_margin)+"px; width: "+div_width+";'><label for='"+id+"' class='"+label_classes+"' id='"+label_id+"' style='"+label_styles+"'>"+label_text+"</label><br>"
string += "<input type='"+type+"' id='"+id+"' name='"+id+"' value='"+value+"' placeholder='"+placeholder+"' style='"+styles+"'>"
if label:
string += "</div>"
return string
def p(inside,classes="",id="",styles=""):
return(
"<p class='"+classes+"' id='"+id+"' style='"+styles+"'>"+
inside+
"</p>"
)
def script(inside):
return(
"<script>"+
inside+
"</script>"
)
def select(value="",options=[],div_margin=0,label=False,label_text="",type="text",label_classes="",label_id="",label_styles="",classes="",id="",styles="",placeholder=""):
string = ""
if label:
string += "<div style='margin: "+str(div_margin)+"px;'><label for='"+id+"' class='"+label_classes+"' id='"+label_id+"' style='"+label_styles+"'>"+label_text+"</label><br>"
string += "<select type='"+type+"' id='"+id+"' name='"+id+"' value='"+value+"' placeholder='"+placeholder+"'>"
for option in options:
string += "<option value='"+option.lower()+"'>"+option+"</option>"
string += "<select>"
if label:
string += "</div>"
return string
def span(inside,classes="",id="",styles=""):
return(
"<span class='"+classes+"' id='"+id+"' style='"+styles+"'>"+
inside+
"</span>"
)
def table(header=False,content=[],classes="",id="",styles=""):
string = "<table class='"+classes+"' id='"+id+"' style='"+styles+"'>"
for i in range(len(content)):
string += "<tr>"
for j in content[i]:
if i == 0 and header:
string += "<th>"
else:
string += "<td>"
string += str(j)
if i == 0 and header:
string += "</th>"
else:
string += "</td>"
string += "</tr>"
string += "</table>"
return string
<file_sep>#! /usr/bin/env python3
import cgitb, cgi
from libs import tags
cgitb.enable(display=0, logdir="./")
DISPLAY_FLEX_CENTER_COLUMN = "display: flex;align-items: center;justify-content: center;flex-direction: column;"
tags.enc_print(
tags.init_html(
inside= tags.head(
inside="<meta http-equiv='X-UA-Compatible' content='IE=edge'>"+
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>"+
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"+
"<!-- HTML 4 -->"+
"<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>"+
"<!-- HTML5 -->"+
"<meta charset='UTF-8'/>",
title="Login"
) +
tags.body(
inside= tags.div(
inside= tags.form(
tags.input_tag(
label=True,
label_text="Email: ",
placeholder="Digite seu email",
id= "email"
)+
tags.br(2)+
tags.input_tag(
label=True,
label_text="Senha: ",
placeholder="Digite sua senha",
type="password",
id="password"
)+
tags.button(
inside="Entrar",
type="submit",
styles="margin-top:17px;"
),
id="form",
method= "post",
styles= DISPLAY_FLEX_CENTER_COLUMN
)+
tags.p(
"Ainda não cadastrado?"+
tags.a(
text="Realizar cadastro",
href="sign_up.py"
)
),
styles= DISPLAY_FLEX_CENTER_COLUMN + "min-height: 100%;"
)+
tags.script(
inside=
"""
$(document).ready(function(){
$('#form').submit(function(e){
e.preventDefault();
var email = $('#email').val();
var password= $('#password').val();
$.ajax({
type: 'POST',
url: 'controllers/users_controller.py',
data: {
action: 'sign_in',
email:email,
password:<PASSWORD>,
},
success:function(res){
if(res['status'] == 'success'){
window.location.href = './home.py';
}else if(res['status'] == 'error'){
alert('Ocorreu um erro durante seu login: '+res['message']);
} else {
alert('Ocorreu um erro imprevisto.')
}
},
error:function(xhr,errmsg,err){ alert(xhr.status + ': ' + xhr.responseText);}
});
});
});"""
)
)
)
)
<file_sep>#! /usr/bin/env python3
import cgitb, cgi
from libs import tags
from controllers.models.user import User
cgitb.enable(display=0, logdir="./")
DISPLAY_FLEX_CENTER = "display: flex;align-items: center;justify-content: center;flex-direction: column;"
tags.enc_print(
tags.init_html(
inside= tags.head(
inside="<meta http-equiv='X-UA-Compatible' content='IE=edge'>"+
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>"+
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"+
"<!-- HTML 4 -->"+
"<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>"+
"<!-- HTML5 -->"+
"<meta charset='UTF-8'/>"+
"""
<style>
table, td, th {
border: 1px solid black;
}
table {
width: 100%;
border-collapse: collapse;
}
</style>
""",
title="Index"
) +
tags.body(
inside=tags.button(
inside="Apagar todos os registros",
onClick="destroyAll()",
styles="margin: 10px;"
)+
tags.table(
header= True,
content= User.allToTable(),
styles= "border-collapse: collapse;"
)+
tags.script(
"""
function destroyAll(){
$.ajax({
type: 'POST',
url: 'controllers/users_controller.py',
data: {
action: 'delete'
},
success:function(res){
if(res['status'] == 'success'){
location.reload();
}else if(res['status'] == 'error'){
alert('Ocorreu um erro durante seu login: '+res['message']);
} else {
alert('Ocorreu um erro imprevisto.')
}
},
error:function(xhr,errmsg,err){ alert(xhr.status + ': ' + xhr.responseText);}
});
}
"""
)
)
)
)
<file_sep>import sqlite3
class User():
__id= ""
__name= ""
__birth_date= ""
__weight= ""
__height= ""
__email= ""
__password= ""
def __init__(self,id=0,name="",birth_date="",weight="",height="",email="",password=""):
self.conexao = sqlite3.connect("./banco.sqlite")
self.createTable()
self.__id = id
self.__name = name
self.__birth_date = birth_date
self.__weight = weight
self.__height = height
self.__email = email
self.__password = password
def createTable(self):
c = self.conexao.cursor()
c.execute(
"""create table if not exists users (
id integer primary key autoincrement ,
name text,
birth_date text,
weight text,
height text,
email text,
password text
)"""
)
self.conexao.commit()
c.close()
def save(self):
c = self.conexao.cursor()
sql = """insert into users (name,birth_date,weight,height,email,password)
values ('{}','{}','{}','{}','{}','{}')""".format(
self.__name,self.__birth_date,self.__weight,
self.__height,self.__email,self.__password
)
c.execute(sql)
self.conexao.commit()
self.__id = c.lastrowid
c.close()
return self.__id
def getId(self):
return self.__id
def getEmail(self):
return self.__email
def getPassword(self):
return self.__<PASSWORD>
def getAttributes(self):
return {
"name": self.__name,
"birth_date": self.__birth_date,
"weight": self.__weight,
"height": self.__height,
"email": self.__email,
"password": self.__<PASSWORD>
}
@staticmethod
def find_by(options={}):
conexao = sqlite3.connect("./banco.sqlite")
c = conexao.cursor()
sql = "select * from users where"
for item in options.items():
sql += " " + str(item[0]) + " = '" + str(item[1]) + "'"
sql += ";"
c.execute(sql)
conexao.commit()
for row in c:
user = User(
id= row[0],
name= row[1],
birth_date= row[2],
weight= row[3],
height= row[4],
email= row[5],
password= row[6]
)
c.close()
if 'user' in locals():
return user
else:
return User()
@staticmethod
def login(email="",password=""):
conexao = sqlite3.connect("./banco.sqlite")
c = conexao.cursor()
c.execute("select * from users where email = '{}' and password = '{}';".format(email,password))
conexao.commit()
for row in c:
user = User(
id= row[0],
name= row[1],
birth_date= row[2],
weight= row[3],
height= row[4],
email= row[5],
password= row[6]
)
c.close()
if 'user' in locals():
return user
else:
return None
@staticmethod
def all():
conexao = sqlite3.connect("./banco.sqlite")
c = conexao.cursor()
c.execute("select * from users;")
conexao.commit()
users = []
for row in c:
users << User(
id= row[0],
name= row[1],
birth_date= row[2],
weight= row[3],
height= row[4],
email= row[5],
password= row[6]
)
c.close()
return users
@staticmethod
def allToTable():
conexao = sqlite3.connect("./banco.sqlite")
c = conexao.cursor()
c.execute("select * from users;")
conexao.commit()
users = [['id','nome','data de nascimento','peso','altura','email']]
for row in c:
users.append([row[0], row[1], row[2], row[3], row[4], row[5]])
c.close()
return users
@staticmethod
def destroy_all():
conexao = sqlite3.connect("./banco.sqlite")
c = conexao.cursor()
c.execute("delete from users;")
conexao.commit()
c.close()
<file_sep>import cgi,sys
import json
import sqlite3
from models.user import User
form = cgi.FieldStorage()
action = form.getvalue("action")
confirm_password = form.getvalue("confirm_password")
dic = {}
user = User(
name= form.getvalue("name"),
weight= form.getvalue("weight"),
height= form.getvalue("height"),
birth_date= form.getvalue("birth_date"),
email= form.getvalue("email"),
password= form.getvalue("password")
)
if action == "sign_up":
if User.find_by(options={"email": user.getEmail()}).getEmail() == user.getEmail():
dic["status"] = "error"
dic["message"] = "Email já cadastrado."
elif(user.getPassword() != confirm_password):
dic["status"] = "error"
dic["message"] = "As senhas não são iguais."
else:
if user.save() == None:
dic["status"] = "error"
dic["message"] = "Ouve um problema no processaento, verifique seus dados e tente novamente."
else:
dic["status"] = "success"
dic["message"] = "Cadastro realizado com sucesso"
dic["user"] = user.getAttributes()
elif action == "sign_in":
if User.login(email=user.getEmail(),password=user.getPassword()) != None:
dic["status"] = "success"
dic["user"] = User.find_by(options={"email": user.getEmail()}).getAttributes()
else:
dic["status"] = "error"
dic["message"] = "Email ou senha incorretos"
dic["user"] = user.getAttributes()
elif action == "delete":
User.destroy_all()
dic["status"] = "success"
else:
dic["status"] = "error"
dic["message"] = "A ação que você deseja realizar é inválida."
sys.stdout.write("Content-Type: application/json\n\n")
sys.stdout.write(json.dumps(dic))
| a973b683899ce5530f402b15187a72f90eaba80d | [
"Python"
] | 6 | Python | Ysaakue/python_cgi | f837f91fb6b70b4922e5310537c2ec9f80e4ac4a | 296d49569a54e60d64b333e87a4b8bcde8c6f6c6 |
refs/heads/master | <file_sep>## Creating your first Discord Bot with Discord.js

## The goal
* Create a simple Discord Bot that responds to keywords or phrases typed into a channel by other users.
## Follow the full tutorial
<a href="https://grant-bartlett.com/creating-your-own-discord-bot-with-discord.js/">Follow the tutorial</a>
## Instructions
* `npm install`
* `npm start`
<file_sep>const { token, prefix } = require('../config.json');
const Discord = require('discord.js');
const client = new Discord.Client();
// Listen to the Bot being ready
client.once('ready', () => onClientReady());
function onClientReady()
{
// Listen to Messages in the channel
client.on('message', (message) => onMessageReceived(message));
}
function onMessageReceived(message)
{
// Stop if our message content does not have the prefix we are looking to reply to
if (!message.content.toLowerCase().startsWith(prefix.toLowerCase()))
{
return;
}
if (message.content.includes("time"))
{
message.reply("The time is " + new Date().toLocaleTimeString());
}
else if (message.content.includes("weather"))
{
message.reply("Do I look like a weather bot?");
}
else
{
message.reply("I wish I was an Android!!!");
}
}
client.login(token); | d795cf634978c8fe339c23111bb09af3c849aa7f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Hoku-Boy/creating-your-first-discord-bot-with-discord.js | b7a6dc152e3f1fe2aebeba7a1076b00fb9c1d51f | aafd493123814ab634c71ed2d8dc0578e82afea6 |
refs/heads/master | <file_sep>import argparse
try:
from Tkinter import *
from ttk import *
except ImportError: # Python 3
from tkinter import *
from tkinter.ttk import *
somearray = [0 for x in range(8)]
anames = ['A', 'B', 'C', 'D', 'F']
arrays = {}
[arrays.update({x: somearray}) for x in anames]
class App(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.CreateUI()
self.LoadTable()
self.grid(sticky = (N,S,W,E))
def CreateUI(self):
tv = Treeview(self)
columns = []
for i in range(8):
columns += [str(i+1)]
tv['columns'] = tuple(columns)
for x in tv['columns']:
tv.heading(x, text=x)
tv.column(x, anchor='center', width=70)
tv.grid(sticky = (N,S,W,E))
self.treeview = tv
def LoadTable(self):
[self.treeview.insert('', str(idx), text=i, value=tuple(arrays[i])) for idx, i in enumerate(anames)]
def main():
root = Tk()
parseargs()
root.resizable(width=False, height=False)
App(root)
root.mainloop()
def parseargs():
arguments_parser = argparse.ArgumentParser()
[arguments_parser.add_argument(x, nargs="+") for x in ['--'+x for x in anames]]
arguments = arguments_parser.parse_args()
for x in anames:
arrays[x] = getattr(arguments, x) or somearray
if __name__ == '__main__':
main()<file_sep>#!/bin/bash
echo "1 - Removing tmp files..."
rm -rf dist
echo "2 - Creating tmp folder..."
mkdir dist
echo "4 - Building mul.asm..."
nasm mul.asm -f elf64 -o dist/mul.o
echo "4.1 - Building arr-ops.asm..."
nasm arr-ops.asm -f elf64 -o dist/arr-ops.o
echo "5 - Buildint sum.asm..."
nasm sum.asm -f elf64 -o dist/sum.o
echo "5 - Linding main.o, mul.o..."
g++ main.cpp dist/arr-ops.o dist/sum.o dist/mul.o -o a.out
echo "6 - Deleting tmp files..."
rm -rf dist
echo "Successfully Built."
<file_sep>
#include <stdlib.h>
#include <cstdlib>
#include <string>
#include <sstream>
namespace patch
{
template < typename T > std::string to_string( const T& n )
{
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
#include <iostream>
extern "C" void sum(short *,short *); // mutate first arg
extern "C" void mul(short *,short *); // mutate first arg
extern "C" void arr_ops(char*, char*, char*, short*); // mutate four arrays, store result at shorts array
char A[]={1,2,3,50,5,6,7,8}; // values range [-128..127]
char B[]={2,3,4,2,6,7,8,8}; // values range [-128..127]
char C[]={3,4,5,6,7,8,9,8}; // values range [-128..127]
short D[]={1,3,2,5,6,7,8,8}; // values range [-2^16+1..2^16]
using namespace std;
string arrshtostr(short*arr)
{
string str = "";
for(int i = 0; i < 8; i ++){
str.append(patch::to_string(arr[i]));
str.append(" ");
}
return str;
}
string arrchtostr(char*arr)
{
string str = "";
for(int i = 0; i < 8; i++){
str.append(patch::to_string((short)arr[i]));
str.append(" ");
}
return str;
}
string command = "python3 gui.py";
int main()
{
string A_str = arrchtostr(A);
string B_str = arrchtostr(B);
string C_str = arrchtostr(C);
string D_str = arrshtostr(D);
char* a = A;
char* b = B;
char* c = C;
short* d = D;
arr_ops(a, b, c, d);
cout << endl;
for(int i=0; i< 8; i++){
cout << " | " << d[i];
}
cout << endl;
string F_str = arrshtostr(d);
command.append(" --A ");
command.append(A_str);
command.append(" --B ");
command.append(B_str);
command.append(" --C ");
command.append(C_str);
command.append(" --D ");
command.append(D_str);
command.append(" --F ");
command.append(F_str);
command.append(" &");
system(command.c_str());
return 1;
}
<file_sep># convergation lab
<file_sep>#!/bin/bash
echo "1 - Removing tmp files..."
rm -rf dist
echo "2 - Creating tmp folder..."
mkdir dist
echo "4 - Building findfval.asm..."
nasm findfval.asm -f elf32 -o dist/findfval.o
echo "5 - Buildint findsval.asm..."
nasm findsval.asm -f elf32 -o dist/findsval.o
echo "5 - Linding main.o, findroots.o..."
g++ main.cpp dist/findsval.o dist/findfval.o -m32 -o a.out
echo "6 - Deleting tmp files..."
rm -rf dist
echo "Successfully Built."
<file_sep>#include <stdio.h>
extern "C" {int findroots(double, double, double, double *, double *);}
int main()
{
double a = 0;
double b = 0;
double c = 0;
double rootfirst = 0;
double rootsecond = 0;
int condition = 0;
printf("\tCalculate equation: a*x^2 + b*x + c = 0.\n");
printf("Enter a: ");
scanf("%lf", &a);
printf("Enter b: ");
scanf("%lf", &b);
printf("Enter c: ");
scanf("%lf", &c);
condition = findroots(a, b, c, &rootfirst, &rootsecond);
printf("\tEquation Calculation\n");
if(condition == 0)
printf("No real roots in equation\n");
if(condition == 1)
printf("First root: %.2lf\nSecond root: %.2lf\n", rootfirst, rootsecond);
if(condition == 2)
printf("Root: %.2lf\n", rootfirst);
return 0;
}
<file_sep># quadratic equation lab
<file_sep>#include <stdio.h>
extern "C" void findfval(double, double*);
extern "C" int findsval(double, double, double, double*);
int main()
{
double a = 0;
double b = 0;
double h = 0;
double e = 0;
double t = 0;
double fval = 0;
double sval = 0;
int seqmembcnt = 0;
printf("\tCalculate convergation: interval - [a, b], step - h, accuracy - e\n");
printf("Enter a: ");
scanf("%lf", &a);
printf("Enter b: ");
scanf("%lf", &b);
printf("Enter h: ");
scanf("%lf", &h);
printf("Enter e: ");
scanf("%lf", &e);
for(double x = a; x <= b; x += h)
{
seqmembcnt = 0;
fval = 0;
sval = 0;
findfval(x, &fval);
seqmembcnt = findsval(x, fval, e, &sval);
printf("| x: %lf\t| F: %lf\t| S: %lf\t| n: %d\t|\n", x, fval, sval, seqmembcnt);
}
return 0;
}
<file_sep># asm-conquest
<file_sep>#!/bin/bash
sudo docker run --security-opt seccomp=unconfined -it test /bin/bash
<file_sep>FROM ubuntu:latest
RUN apt-get update; \
apt-get install -y --no-install-recommends \
git \
vim \
g++ \
nasm \
apt-utils \
g++-multilib \
gdb;
RUN apt-get install -y --no-install-recommends ca-certificates
<file_sep>#!/bin/bash
echo "1 - Removing tmp files..."
rm -rf dist
echo "2 - Creating tmp folder..."
mkdir dist
echo "3 - Building main.cpp..."
g++ main.cpp -c -m32 -o dist/main.o
echo "4 - Building findroots.asm..."
nasm findroots.asm -f elf32 -o dist/findroots.o
echo "5 - Linding main.o, findroots.o..."
g++ dist/main.o dist/findroots.o -m32 -o a.out
echo "6 - Deleting tmp files..."
rm -rf dist
echo "Successfully Built."
<file_sep>#include <stdio.h>
#include <stdlib.h>
char **array;
int arraysize=0;
int arraycapacity=0;
int userinput;
int opstatus;
void fleshinput();
int promptmenu();
int show(char**, int);
int push(char**, int);
int insert(char**, int);
int deleteitem(char**, int);
int deleteall(char**, int);
int _push(char*);
int _insert(char*, int);
int _addmemory();
int _delete(int);
int _deleteall();
int main()
{
userinput = promptmenu();
while(true)
{
if(userinput == 1)
opstatus = show(array, arraysize);
else if(userinput == 2)
opstatus = push(array, arraysize);
else if(userinput == 3)
opstatus = insert(array, arraysize);
else if(userinput == 4)
opstatus = deleteitem(array, arraysize);
else if(userinput == 5)
opstatus = deleteall(array, arraysize);
else if(userinput == 6)
break;
userinput = promptmenu();
}
_deleteall();
free(array);
return 0;
}
void fleshinput()
{
char c;
while((c=getchar()) != '\n' && c != EOF) {}
}
int push(char** array, int arraysize)
{
fleshinput();
char *str = (char*)malloc(sizeof(char)*255);
printf("enter new item: ");
scanf("%s", str);
return _push(str);
}
int _push(char* newitem)
{
_addmemory();
array[arraysize] = newitem;
arraysize += 1;
return 1;
}
int insert(char** array, int arraysize)
{
fleshinput();
int position = 0;
char *str = (char*)malloc(sizeof(char)*255);
printf("enter new item: ");
scanf("%s", str);
fleshinput();
printf("enter item position: ");
scanf("%d", &position);
return _insert(str, position);
}
int deleteitem(char** array, int arraysize)
{
fleshinput();
int position = 0;
printf("enter position: ");
scanf("%d", &position);
return _delete(position);
}
int _delete(int position)
{
if(position >= arraysize || position < 0)
return -1;
else
{
for(int i = position; i < arraysize -1; i++)
array[i] = array[i+1];
arraysize -= 1;
return 0;
}
}
int deleteall(char** array, int arraysize)
{
fleshinput();
return _deleteall();
}
int _deleteall()
{
for(int i = 0; i < arraysize; i++)
free(array[i]);
arraysize = 0;
return 0;
}
int _insert(char* newitem, int position)
{
printf("%s - %d\n", newitem, position);
_addmemory();
if(position > arraysize || position < 0)
return -1;
else if(position == arraysize)
_push(newitem);
else
{
char *removeditem;
for(int i = position; i < arraysize + 1; i++)
{
removeditem = array[i];
array[i] = newitem;
newitem = removeditem;
}
arraysize += 1;
}
return 1;
}
int _addmemory()
{
if(arraysize >= arraycapacity)
{
char ** newarray = (char**)malloc((arraycapacity+1)*2*sizeof(char*));
arraycapacity = (arraycapacity+1)*2;
for(int i = 0; i < arraysize; i++)
{
newarray[i] = array[i];
}
free(array);
array = newarray;
}
}
int show(char** array, int arraysize)
{
fleshinput();
printf("<--proc show content-->\n");
for(int i = 0; i < arraysize; i++)
{
printf("\t");
printf("%s | \n", array[i]);
}
printf("back to menu...");
(void)getchar();
return 0;
}
int promptmenu()
{
int userinput;
printf("<--dynamic-array-manager-->\n");
printf(" 1 - show\n");
printf(" 2 - push\n");
printf(" 3 - insert\n");
printf(" 4 - delete\n");
printf(" 5 - delete all\n");
printf(" 6 - exit\n");
printf("choose option 1-6...");
scanf("%d", &userinput);
return userinput;
}
| b775da12807c5e696cb5f88059a403e694bbcd4a | [
"Markdown",
"Dockerfile",
"Python",
"C++",
"Shell"
] | 13 | Python | Kr1an/asm-conquest | 7076d24662612c6a79e12370c5d5d06b43ac0653 | 91718ca8ca297f91a22ddefa7c7d6d0f108d9b63 |
refs/heads/master | <file_sep>void Branding() {
TeksStatis(" JWSCAY", 0, 0);
delay(2000);
TeksStatis(" VER.1", 0, 1);
delay(2000);
}
void printLcd(const RtcDateTime& dt)
{
char datestring[20];
snprintf_P(datestring, countof(datestring), PSTR(" %02u/%02u/%04u"),
dt.Month(),
dt.Day(),
dt.Year() );
Serial.print(datestring);
lcd.setCursor(0, 1);
lcd.print(datestring);
snprintf_P(datestring, countof(datestring), PSTR(" %02u:%02u:%02u"),
dt.Hour(),
dt.Minute(),
dt.Second() );
Serial.print(datestring);
lcd.setCursor(0, 0);
lcd.print(datestring);
}
//-----------------------------------------------------
//Menampilkan Jam
void TampilJam() {
RtcDateTime now = Rtc.GetDateTime();
char jam[8];
int waktu = now.Hour();
// waktu = waktu%10;
sprintf(jam, "%02d:%02d:%02d", //%02d print jam dengan format 2 digit
now.Hour(), //get hour method
now.Minute(), //get minute method
now.Second() //get second method
);
Serial.println(jam); //print the string to the serial port
if (jamsekarang != waktu || tampilcube) {
tampilCube(waktu);
jamsekarang = waktu;
tampilcube = false;
}
TeksStatis(jam, 8, 0);
Serial.println(waktu);
delay(1000); //second delay
}
void TampilJam2() {
RtcDateTime now = Rtc.GetDateTime();
char jam[8];
sprintf(jam, "%02d:%02d:%02d", //%02d print jam dengan format 2 digit
now.Hour(), //get hour method
now.Minute(), //get minute method
now.Second() //get second method
);
Serial.println(jam); //print the string to the serial port
TeksStatis(jam, 8, 0);
//second delay
}
//-----------------------------------------------------
//Menampilkan Tanggal
void TampilTanggal() {
RtcDateTime now = Rtc.GetDateTime();
char tanggal[18];
// sprintf(tanggal, " %s,%02d %s %04u", //%02d allows to print an integer with leading zero 2 digit to the string, %s print sebagai string
// weekDay[now.DayOfWeek()], //ambil method hari dalam format lengkap
// now.Day(), //get day method
// monthYear[now.Month()],
// now.Year()//get month method
// );
sprintf(tanggal, "%02d/%02d/%04u", //%02d allows to print an integer with leading zero 2 digit to the string, %s print sebagai string
// now.DayOfWeek(), //ambil method hari dalam format lengkap
now.Day(), //get day method
now.Month(),
now.Year()//get month method
);
Serial.println(tanggal); //print the string to the serial port
TeksStatis(tanggal, 6, 1);
//delay(3000);
}
//-----------------------------------------------------
//Menampilkan Suhu
void TampilSuhu() {
RtcTemperature temp = Rtc.GetTemperature();
int celsius = temp.AsFloatDegC();
char suhu[2];
int koreksisuhu = 2; // Perkiraan selisih suhu ruangan dan luar ruangan
sprintf(suhu, "SUHU");
TeksStatis(suhu, 0, 0);
sprintf(suhu, "%dC", celsius - koreksisuhu);
TeksStatis(suhu, 0, 1);
}
void TeksStatis(String text, int kolom, int baris) {
lcd.setCursor(kolom, baris);
lcd.print(text);
}
void scrollText(String text, int baris)
{
unsigned int i = text.length();
lcd.setCursor(0, baris);
lcd.print(text);
for (int n = 0; n < i; n++)
{
lcd.scrollDisplayLeft();
delay(500);
}
lcd.clear();
while (1);
// while(text[i] != '\0')
// {
// lcd.print(text);
//// if(i>=16)
//// {
// lcd.command(0x18);
//// }
// delay(500);
// i++;
// }
lcd.clear();
}
//----------------------------------------------------------------------
// BUNYIKAN BEEP BUZZER
void BuzzerPanjang() {
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(1000);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(50);
}
void BuzzerPendek() {
digitalWrite(buzzer, HIGH);
delay(200);
digitalWrite(buzzer, LOW);
delay(100);
digitalWrite(buzzer, HIGH);
delay(200);
digitalWrite(buzzer, LOW);
delay(50);
}
<file_sep>int cayuC[][5] =
{
{0, 1, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0}
};
int cayuA[][5] =
{
{0, 1, 1, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0}
};
int cayuY[][5] =
{
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0}
};
int cayuU[][5] =
{
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0}
};
int hbdH[][5] =
{
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0}
};
int hbdB[][5] =
{
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0}
};
int hbdD[][5] =
{
{0, 0, 0, 1, 0},
{0, 0, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0}
};
int angka1[][5] =
{
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0}
};
int angka6[][5] =
{
{0, 1, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0}
};
int desE[][5] =
{
{0, 1, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0}
};
int desS[][5] =
{
{0, 1, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 1, 0},
{0, 1, 1, 1, 0}
};
int hurufL[][5] =
{
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0}
};
int hurufO[][5] =
{
{0, 1, 1, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0}
};
int kedip[][5] =
{
{0, 1, 0, 1, 0},
{1, 0, 1, 0, 1},
{0, 1, 0, 1, 0},
{1, 0, 1, 0, 1},
{0, 1, 0, 1, 0}
};
int smile[][5] =
{
{0, 0, 0, 1, 0},
{0, 1, 0, 0, 1},
{0, 0, 0, 0, 1},
{0, 1, 0, 0, 1},
{0, 0, 0, 1, 0}
};
void helloCayu() {
delayms = 120;
n(29);
jalan(hbdH);
jalan(desE);
jalan(hurufL);
jalan(hurufL);
jalan(hurufO);
delay(100);
cayuJalan();
delay(100);
jalan(smile);
delay(100);
}
void hbdcayu() {
delayms = 120;
n(29);
jalan(hbdH);
jalan(hbdB);
jalan(hbdD);
delay(100);
cayuJalan();
delay(100);
jalan(angka1);
jalan(angka6);
delay(100);
jalan(hbdD);
jalan(desE);
jalan(desS);
delay(100);
jalan(smile);
delay(100);
}
void cayuJalan() {
jalan(cayuC);
// delay(50);
jalan(cayuA);
// delay(50);
jalan(cayuY);
// delay(50);
jalan(cayuU);
// delay(50);
}
void jalan(int data[5][5]) {
int buf[5][5];
for (int k = 4; k >= -3; k--) {
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (k >= 0) {
if (j - k < 0 ) buf[i][j] = 0;
else buf[i][j] = data[i][j - k];
}
else if (k < 0) {
if (j + k < 0 ) buf[i][k + 5] = 0;
else
buf[i][j + k] = data[i][j];
}
}
}
transferReg(buf);
delay(delayms);
}
}
void transferReg(int data[5][5]) {
int num = 0;
for (int i = 0; i < 5; i++)
{
num = i;
for (int j = 0; j < 5; j++)
{
regWrite(num, data[i][j]);
num += 5;
}
}
}
void initCube() {
//Initialize array
registerState = new byte[numOfRegisters];
for (size_t i = 0; i < numOfRegisters; i++) {
registerState[i] = 0;
}
//set pins to output so you can control the shift register
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void cube() {
// allOff();
for (int i = 29; i >= 26 ; i--) {
n(i);
n(i - 1);
delay(100);
f(i);
f(i - 1);
}
delay(100);
allOff();
TeksStatis(" HAPPY ", 0, 0);
TeksStatis(" BIRTHDAY ", 0, 1);
// void loop() {
// while (1) {
// for (int i = 100; i > 30; i -= 10) {
// delayms = 120;
// hujan();
// }
// //
// }
// for (int i = 800; i > 700; i -= 100) {
// delayms = i;
// ulangTahun();
// }
hbdcayu();
TeksStatis(" SELAMAT HARI ", 0, 0);
TeksStatis(" LAHIR ", 0, 1);
for (int i = 100; i > 30; i -= 10) {
delayms = 170;
hujan();
}
TeksStatis(" CATUR AYU ", 0, 0);
TeksStatis(" CAD :) ", 0, 1);
// buzzer();
n(25); n(26); n(27); n(28); n(29);
for (int i = 120; i > 80; i -= 10) {
delayms = i;
jalan(kedip);
}
for (int i = 100; i > 30; i -= 10) {
delayms = i;
meluap();
}
// buzzer();
for (int i = 500; i > 10; i -= 2) {
delayms = 20;
randomCube();
}
// buzzer();
for (int i = 100; i > 60; i -= 10) {
delayms = i;
berputarPutar();
}
// buzzer();
for (int i = 100; i > 50; i -= 10) {
delayms = i;
geserGeser();
}
// buzzer();
for (int i = 30; i > 20; i -= 10) {
delayms = i;
muterMuter(i);
}
// buzzer();
for (int i = 50; i > 10; i -= 10) {
delayms = i;
mekarMekar();
}
// buzzer();
for (int i = 100; i > 10; i -= 10) {
delayms = i;
blinks();
}
// buzzer();
lcd.clear();
tampilcube = true;
}
void tampilCube(int jam) {
// allOff();
for (int i = 29; i >= 26 ; i--) {
n(i);
n(i - 1);
delay(80);
f(i);
f(i - 1);
}
delay(80);
if (jam > 12) jam -= 12;
switch (jam) {
case 1: {
satu();
break;
}
case 2: {
dua();
break;
}
case 3: {
tiga();
break;
}
case 4: {
empat();
break;
}
case 5: {
lima();
break;
}
case 6: {
enam();
break;
}
case 7: {
tujuh();
break;
}
case 8: {
delapan();
break;
}
case 9: {
sembilan();
break;
}
case 10: {
sepuluh();
break;
}
case 11: {
sebelas();
break;
}
case 12: {
duabelas();
break;
}
}
for (int i = 25; i <= 29; i++) {
n(i);
n(i - 1);
delay(80);
if (i < 29) {
f(i);
f(i - 1);
}
f(28);
}
}
void satu() {
f(0); n(5); f(10); f(15); f(20);
f(1); n(6); f(11); f(16); f(21);
f(2); n(7); f(12); f(17); f(22);
f(3); n(8); f(13); f(18); f(23);
f(4); n(9); f(14); f(19); f(24);
}
void dua() {
f(0); n(5); n(10); n(15); f(20);
f(1); f(6); f(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); n(8); f(13); f(18); f(23);
f(4); n(9); n(14); n(19); f(24);
}
void tiga() {
f(0); n(5); n(10); n(15); f(20);
f(1); f(6); f(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); f(8); f(13); n(18); f(23);
f(4); n(9); n(14); n(19); f(24);
}
void empat() {
f(0); n(5); f(10); n(15); f(20);
f(1); n(6); f(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); f(8); f(13); n(18); f(23);
f(4); f(9); f(14); n(19); f(24);
}
void lima() {
f(0); n(5); n(10); n(15); f(20);
f(1); n(6); f(11); f(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); f(8); f(13); n(18); f(23);
f(4); n(9); n(14); n(19); f(24);
}
void enam() {
f(0); n(5); n(10); n(15); f(20);
f(1); n(6); f(11); f(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); n(8); f(13); n(18); f(23);
f(4); n(9); n(14); n(19); f(24);
}
void tujuh() {
f(0); n(5); n(10); n(15); f(20);
f(1); f(6); f(11); n(16); f(21);
f(2); f(7); f(12); n(17); f(22);
f(3); f(8); f(13); n(18); f(23);
f(4); f(9); f(14); n(19); f(24);
}
void delapan() {
f(0); n(5); n(10); n(15); f(20);
f(1); n(6); f(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); n(8); f(13); n(18); f(23);
f(4); n(9); n(14); n(19); f(24);
}
void sembilan() {
f(0); n(5); n(10); n(15); f(20);
f(1); n(6); f(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); f(8); f(13); n(18); f(23);
f(4); n(9); n(14); n(19); f(24);
}
void sepuluh() {
n(0); f(5); n(10); n(15); n(20);
n(1); f(6); n(11); f(16); n(21);
n(2); f(7); n(12); f(17); n(22);
n(3); f(8); n(13); f(18); n(23);
n(4); f(9); n(14); n(19); n(24);
}
void sebelas() {
n(0); f(5); n(10); f(15); f(20);
n(1); f(6); n(11); f(16); f(21);
n(2); f(7); n(12); f(17); f(22);
n(3); f(8); n(13); f(18); f(23);
n(4); f(9); n(14); f(19); f(24);
}
void duabelas() {
n(0); f(5); n(10); n(15); n(20);
n(1); f(6); f(11); f(16); n(21);
n(2); f(7); n(12); n(17); n(22);
n(3); f(8); n(13); f(18); f(23);
n(4); f(9); n(14); n(19); n(24);
}
void brandCube() {
delayms = 200;
blinks();
blinks();
delay(50);
f(0); f(5); n(10); f(15); f(20);
f(1); n(6); n(11); n(16); f(21);
n(2); n(7); n(12); n(17); n(22);
f(3); n(8); n(13); n(18); f(23);
f(4); f(9); n(14); f(19); f(24);
// n(25); f(26); f(27); f(28); f(29);
int count = 29;
for (int i = 25; i <= count; i++) {
n(i);
delay(50);
f(i);
if (count == i) {
n(i);
delay(200);
count -= 1;
i = 24;
if (count == 25) {
n(25);
delay(200);
break;
}
}
}
for (int i = 29; i >= 25; i--) {
f(i);
delay(50);
}
allOff();
n(0); n(5); f(10); n(15); n(20);
n(1); f(6); f(11); f(16); n(21);
f(2); f(7); f(12); f(17); f(22);
n(3); f(8); f(13); f(18); n(23);
n(4); n(9); f(14); n(19); n(24);
for (int i = 25; i < 30; i++) {
n(i);
delay(50);
}
delay(100);
delayms = 30;
meluap();
allOff();
}
void meluap() {
allOff();
f(0); f(5); f(10); f(15); f(20);
f(1); n(6); n(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); n(8); n(13); n(18); f(23);
f(4); f(9); f(14); f(19); f(24);
n(25); f(26); f(27); f(28); f(29);
delay(delayms);
n(25); n(26); f(27); f(28); f(29);
delay(delayms);
f(25); n(26); n(27); f(28); f(29);
delay(delayms);
f(25); f(26); n(27); n(28); f(29);
delay(delayms);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
n(0); n(5); n(10); n(15); n(20);
n(1); n(6); n(11); n(16); n(21);
n(2); n(7); f(12); n(17); n(22);
n(3); n(8); n(13); n(18); n(23);
n(4); n(9); n(14); n(19); n(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
f(25); f(26); n(27); n(28); f(29);
delay(delayms);
f(25); n(26); n(27); f(28); f(29);
delay(delayms);
n(25); n(26); f(27); f(28); f(29);
delay(delayms);
n(25); f(26); f(27); f(28); f(29);
delay(delayms);
}
void randomCube() {
int kolom;
int layer;
kolom = random(30);
// layer = random(5) + 25;
n(kolom);
// n(layer);
delay(delayms);
kolom = random(30);
// layer = random(5) + 25;
f(kolom);
// f(layer);
delay(delayms);
}
void hujan() {
int a, b, c, d, e;
a = random(25); b = random(25); c = random(25); d = random(25); e = random(25);
n(a); n(b); n(c); n(d); n(e);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
a = random(25); b = random(25); c = random(25); d = random(25); e = random(25);
f(a); f(b); f(c); f(d); f(e);
f(25); f(26); n(27); n(28); f(29);
delay(delayms - 10);
a = random(25); b = random(25); c = random(25); d = random(25); e = random(25);
n(a); n(b); n(c); n(d); n(e);
f(25); n(26); n(27); f(28); f(29);
delay(delayms - 20);
a = random(25); b = random(25); c = random(25); d = random(25); e = random(25);
f(a); f(b); f(c); f(d); f(e);
n(25); n(26); f(27); f(28); f(29);
delay(delayms - 30);
a = random(25); b = random(25); c = random(25); d = random(25); e = random(25);
n(a); n(b); n(c); n(d); n(e);
n(25); f(26); f(27); f(28); f(29);
delay(delayms - 40);
}
void ulangTahun() {
HBD();
delay(100);
CAYU();
delay(100);
DES16();
delay(100);
}
void DES16() {
//1
n(0); f(5); n(10); n(15); n(20);
n(1); f(6); n(11); f(16); f(21);
n(2); f(7); n(12); n(17); n(22);
n(3); f(8); n(13); f(18); n(23);
n(4); f(9); n(14); n(19); n(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
// //6
// f(0); n(5); n(10); n(15); f(20);
// f(1); n(6); f(11); f(16); f(21);
// f(2); n(7); n(12); n(17); f(22);
// f(3); n(8); f(13); n(18); f(23);
// f(4); n(9); n(14); n(19); f(24);
// f(25); f(26); f(27); n(28); n(29);
// delay(delayms);
// allOff();
// delay(delayms/3);
//D
f(0); f(5); f(10); n(15); f(20);
f(1); f(6); f(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); n(8); f(13); n(18); f(23);
f(4); n(9); n(14); n(19); f(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
//E
f(0); n(5); n(10); n(15); f(20);
f(1); n(6); f(11); f(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); n(8); f(13); f(18); f(23);
f(4); n(9); n(14); n(19); f(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
//S
f(0); n(5); n(10); n(15); f(20);
f(1); n(6); f(11); f(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); f(8); f(13); n(18); f(23);
f(4); n(9); n(14); n(19); f(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
}
void CAYU() {
//C
f(0); f(5); f(10); f(15); f(20);
f(1); n(6); n(11); n(16); f(21);
f(2); n(7); f(12); f(17); f(22);
f(3); n(8); f(13); f(18); f(23);
f(4); n(9); n(14); n(19); f(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
//A
f(0); n(5); n(10); n(15); f(20);
f(1); n(6); f(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); n(8); f(13); n(18); f(23);
f(4); n(9); f(14); n(19); f(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
//y
f(0); n(5); f(10); n(15); f(20);
f(1); n(6); f(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); f(8); n(13); f(18); f(23);
f(4); f(9); n(14); f(19); f(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
//u
f(0); f(5); f(10); f(15); f(20);
f(1); n(6); f(11); n(16); f(21);
f(2); n(7); f(12); n(17); f(22);
f(3); n(8); f(13); n(18); f(23);
f(4); n(9); n(14); n(19); f(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
}
void HBD() {
//H
f(0); n(5); f(10); n(15); f(20);
f(1); n(6); f(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); n(8); f(13); n(18); f(23);
f(4); n(9); f(14); n(19); f(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
//B
f(0); n(5); f(10); f(15); f(20);
f(1); n(6); f(11); f(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); n(8); f(13); n(18); f(23);
f(4); n(9); n(14); n(19); f(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
//D
f(0); f(5); f(10); n(15); f(20);
f(1); f(6); f(11); n(16); f(21);
f(2); n(7); n(12); n(17); f(22);
f(3); n(8); f(13); n(18); f(23);
f(4); n(9); n(14); n(19); f(24);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
allOff();
delay(delayms / 3);
}
void keBawah() {
f(25); f(26); f(27); f(28); n(29);
delay(delayms);
f(25); f(26); f(27); n(28); n(29);
delay(delayms);
f(25); f(26); n(27); n(28); n(29);
delay(delayms);
f(25); n(26); n(27); n(28); n(29);
delay(delayms);
n(25); n(26); n(27); n(28); n(29);
delay(delayms);
}
void layerAll() {
n(25); n(26); n(27); n(28); n(29);
}
void geserBawah() {
f(25); f(26); f(27); f(28); n(29);
delay(delayms);
f(25); f(26); f(27); n(28); f(29);
delay(delayms);
f(25); f(26); n(27); f(28); f(29);
delay(delayms);
f(25); n(26); f(27); f(28); f(29);
delay(delayms);
n(25); f(26); f(27); f(28); f(29);
delay(delayms);
}
void berputarPutar() {
n(25); n(26); n(27); n(28); n(29);
berputar();
f(25); n(26); n(27); n(28); f(29);
berputar();
f(25); f(26); n(27); f(28); f(29);
berputar();
f(25); n(26); n(27); n(28); f(29);
berputar();
n(25); n(26); n(27); n(28); n(29);
berputar();
n(25); n(26); f(27); n(28); n(29);
berputar();
n(25); f(26); f(27); f(28); n(29);
berputar();
n(25); n(26); f(27); n(28); n(29);
berputar();
}
void berputar() {
n(12);
n(2); n(7); n(17); n(22);
delay(delayms);
f(2); f(7); f(17); f(22);
n(4); n(8); n(16); n(20);
delay(delayms);
f(4); f(8); f(16); f(20);
n(10); n(11); n(13); n(14);
delay(delayms);
f(10); f(11); f(13); f(14);
n(0); n(6); n(18); n(24);
delay(delayms);
f(0); f(6); f(18); f(24);
allOff();
}
void mekarMekar() {
mekar();
nutup();
}
void mekar() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
regWrite(12, HIGH);
delay(delayms * 2);
for (int i = 6; i < 16; i += 5) {
regWrite(i, HIGH);
}
for (int i = 16; i < 18; i++) {
regWrite(i, HIGH);
}
for (int i = 18; i >= 8; i -= 5) {
regWrite(i, HIGH);
}
for (int i = 7; i >= 6; i--) {
regWrite(i, HIGH);
}
delay(delayms * 2);
for (int i = 0; i < 20; i += 5) {
regWrite(i, HIGH);
}
for (int i = 20; i < TINGGI; i++) {
regWrite(i, HIGH);
}
for (int i = 24; i >= 4; i -= 5) {
regWrite(i, HIGH);
}
for (int i = 4; i >= 0; i--) {
regWrite(i, HIGH);
}
delay(delayms * 2);
}
void nutup() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
for (int i = 0; i < 20; i += 5) {
regWrite(i, LOW);
}
for (int i = 20; i < TINGGI; i++) {
regWrite(i, LOW);
}
for (int i = 24; i >= 4; i -= 5) {
regWrite(i, LOW);
}
for (int i = 4; i >= 0; i--) {
regWrite(i, LOW);
}
delay(delayms * 2);
for (int i = 6; i < 16; i += 5) {
regWrite(i, LOW);
}
for (int i = 16; i < 18; i++) {
regWrite(i, LOW);
}
for (int i = 18; i >= 8; i -= 5) {
regWrite(i, LOW);
}
for (int i = 7; i >= 6; i--) {
regWrite(i, LOW);
}
delay(delayms * 2);
regWrite(12, LOW);
delay(delayms * 2);
}
void muterMuter(int j) {
for (int layer = TINGGI; layer < MAX; layer++) {
for (int k = TINGGI; k < MAX; k++) {
if (k == layer) {
regWrite(k, HIGH);
}
else {
regWrite(k, LOW);
}
}
for (int i = 0; i < 20; i += 5) {
regWrite(i, HIGH);
delay(j);
regWrite(i, LOW);
}
for (int i = 20; i < TINGGI; i++) {
regWrite(i, HIGH);
delay(j);
regWrite(i, LOW);
}
for (int i = 24; i >= 4; i -= 5) {
regWrite(i, HIGH);
delay(j);
regWrite(i, LOW);
}
for (int i = 4; i >= 0; i--) {
regWrite(i, HIGH);
delay(j);
regWrite(i, LOW);
}
j -= 2;
}
for (int layer = MAX - 1; layer >= TINGGI; layer--) {
for (int k = TINGGI; k < MAX; k++) {
if (k == layer) {
regWrite(k, HIGH);
}
else {
regWrite(k, LOW);
}
}
for (int i = 6; i < 16; i += 5) {
regWrite(i, HIGH);
delay(j);
regWrite(i, LOW);
}
for (int i = 16; i < 18; i++) {
regWrite(i, HIGH);
delay(j);
regWrite(i, LOW);
}
for (int i = 18; i >= 8; i -= 5) {
regWrite(i, HIGH);
delay(j);
regWrite(i, LOW);
}
for (int i = 7; i >= 6; i--) {
regWrite(i, HIGH);
delay(j);
regWrite(i, LOW);
}
j -= 2;
}
for (int layer = TINGGI; layer < MAX; layer++) {
regWrite(12, HIGH);
regWrite(layer, HIGH);
delay(j);
j -= 2;
}
regWrite(12, LOW);
delay(100);
}
//void buzzer() {
// digitalWrite(buzzer, HIGH);
// delay(100);
// digitalWrite(buzzer, LOW);
// delay(100);
//}
void blinks() {
allOn();
delay(delayms);
allOff();
delay(delayms);
}
void allOn() {
for (int i = 0; i < MAX; i++) {
regWrite(i, HIGH);
}
}
void allOff() {
for (int i = 0; i < MAX; i++) {
regWrite(i, LOW);
}
}
void geserGeser() {
barisJalanKanan();
kolomMaju();
barisJalanKiri();
kolomMundur();
allOff();
}
void kolomMaju() {
kolom5();
delay(delayms);
kolom4();
delay(delayms);
kolom3();
delay(delayms);
kolom2();
delay(delayms);
kolom1();
delay(delayms);
}
void kolomMundur() {
kolom1();
delay(delayms);
kolom2();
delay(delayms);
kolom3();
delay(delayms);
kolom4();
delay(delayms);
kolom5();
delay(delayms);
}
void kolom1() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
int j = 0;
for (int i = 0; i < 25; i++) {
if (i == j) {
regWrite(i, HIGH);
j += 5;
}
else {
regWrite(i, LOW);
}
}
}
void kolom2() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
int j = 1;
for (int i = 0; i < 25; i++) {
if (i == j) {
regWrite(i, HIGH);
j += 5;
}
else {
regWrite(i, LOW);
}
}
}
void kolom3() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
int j = 2;
for (int i = 0; i < 25; i++) {
if (i == j) {
regWrite(i, HIGH);
j += 5;
}
else {
regWrite(i, LOW);
}
}
}
void kolom4() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
int j = 3;
for (int i = 0; i < 25; i++) {
if (i == j) {
regWrite(i, HIGH);
j += 5;
}
else {
regWrite(i, LOW);
}
}
}
void kolom5() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
int j = 4;
for (int i = 0; i < 25; i++) {
if (i == j) {
regWrite(i, HIGH);
j += 5;
}
else {
regWrite(i, LOW);
}
}
}
void barisJalanKanan() {
baris1();
delay(delayms);
baris2();
delay(delayms);
baris3();
delay(delayms);
baris4();
delay(delayms);
baris5();
delay(delayms);
}
void barisJalanKiri() {
baris5();
delay(delayms);
baris4();
delay(delayms);
baris3();
delay(delayms);
baris2();
delay(delayms);
baris1();
delay(delayms);
}
void baris1() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
for (int i = 0; i < 5; i++) {
regWrite(i, HIGH);
}
for (int i = 5; i < TINGGI; i++) {
regWrite(i, LOW);
}
}
void baris2() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
for (int i = 5; i < 10; i++) {
regWrite(i, HIGH);
}
for (int i = 10; i < TINGGI; i++) {
regWrite(i, LOW);
}
for (int i = 0; i < 5; i++) {
regWrite(i, LOW);
}
}
void baris3() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
for (int i = 10; i < 15; i++) {
regWrite(i, HIGH);
}
for (int i = 15; i < TINGGI; i++) {
regWrite(i, LOW);
}
for (int i = 0; i < 10; i++) {
regWrite(i, LOW);
}
}
void baris4() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
for (int i = 15; i < 20; i++) {
regWrite(i, HIGH);
}
for (int i = 20; i < TINGGI; i++) {
regWrite(i, LOW);
}
for (int i = 0; i < 15; i++) {
regWrite(i, LOW);
}
}
void baris5() {
for (int i = TINGGI; i < MAX; i++) {
regWrite(i, HIGH);
}
for (int i = 20; i < 25; i++) {
regWrite(i, HIGH);
}
// for (int i = 10; i < TINGGI; i++) {
// regWrite(i, LOW);
// }
for (int i = 0; i < 20; i++) {
regWrite(i, LOW);
}
}
void n(int pin) {
regWrite(pin, HIGH);
}
void f(int pin) {
regWrite(pin, LOW);
}
void regWrite(int pin, bool state) {
//Determines register
int reg = pin / 8;
//Determines pin for actual register
int actualPin = pin - (8 * reg);
//Begin session
digitalWrite(latchPin, LOW);
for (int i = 0; i < numOfRegisters; i++) {
//Get actual states for register
byte* states = ®isterState[i];
//Update state
if (i == reg) {
bitWrite(*states, actualPin, state);
}
//Write
shiftOut(dataPin, clockPin, MSBFIRST, *states);
}
//End session
digitalWrite(latchPin, HIGH);
}
<file_sep>/* Just a little test message. Go to http://192.168.4.1 in a web browser
connected to this access point to see it.
*/
void mainkan() {
TampilJam();
TampilTanggal();
TampilSuhu();
AlarmSholat();
if (millis() - clkTime > 15000) { //Every 15 seconds, tampilkan tanggal bergerak
AlarmSholat();
}
if (millis() - clkTime > 18000) { //Every 15 seconds, tampilkan tanggal bergerak
delay(3000);
AlarmSholat();
TampilJadwalSholat();
AlarmSholat();
clkTime = millis();
}
}
void JadwalSholat() {
RtcDateTime now = Rtc.GetDateTime();
int tahun = now.Year();
int bulan = now.Month();
int tanggal = now.Day();
int dst = 7; // TimeZone
set_calc_method(ISNA);
set_asr_method(Shafii);
set_high_lats_adjust_method(AngleBased);
set_fajr_angle(20);
set_isha_angle(18);
//SETTING LOKASI DAN WAKTU Masjid Miftahul Jannah
float latitude = -7.762552;
float longitude = 110.376463;
get_prayer_times(tahun, bulan, tanggal, latitude, longitude, dst, times);
}
void TampilJadwalSholat() {
JadwalSholat();
lcd.clear();
char sholat[7];
char jam[50];
//char TimeName[][16] = {" SUBUH"," TERBIT"," DZUHUR"," ASHAR"," TENGGELAM"," MAGRIB"," ISYA'","WA"};
char TimeName[][8] = {"SUBUH ", "TERBIT", "DZUHUR", "ASHAR ", "TE", "MAGRIB", "ISYA' ", "WA"};
int hours, minutes;
for (int i = 0; i < 8; i++) {
get_float_time_parts(times[i], hours, minutes);
ihti = 2;
minutes = minutes + ihti;
if (minutes >= 60) {
minutes = minutes - 60;
hours ++;
}
else {
;
}
if (i == 0 || i == 2 || i == 3 || i == 5 || i == 6) { //Tampilkan hanya Subuh, Dzuhur, Ashar, Maghrib, Isya
//sprintf(sholat,"%s",TimeName[i]);
TampilJam2();
TampilTanggal();
sprintf(jam, "%s %02d:%02d", TimeName[i], hours, minutes);
Serial.println(jam);
sprintf(jam, "%s", TimeName[i]);
TeksStatis(jam, 0, 0);
sprintf(jam, "%02d:%02d", hours, minutes);
TeksStatis(jam, 0, 1);
delay(2000);
lcd.clear();
}
}
//Tambahan Waktu Tanbih (Peringatan 10 menit sebelum mulai puasa) yang biasa disebut Imsak
get_float_time_parts(times[0], hours, minutes);
minutes = minutes + ihti;
if (minutes < 11) {
minutes = 60 - minutes;
hours --;
} else {
minutes = minutes - 10 ;
}
TampilJam2();
TampilTanggal();
// sprintf(jam, "TANBIH %02d:%02d", hours, minutes);
// TeksStatis(jam, 0, 1);
sprintf(jam, "TANBIH");
TeksStatis(jam, 0, 0);
sprintf(jam, "%02d:%02d", hours, minutes);
TeksStatis(jam, 0, 1);
delay(2000);
lcd.clear();
}
void AlarmSholat() {
RtcDateTime now = Rtc.GetDateTime();
int Hari = now.DayOfWeek();
int Hor = now.Hour();
int Min = now.Minute();
int Sec = now.Second();
JadwalSholat();
int hours, minutes;
char jam[50];
// Tanbih Imsak
get_float_time_parts(times[0], hours, minutes);
minutes = minutes + ihti;
if (minutes < 11) {
minutes = 60 - minutes;
hours --;
} else {
minutes = minutes - 10 ;
}
if (Hor == hours && Min == minutes) {
TeksStatis(" TANBIH ", 0, 0);
sprintf(jam, " %02d:%02d ", hours, minutes);
TeksStatis(jam, 0, 1);
BuzzerPendek();
delayms = 100;
for (int i = 0; i < 5; i++) blinks();
Serial.println("TANBIH");
delay(60000);
}
// Subuh
get_float_time_parts(times[0], hours, minutes);
minutes = minutes + ihti;
if (minutes >= 60) {
minutes = minutes - 60;
hours ++;
}
if (Hor == hours && Min == minutes) {
TeksStatis(" SUBUH ", 0, 0);
sprintf(jam, " %02d:%02d ", hours, minutes);
TeksStatis(jam, 0, 1);
BuzzerPanjang();
Serial.println("SUBUH");
delayms = 100;
for (int i = 0; i < 5; i++) blinks();
delay(180000);//180 detik atau 3 menit untuk adzan
BuzzerPendek();
value_iqmh = 10;
Iqomah();
}
// Dzuhur
get_float_time_parts(times[2], hours, minutes);
minutes = minutes + ihti;
if (minutes >= 60) {
minutes = minutes - 60;
hours ++;
}
if (Hor == hours && Min == minutes && Hari != 5) {
TeksStatis(" DZUHUR ", 0, 0);
sprintf(jam, " %02d:%02d ", hours, minutes);
TeksStatis(jam, 0, 1);
BuzzerPanjang();
Serial.println("DZUHUR");
delayms = 100;
for (int i = 0; i < 5; i++) blinks();
delay(180000);//180 detik atau 3 menit untuk adzan
BuzzerPendek();
value_iqmh = 3;
Iqomah();
} else if (Hor == hours && Min == minutes && Hari == 5) {
TeksStatis(" JUM'AT ", 0, 0);
sprintf(jam, " %02d:%02d ", hours, minutes);
TeksStatis(jam, 0, 1);
BuzzerPanjang();
Serial.println("JUM'AT");
delayms = 100;
for (int i = 0; i < 5; i++) blinks();
delay(180000);//180 detik atau 3 menit untuk adzan
}
// Ashar
get_float_time_parts(times[3], hours, minutes);
minutes = minutes + ihti;
if (minutes >= 60) {
minutes = minutes - 60;
hours ++;
}
if (Hor == hours && Min == minutes) {
TeksStatis(" ASHAR ", 0, 0);
sprintf(jam, " %02d:%02d ", hours, minutes);
TeksStatis(jam, 0, 1);
BuzzerPanjang();
Serial.println("ASHAR");
delayms = 100;
for (int i = 0; i < 5; i++) blinks();
delay(180000);//180 detik atau 3 menit untuk adzan
BuzzerPendek();
value_iqmh = 3;
Iqomah();
}
// Maghrib
get_float_time_parts(times[5], hours, minutes);
minutes = minutes + ihti;
if (minutes >= 60) {
minutes = minutes - 60;
hours ++;
}
if (Hor == hours && Min == minutes) {
TeksStatis(" MAGHRIB ", 0, 0);
sprintf(jam, " %02d:%02d ", hours, minutes);
TeksStatis(jam, 0, 1);
BuzzerPanjang();
Serial.println("MAGHRIB");
delayms = 100;
for (int i = 0; i < 5; i++) blinks();
delay(180000);//180 detik atau 3 menit untuk adzan
BuzzerPendek();
value_iqmh = 2;
Iqomah();
}
// Isya'
get_float_time_parts(times[6], hours, minutes);
minutes = minutes + ihti;
if (minutes >= 60) {
minutes = minutes - 60;
hours ++;
}
if (Hor == hours && Min == minutes) {
TeksStatis(" ISYA ", 0, 0);
sprintf(jam, " %02d:%02d ", hours, minutes);
TeksStatis(jam, 0, 1);
BuzzerPanjang();
Serial.println("ISYA");
delayms = 100;
for (int i = 0; i < 5; i++) blinks();
delay(180000);//180 detik atau 3 menit untuk adzan
BuzzerPendek();
value_iqmh = 2;
Iqomah();
}
}
//--------------------------------------------------
//IQOMAH
void Iqomah() {
RtcDateTime now = Rtc.GetDateTime();
//iqomah----------------------------------
char iqomah[8];
int tampil;
int detik = 0, menit = value_iqmh;
for (detik = 0; detik >= 0; detik--) {
delay(1000);
sprintf(iqomah, " IQOMAH ");
TeksStatis(iqomah, 0, 0);
sprintf(iqomah, " %02d:%02d ", menit, detik);
TeksStatis(iqomah, 0, 1);
if (detik <= 0) {
detik = 60;
menit = menit - 1;
} if (menit <= 0 && detik <= 1) {
BuzzerPendek();
delayms = 100;
for (int i = 0; i < 10; i++) blinks();
lcd.clear();
TeksStatis(" SHOLAT ", 0, 0);
delay(10000);
for (tampil = 0; tampil < 300 ; tampil++) { //< tampil selama 300 detik waktu saat sholat
menit = 0;
detik = 0;
///////////////////////
//now = rtc.now();
TeksStatis(" SHOLAT ", 0, 0);
sprintf(iqomah, " %02d:%02d ", now.Hour(), now.Minute());
TeksStatis(iqomah, 0, 1);
/////////////////////
delay (1000);
}
}
}
lcd.clear();
}
//=============================================================================================
void buildJavascript() {
//=============================================================================================
javaScript = "<SCRIPT>\n";
javaScript += "var xmlHttp=createXmlHttpObject();\n";
javaScript += "function createXmlHttpObject(){\n";
javaScript += " if(window.XMLHttpRequest){\n";
javaScript += " xmlHttp=new XMLHttpRequest();\n";
javaScript += " }else{\n";
javaScript += " xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');\n"; // code for IE6, IE5
javaScript += " }\n";
javaScript += " return xmlHttp;\n";
javaScript += "}\n";
javaScript += "function process(){\n";
javaScript += " if(xmlHttp.readyState==0 || xmlHttp.readyState==4){\n";
javaScript += " xmlHttp.open('PUT','xml',true);\n";
javaScript += " xmlHttp.onreadystatechange=handleServerResponse;\n";
javaScript += " xmlHttp.send(null);\n";
javaScript += " }\n";
javaScript += " setTimeout('process()',1000);\n";
javaScript += "}\n";
javaScript += "function handleServerResponse(){\n";
javaScript += " if(xmlHttp.readyState==4 && xmlHttp.status==200){\n";
javaScript += " xmlResponse=xmlHttp.responseXML;\n";
javaScript += " xmldoc = xmlResponse.getElementsByTagName('rYear');\n";
javaScript += " message = xmldoc[0].firstChild.nodeValue;\n";
javaScript += " document.getElementById('year').innerHTML=message;\n";
javaScript += " xmldoc = xmlResponse.getElementsByTagName('rMonth');\n";
javaScript += " message = xmldoc[0].firstChild.nodeValue;\n";
javaScript += " document.getElementById('month').innerHTML=message;\n";
javaScript += " xmldoc = xmlResponse.getElementsByTagName('rDay');\n";
javaScript += " message = xmldoc[0].firstChild.nodeValue;\n";
javaScript += " document.getElementById('day').innerHTML=message;\n";
javaScript += " xmldoc = xmlResponse.getElementsByTagName('rHour');\n";
javaScript += " message = xmldoc[0].firstChild.nodeValue;\n";
javaScript += " document.getElementById('hour').innerHTML=message;\n";
javaScript += " xmldoc = xmlResponse.getElementsByTagName('rMinute');\n";
javaScript += " message = xmldoc[0].firstChild.nodeValue;\n";
javaScript += " document.getElementById('minute').innerHTML=message;\n";
javaScript += " xmldoc = xmlResponse.getElementsByTagName('rSecond');\n";
javaScript += " message = xmldoc[0].firstChild.nodeValue;\n";
javaScript += " document.getElementById('second').innerHTML=message;\n";
javaScript += " xmldoc = xmlResponse.getElementsByTagName('rTemp');\n";
javaScript += " message = xmldoc[0].firstChild.nodeValue;\n";
javaScript += " document.getElementById('temp').innerHTML=message;\n";
javaScript += " }\n";
javaScript += "}\n";
javaScript += "</SCRIPT>\n";
}
//=============================================================================================
void buildXML() {
//=============================================================================================
RtcDateTime now = Rtc.GetDateTime();
RtcTemperature temp = Rtc.GetTemperature();
XML = "<?xml version='1.0'?>";
XML += "<t>";
XML += "<rYear>";
XML += now.Year();
XML += "</rYear>";
XML += "<rMonth>";
XML += now.Month();
XML += "</rMonth>";
XML += "<rDay>";
XML += now.Day();
XML += "</rDay>";
XML += "<rHour>";
if (now.Hour() < 10) {
XML += "0";
XML += now.Hour();
} else {
XML += now.Hour();
}
XML += "</rHour>";
XML += "<rMinute>";
if (now.Minute() < 10) {
XML += "0";
XML += now.Minute();
} else {
XML += now.Minute();
}
XML += "</rMinute>";
XML += "<rSecond>";
if (now.Second() < 10) {
XML += "0";
XML += now.Second();
} else {
XML += now.Second();
}
XML += "</rSecond>";
XML += "</rTemp>";
XML += temp.AsFloatDegC();
XML += "</rTemp>";
XML += "</t>";
}
//=============================================================================================
void handleRoot() {
//=============================================================================================
buildJavascript();
IPAddress ip = WiFi.localIP();
String ipStr = (String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]));
message = "<!DOCTYPE HTML>";
message += "<html>";
message += "<head>";
message += javaScript;
message += "<title>JWS Grobak.Net</title>";
message += "<style> body { font-family: Arial, Helvetica, Sans-Serif; color: green; }";
message += "h1 {text-align:center;}";
message += "h5 {text-align:center;}";
message += "a {text-decoration:none; color:#fff; background:green; padding:10px; border-radius:15px; }";
message += "p {text-align:center;}";
message += "table.center { width:80%; margin-left:10%; margin-right:10%;}";
message += "</style>";
message += " </head>";
message += " <body onload='process()'>";
message += "<table class='center'>";
message += " <tr>";
message += " <th>";
message += "<h1>JWS Grobak.Net</h1>";
message += " </th> ";
message += " </tr>";
message += " <tr>";
message += " <td align='center'>";
message += " </td>";
message += " </tr>";
message += " <tr>";
message += " <td align='center'>";
message += "<span id='year'></span>/<span id='month'></span>/<span id='day'></span> <span id='hour'></span>:<span id='minute'></span>:<span id='second'></span><BR>";
message += " </td>";
message += " </tr>";
message += " <tr>";
message += " <td align='center'>";
message += "Temp =<span id='temp'></span>C<BR>";
message += " </td>";
message += " </tr>";
message += " <tr>";
message += " <td>";
message += "<h5><a href='/setTime'>Ubah Tanggal dan Jam</a></h5>";
message += " </td>";
message += " </tr>";
message += " <tr>";
message += " <td align='center'>";
message += "<BR>IP ";
message += ipStr;
message += " </td>";
message += " </tr>";
message += "</table>";
message += "<BR>";
message += "";
message += "</body></html>";
server.send ( 404 , "text/html", message );
}
//=============================================================================================
void setTime() {
//=============================================================================================
buildJavascript();
message = "<!DOCTYPE HTML>";
message += "<html>";
message += "<head>";
message += javaScript;
message += "<title>JWS Grobak.Net</title>";
message += "<style> body { font-family: Arial, Helvetica, Sans-Serif; color: green; }";
message += "h1 {text-align:center;}";
message += "h5 {text-align:center;}";
message += "a {text-decoration:none; color:#fff; background:green; padding:10px; border-radius:15px; }";
message += "p {text-align:center;}";
message += "table.center { width:80%; margin-left:10%; margin-right:10%;}";
message += "</style>";
message += " </head>";
message += " <body onload='process()'>";/////////////////////////////////////////
message += "";
message += "<table class='center'>";
message += " <tr>";
message += " <th>";
message += "<h1>Ubah Tanggal dan Jam</h1>";
message += " </th> ";
message += " </tr>";
message += " <tr>";
message += " <td align='center'>";
message += "Tanggal Sekarang ";
message += " <BR> </td>";
message += " </tr>";
message += " <tr>";
message += " <td align='center'>";
message += "<span id='year'></span>/<span id='month'></span>/<span id='day'></span><BR>";
message += " </td>";
message += " </tr>";
message += " <tr>";
message += " <td align='center'>";
message += "<form >";
message += "Format tanggal 2017-03-20<br><br>";
message += "<input type='date' name='date' min='2017-03-20' style='height:75px; width:200px'><br><br>";
message += "<input type='submit' value='Ubah Tanggal' style='height:75px; width:200px'> ";
message += "</form>";
message += " </td>";
message += " </tr>";
message += " <tr>";
message += " <td align='center'>";
message += "Jam Tersimpan<BR><span id='hour'></span>:<span id='minute'></span>:<span id='second'></span><BR><BR>";
message += " </td>";
message += " </tr>";
message += " <tr>";
message += " <td align='center'>";
message += "<form >";
message += "Tentukan Jam<br>";
message += "<input type='TIME' name='time' style='height:75px; width:200px'><br><br>";
message += "<input type='submit' value='Ubah Jam' style='height:75px; width:200px'> ";
message += "</form>";
message += " </td>";
message += " </tr>";
message += " <tr>";
message += " <td>";
message += "<h5><a href='/'>Kembali</a></h5>";
message += " </td>";
message += " </tr>";
message += "</table>";
message += "";
message += "</body></html>";
server.send ( 404 , "text/html", message );
// Tanggal--------------------------------------------------------------------
if (server.hasArg("date")) {
uint16_t ano;
uint8_t mes;
uint8_t dia;
Serial.print("ARGdate");
Serial.println(server.arg("date"));
String sd = server.arg("date");
String lastSd;
ano = ((sd[0] - '0') * 1000) + ((sd[1] - '0') * 100) + ((sd[2] - '0') * 10) + (sd[3] - '0');
mes = ((sd[5] - '0') * 10) + (sd[6] - '0');
dia = ((sd[8] - '0') * 10) + (sd[9] - '0');
if (sd != lastSd) {
RtcDateTime now = Rtc.GetDateTime();
uint8_t hour = now.Hour();
uint8_t minute = now.Minute();
Rtc.SetDateTime(RtcDateTime(ano, mes, dia, hour, minute, 0));
lastSd = sd;
}
// Serial.println(fa);
server.send ( 404 , "text", message );
}//if has date
// Jam ------------------------------------------------
if (server.hasArg("time")) {
Serial.println(server.arg("time"));
String st = server.arg("time");
String lastSt;
uint8_t hora = ((st[0] - '0') * 10) + (st[1] - '0');
uint8_t minuto = ((st[3] - '0') * 10) + (st[4] - '0');
if (st != lastSt) {
RtcDateTime now = Rtc.GetDateTime();
uint16_t year = now.Year();
uint8_t month = now.Month();
uint8_t day = now.Day();
Rtc.SetDateTime(RtcDateTime(year, month, day, hora, minuto, 0));
lastSt = st;
}
server.send ( 404 , "text", message );
}//if has time
}
//=============================================================================================
void handleXML() {
//=============================================================================================
buildXML();
server.send(200, "text/xml", XML);
}
//=============================================================================================
void handleNotFound() {
//=============================================================================================
String message = "<html><head>";
message += "<title>JWS Grobak.Net - Halaman tidak ditemukan</title>";
message += "<style> body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }";
message += "h1 {text-align:center;}";
message += "h5 {text-align:center;}";
message += "a {text-decoration:none; color:#fff; background:green; padding:10px; border-radius:15px; }";
message += "</style>";
message += " </head>";
message += " <body>";
message += "<table style='width:80%'>";
message += "<tr>";//baris 2
message += "<th>";//kolom judul
message += "<h1>Tidak ditemukan</h1>";
message += "</th>";
message += "<tr>";//baris 2
message += "<td>";//kolom isi
message += "<h5><a href='/'>Kembali</a></h5>";
message += "<td>";
message += "</tr>";
message += "</table>";
message += "</body></html>";
message += "";
server.send ( 404 , "text", message );
}
void initSSID()
{
Serial.println();
Serial.print("Configuring access point...");
/* You can remove the password parameter if you want the AP to be open. */
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.on ( "/", handleRoot );
server.on ( "/setTime", setTime );
server.on ( "/xml", handleXML) ;
server.onNotFound ( handleNotFound );
server.begin();
Serial.println("HTTP server started");
}
<file_sep>#include "PrayerTimes.h"
#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS3231.h>
#include <LiquidCrystal_I2C.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPUpdateServer.h>
#define countof(a) (sizeof(a) / sizeof(a[0]))
#define MAX 30
#define TINGGI 25
// Konstruk object LCD dengan alamat I2C
// Ganti 0x3F sesuai dengan alamat I2C modul kalian
// Jika tidak tahu dapat menggunakan LCD I2C Scanner
LiquidCrystal_I2C lcd(0x27, 16, 2);
RtcDS3231<TwoWire> Rtc(Wire);
// Ubah nama hari dan nama bulan
char weekDay[][3] = {"AH", "SN", "SL", "RB", "KM", "JM", "SB", "AH"};
char monthYear[][4] = { " ", "JAN", "FEB", "MAR", "APR", "MEI", "JUN", "JUL", "AGU", "SEP", "OKT", "NOV", "DES" };
// Inisiasi Jadwal Sholat
double times[sizeof(TimeName) / sizeof(char*)];
int ihti = 2; // Koreksi Waktu Menit Jadwal Sholat
int value_iqmh; // Waktu Iqomah 10 menit
// Set Wifi SSID dan Password
#ifndef APSSID
#define APSSID "AndroidAP"
#define APPSK "<PASSWORD>"
#endif
/* Set these to your desired credentials. */
const char *ssid = APSSID;
const char *password = APPSK;
char datestring[20];
String message, javaScript, XML;
ESP8266WebServer server(80);
ESP8266HTTPUpdateServer httpUpdater;
char data[] = "www.tokobaguskerenasik.com";
// BUZZER
uint8_t buzzer = 15;
uint8_t GPIO_Pin = 0;
int updCnt = 0;
long clkTime = 0;
bool fungsi = true;
int latchPin = 13;
int clockPin = 12;
int dataPin = 14;
//int buz = 15;
int numOfRegisters = 4;
byte* registerState;
int delayms = 100;
int jamsekarang = 0;
bool tampilcube = false;
void setup() {
Serial.begin(115200);
// // initSSID();
initCube();
Serial.print("compiled: ");
Serial.print(__DATE__);
Serial.println(__TIME__);
initRTC();
lcd.begin();
pinMode(buzzer, OUTPUT);
BuzzerPendek();
brandCube();
Branding();
lcd.clear();
TeksStatis(" HELLO ", 0, 0);
TeksStatis(" CAYU ", 0, 1);
helloCayu();
lcd.clear();
allOff();
pinMode(GPIO_Pin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(GPIO_Pin), IntCallback, FALLING);
}
void loop() {
// n(28);
// hbdcayu();
// cayuJalan();
//
if (fungsi) mainkan();
else {
BuzzerPanjang();
cube();
fungsi = true;
}
}
ICACHE_RAM_ATTR void IntCallback() {
fungsi = false;
// delay(100);
// delay(100);
// Serial.print("Stamp(ms): ");
// Serial.println(millis());
// BuzzerPanjang();
// delay(100);
}
| 28d70ac02b07c15c7930bf9bb74b782c98286c7f | [
"C++"
] | 4 | C++ | dayatsa/LED-CUBE1 | 4fe11a7d3f2ac59dd02522bff9859077e2a35eed | 9cc9a47122e4cc65023a64e14db892657a345774 |
refs/heads/master | <file_sep>library("shiny")
library("threejs")
library("RSQLite")
library("RColorBrewer")
shinyUI(
fluidPage(
# タイトル
titlePanel("Co-author Network Browser (coauthree)"),
# レイアウト設定
sidebarLayout(
absolutePanel(
id = "controls",
class = "panel panel-default",
fixed = FALSE,
top = 60,
left = "auto",
right = 40,
bottom = "auto",
width = 330,
height = "auto",
draggable = TRUE,
textInput(
"Keyword",
"Keyword (e.g., iPS cell)"
),
sliderInput(
"Y",
"Year published",
value=c(2000, 2016),
min = 1867,
max = 2016,
step = 1),
plotOutput("plot1", height=200),
sliderInput(
"B",
"Bar height",
value=100,
min = 1,
max = 500,
step = 10),
sliderInput(
"E",
"Edge width",
value = 0.05,
min = 0.01,
max = 5,
step = 0.01),
# 空白埋め込み
hr(),
# 文章埋め込み
p("Use the mouse zoom to zoom in/out."),
p("Click and drag to rotate.")
),
# output$globe埋め込み
mainPanel(
globeOutput("globe"),
hr(),
tabsetPanel(
tabPanel('result',
dataTableOutput("mytable1"))
),
hr(),
p("Copyright (c)", tags$a(href="http://kokitsuyuzaki.github.io", "<NAME>"), tags$a(hrep="http://bit.riken.jp", "RIKEN ACCC BiT"))
)
)
)
)
<file_sep>library("shiny")
library("threejs")
library("RSQLite")
library("RColorBrewer")
# 設定
options <- list(
img="/Users/tsuyusakikouki/Desktop/data/PubMed.db/data/world.topo.bathy.200412.3x5400x2700.jpg", # 背景
bodycolor="#0011ff", # 輪郭
emissive="#0011ff", # 暗さ?
lightcolor="#99ddff", #反射光
arcsColor='#ff00ff', # エッジの色
arcsHeight=0.4, # エッジの高さ
arcsOpacity=0.3, # エッジの透明度
atmosphere=FALSE, # 大気を加えるか(NASA画像の場合関係ない)
rotationlong=5.5, # 初期位置
rotationlat=0.5 # 初期位置
)
# ここの書き方は同じ(input = ui.Rから来る?, output = ui.Rに送られる?)
shinyServer(function(input, output) {
# cullの設定(reactiveで設定が毎回反映される?)
cull <- reactive({
out <- demodata.bc[intersect(
which(demodata.bc$YEAR >= input$Y[1]),
which(demodata.bc$YEAR <= input$Y[2])), ]
if(input$Keyword != ""){
out[grep(input$Keyword, out$TITLE), ]
}else{
out
}
})
# プロット
output$plot1 <- renderPlot({
barplot(table(demodata.bc$YEAR), col=rgb(0,1,0,0.5))
})
# valuesの設定
values <- reactive({
col <- brewer.pal(11, "Spectral")
names(col) <- c()
myinput <- cull() # cullで切り出されたデータ
value <- input$B * log10(myinput$Freq+1) / max(log10(myinput$Freq+1))
col <- col[floor(length(col) * (input$B - value) / input$B) + 1]
list(value=value, color=col, myinput=myinput)
})
# edgesの設定
edges <- reactive({
myinput <- values()$myinput # cullで切り出されたデータ
demo <- sapply(names(table(myinput$TITLE)), function(x){
authors <- which(x == myinput$TITLE)
if(length(authors) != 1){
comb <- t(combn(authors, 2)) # あらゆる著者の組み合わせ
# 緯度・経度に変換
out <- unlist(apply(comb, 1, function(xx){
longlat <- myinput[xx, 11:10]
as.numeric(c(longlat[1,], longlat[2, ]))
}))
out <- t(out)
out
}
})
edge <- c()
for(i in 1:length(demo)){
edge <- rbind(edge, demo[[i]])
}
edge
})
# レンダリング
output$mytable1 <- renderDataTable({
myinput <- cull()
myinput$LONGITUDE <- round(myinput$LONGITUDE, 2)
myinput$LATTITUDE <- round(myinput$LATTITUDE, 2)
myinput
})
output$globe <- renderGlobe({
v <- values()
e <- edges()
# globejsのオプション
args <- c(
options,
list(
lat=v$myinput$LATTITUDE,
long=v$myinput$LONGITUDE,
value=v$value,
color=v$color,
arcs=e,
arcsLwd=input$E)
)
# 出力
do.call(globejs, args=args)
})
})
| 2cac8fb470d80b2c64e4804121fb8dcc490e4beb | [
"R"
] | 2 | R | kokitsuyuzaki/coauthree | bf800ba4654a4e09090b75bc522c42245c23b580 | b911501ec0ebf2d4de4d66cb642057d5e7a4f10e |
refs/heads/master | <repo_name>rafaelcpalmeida/awesome-talks-ios<file_sep>/README.md
# awesome-talks-ios<file_sep>/Awesome Talks/Controller/ViewController.swift
//
// ViewController.swift
// Awesome Talks
//
// Created by <NAME> on 05/06/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import Apollo
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
apollo.fetch(query: AllVideosQuery(first: 10, search: " ")) { (result, error) in
print("Results:")
result?.data?.allVideoses.forEach({ (video) in
print(video.name)
})
print("Error:\n")
print(error)
}
apollo.fetch(query: AllSpeakersQuery()) { (result, error) in
result?.data?.allSpeakerses.forEach({ (speaker) in
print(speaker.name)
})
print("\n\n\n")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| a25adf79f8322daa0cc1854fceb1dcd2fef28194 | [
"Markdown",
"Swift"
] | 2 | Markdown | rafaelcpalmeida/awesome-talks-ios | 69263a7d9e389930f02c1c0ccf88539e4f5e88d5 | 1e0b33b92a5753e4dcb0644cc5d3355886d6f14d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.